Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first element of nested list

Tags:

list

r

People also ask

How do you extract the first element of a list?

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).

How do I access the elements of a nested list?

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.

How do you extract an element from a nested list in Python?

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 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.


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