To extract only first element from a list, we can use sapply function and access the first element with double square brackets. For example, if we have a list called LIST that contains 5 elements each containing 20 elements then the first sub-element can be extracted by using the command sapply(LIST,"[[",1).
You can access a nested list by negative indexing as well. Negative indexes count backward from the end of the list. So, L[-1] refers to the last item, L[-2] is the second-last, and so on.
Approach #2 : Using zip and unpacking(*) operator This method uses zip with * or unpacking operator which passes all the items inside the 'lst' as arguments to zip function. Thus, all the first element will become the first tuple of the zipped list. Returning the 0th element will thus, solve the purpose.
Not much of a shortcut, but you can do this:
lapply(x, `[[`, 1)
# [[1]]
# [1] 1
#
# [[2]]
# [1] 3
#
# [[3]]
# [1] 5
Another possibility uses the nice purrr
library:
library(purrr)
map(x, 1)
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 unlist
ed 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With