arebearit arebearit - 1 year ago 68
R Question

Dynamic, General Indexing in R

Is there a way to index across many lists, data frames, etc., in R? That is to say, generally? For example, you could retrieve a list of the second element of the second element of lists a & b via

, but how can you do this without writing the names of each list and the respective indexing brackets?


l1 <- as.list(c(1,2,3,4,5))
l2 <- as.list(c(6,7,8,9,10))
a <- list(l1,l2)

l4 <- as.list(c(1,2,3,4,5))
l5 <- as.list(c(6,7,8,9,10))
b <- list(l4,l5)

Desired output:

[1] 7 7

I know that you could create a list of only upper nested lists - assuming the same naming convention - with this:

nol <- objects()
nol <- grep("^[a-z]$", nol, value=TRUE)

I just don't know how to apply across this list.

Answer Source

You can do this via vapply as follows:

vapply(mget(nol), function(x) x[[2]][[2]], FUN.VALUE = double(1), USE.NAMES = FALSE)

The idea here is that mget gives you a list of your objects. you could also create it by list(a,b). And the anonymous function function(x) x[[2]][[2]] returns your values.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download