Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subsetting in R

Tags:

r

x <- list(l1=list(1:4),l2=list(2:5),l3=list(3:8))

I know [] is used for extracting multiple elements and [[]] is used to extract a single element in a list inside a list. I need help in extracting multiple elements in a list inside another list. For example I need to extract 1,3 from list l1 which is inside another list?

like image 466
user3586183 Avatar asked May 25 '26 22:05

user3586183


1 Answers

For full details, see help(Extract) which covers [[ and [

The [[ operator can walk/search nested lists in a single step, by providing a vector of names OR indices (a path):

> y = list(a=list(b=1))
> y[[c("a","b")]]
[1] 1
> y[[c(1,1)]]
[1] 1

You can't mix names and indices:

> y[[c("a",1)]]
NULL

It seems like you are asking a different question, since your inner lists are not named.

Here's a solution using only numeric indices:

> x[[c(1,1)]]
[1] 1 2 3 4
> x[[c(1,1)]][c(1,3)]
[1] 1 3

the first 1 gets the first element of the first list. The second 1 unwraps it to expose the vector inside.

This might be useful if your real use case involves more complex paths, but to avoid surprising other programmers, in the given example the following...

x[["l1"]][[1]][c(1,3)]

...is probably preferable. The second 1 unwraps the list.

In your case, the following is also equivalent

unlist(x[["l1"]])[c(1,3)]
like image 140
Alex Brown Avatar answered May 28 '26 14:05

Alex Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!