115

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 5

183

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

lapply(x, `[[`, 1)
# [[1]]
# [1] 1
#
# [[2]]
# [1] 3
#
# [[3]]
# [1] 5
3
  • 1
    I agree it does look cooler. I was hoping there would be a shorter way to do this but I'll settle for a cooler way!
    – Alex
    Dec 6, 2013 at 16:47
  • @A5C1D2H2I1M1N2O1R2T1 I appreciate the cleanness and shortness, but can you explain the "[[" ? I didn't find anything useful in ?lapply Apr 27, 2017 at 10:01
  • 2
    @MehradMahmoudian, a better place to look would be "extract" (stat.ethz.ch/R-manual/R-devel/library/base/html/Extract.html). Apr 27, 2017 at 10:38
65

Another possibility uses the nice purrr library:

library(purrr)
map(x, 1)
3
  • 7
    For those who are wondering, this works since map interprets numerical values as extracting, like [[
    – qwr
    Dec 12, 2018 at 23:40
  • 2
    Using purrr::map() solves some errors by specifying the package.
    – Will M
    Apr 27, 2021 at 15:27
  • 1
    Seems more robust than the accepted answer regarding nested objects of different lengths.
    – Patrick
    Oct 13, 2023 at 13:13
12

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.

3

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
1
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.