简体   繁体   中英

Combining deeply-nested vectors from multiple lists

I wish to combine equivalent, deeply-nested columns from all elements of a reasonably long list. What I would like to do, though it's not possible in R, is this:

combined.columns <- my.list[[1:length(my.list)]]$my.matrix[,"my.column"]

The only thing I can think of is to manually type out all the elements in cbind() like this:

combined.columns <- cbind(my.list[[1]]$my.matrix[,"my.column"], my.list[[2]]$my.matrix[,"my.column"], . . . )

This answer is pretty close to what I need, but I can't figure out how to make it work for the extra level of nesting.

There must be a more elegant way of doing this, though. Any ideas?

Assuming all your matrices have the same column name you wish to extract you could use sapply

set.seed(123)
my.list <- vector("list")
my.list[[1]] <- list(my.matrix  = data.frame(A=rnorm(10,sd=0.3), B=rnorm(10,sd=0.3)))
my.list[[2]] <- list(my.matrix  = data.frame(C=rnorm(10,sd=0.3), B=rnorm(10,sd=0.3)))
my.list[[3]] <- list(my.matrix  = data.frame(D=rnorm(10,sd=0.3), B=rnorm(10,sd=0.3)))

sapply(my.list, FUN = function(x) x$my.matrix[,"B"])

Free data:

myList <- list(list(myMat = matrix(1:10, 2, dimnames=list(NULL, letters[1:5])),
                    myVec = 1:10),
               list(myMat = matrix(10:1, 2, dimnames=list(NULL, letters[1:5])),
                    myVec = 10:1))

We can get column a of myMat a few different ways. Here's one that uses with .

sapply(myList, with, myMat[,"a"])
#      [,1] [,2]
# [1,]    1   10
# [2,]    2    9 

This mapply one might be better for a more recursive type problem. It works too and might be faster than sapply .

mapply(function(x, y, z) x[[y]][,z] , myList, "myMat", "a")
#      [,1] [,2]
# [1,]    1   10
# [2,]    2    9

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