我想转置一个嵌套列表。假设给出了以下嵌套列表x:
a <- list(c("a","b","c","d"))
b <- list(c("d","c","b","a"))
c <- list(c("4","3","2","1"))
d <- list(c("1","2","3","4"))
x <- list(a,b,c,d)
结果应该是一个嵌套列表,其中原始列表x的第一列是第一个嵌套列表元素,即“a”,“d”,“4”,“1”,第二列是第二列嵌套列表元素,即“b”,“c”,“3”,“2”等。最后,结构是原始结构的转置。怎么能在R?
中完成答案 0 :(得分:4)
我们也可以不用lapply
(使用矩阵):
relist(matrix(unlist(x), ncol = 4, byrow = T), skeleton = x)
<强>基准强>
library(microbenchmark)
a <- list(c("a","b","c","d"))
b <- list(c("d","c","b","a"))
c <- list(c("4","3","2","1"))
d <- list(c("1","2","3","4"))
x <- list(a,b,c,d)
f_akrun <- function(x) {m1 <- do.call(rbind, lapply(x, function(y) do.call(rbind, y)));relist(m1, skeleton = x);}
f_m0h3n <- function(x) {relist(matrix(unlist(x), ncol = length(x[[1]][[1]]), byrow = T), skeleton = x)}
setequal(f_akrun(x), f_m0h3n(x))
# [1] TRUE
microbenchmark(f_akrun(x), f_m0h3n(x))
# Unit: microseconds
# expr min lq mean median uq max neval
# f_akrun(x) 135.591 137.301 144.3545 138.585 148.422 334.484 100
# f_m0h3n(x) 110.782 111.638 116.5477 112.493 117.412 212.153 100
答案 1 :(得分:3)
我们可以尝试
m1 <- do.call(rbind, lapply(x, function(y) do.call(rbind, y)))
relist(m1, skeleton = x)