选择嵌套列表的第一个元素

假设我有一个这样的清单:

x = list(list(1,2), list(3,4), list(5,6))

我想要一个只包含嵌套列表的第一个元素的列表。我可以像这样返回另一个列表

x1 = lapply(x, function(l) l[[1]])

这个有快捷记号吗?

110135 次浏览

Not much of a shortcut, but you can do this:

lapply(x, `[[`, 1)
# [[1]]
# [1] 1
#
# [[2]]
# [1] 3
#
# [[3]]
# [1] 5

For your example list you can just do:

unlist(x)[ c(TRUE,FALSE) ]

but that depends on each sublist having exactly 2 elements.

If there are different numbers of elements then you could first do an sapply to calculate the lengths, then compute the corresponding 1st element positions (see cumsum), then select those values from the unlisted list. But by that time the accepted answer is probably much simpler.

If all the sublists have the same length (but could be different from 2) then you could do something like:

do.call( rbind, x)[,1]

or some other cast to a common object. But I doubt that this would be as efficient as the lapply approach.

Another possibility uses the nice purrr library:

library(purrr)
map(x, 1)

We can use pluck from rvest which selects 1st element from each nested list

rvest::pluck(x, 1)
#[[1]]
#[1] 1


#[[2]]
#[1] 3


#[[3]]
#[1] 5

Note that this gives different result with pluck from purrr which selects 1st element (x[[1]])

purrr::pluck(x, 1)


#[[1]]
#[1] 1


#[[2]]
#[1] 2

Not exactly a short notation, but this can also be done with a fold:

Reduce(function(a, b) c(a, b[1]), x, init = c())


# [[1]]
# [1] 1
#
# [[2]]
# [1] 3
#
# [[3]]
# [1] 5