suppose a, b , c matrices. , have list of them this:
list(a,list(b,c)) i want convert this:
list(a,b,c) the unlist function convert matrices vectors!
for example:
a=matrix(1:10,nrow=2) b=list(a,list(a,a)) unlist(b)
here recursive implementation:
flatten2 <- function(x) if(is.list(x)) reduce(c, lapply(x, flatten2)) else list(x) then:
str(flatten2(b)) # list of 3 matrices: # list of 3 # $ : int [1:2, 1:5] 1 2 3 4 5 6 7 8 9 10 # $ : int [1:2, 1:5] 1 2 3 4 5 6 7 8 9 10 # $ : int [1:2, 1:5] 1 2 3 4 5 6 7 8 9 10 and more complex:
c <- list(a, list(list(a, a), a)) str(flatten2(c)) # list of 4 # $ : int [1:2, 1:5] 1 2 3 4 5 6 7 8 9 10 # $ : int [1:2, 1:5] 1 2 3 4 5 6 7 8 9 10 # $ : int [1:2, 1:5] 1 2 3 4 5 6 7 8 9 10 # $ : int [1:2, 1:5] 1 2 3 4 5 6 7 8 9 10 also, "wordier" faster version (this 1 tested pierre):
flatten <- function(x) { res <- list() for(i in x) res <- c(res, if(is.list(i)) recall(i) else list(i)) res } you make flatten2 little faster replacing reduce do.call, little less cute. flatten remains fastest change.
Comments
Post a Comment