user3586183
user3586183

Reputation: 46

Subsetting in 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?

Upvotes: 3

Views: 160

Answers (2)

Alex Brown
Alex Brown

Reputation: 42872

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

Upvotes: 1

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

It sounds like you might be interested in exploring the rapply function (recursive lapply).

If I understand your question correctly, you could do something like this:

rapply(x[["l1"]], f=`[`, ...=c(1, 3))
# [1] 1 3

which is a little different than:

lapply(x[["l1"]], `[`, c(1, 3))
# [[1]]
# [1] 1 3

Upvotes: 0

Related Questions