Select first element of nested list

Viewed 107608

Let's say I have a list like this:

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

I would like a list that contains only the first elements of the nested list. I can do this by returning another list like so

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

Is there shortcut notation for this?

5 Answers

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
Related