简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM