arebearit arebearit - 2 months ago 10
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

c(a[[2]][[2]],b[[2]][[2]])
, but how can you do this without writing the names of each list and the respective indexing brackets?

Input:

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

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.