[英]How to access list in a list by character name in a loop?
I have a list X of three elements.我有一个包含三个元素的列表 X。 Each element X[[i]] is a list of two – X1 and X2.每个元素 X[[i]] 是一个包含两个元素的列表——X1 和 X2。
I want to construct a list X_new which would be a list of two elements X1 and X2, each element X_new[[i]] is a list of three.我想构造一个列表 X_new,它是一个包含两个元素 X1 和 X2 的列表,每个元素 X_new[[i]] 是一个包含三个元素的列表。
This works perfectly fine:这工作得很好:
X_new <- vector(mode = "list", length = 2)
X_new[[1]] <- lapply(X, function(x) x$X1)
X_new[[2]] <- lapply(X, function(x) x$X2)
But what if instead of 2 I have n ?但是如果我有n而不是 2 呢? I tried this我试过这个
X_new <- vector(mode = "list", length = n)
ind <- names(X[[1]])
for (i in 1:n) {
X[[i]] <- lapply(X, function(x) x$ind[i])
}
but it doesn't work, I just get null lists.但它不起作用,我只是得到空列表。
We can use transpose
from purrr
我们可以使用来自purrr
transpose
library(purrr)
X_new <- transpose(X)
-output -输出
X_new
#[[1]]
#[[1]][[1]]
#[1] "a"
#[[1]][[2]]
#[1] "a"
#[[1]][[3]]
#[1] "a"
#[[2]]
#[[2]][[1]]
#[1] "b"
#[[2]][[2]]
#[1] "b"
#[[2]][[3]]
#[1] "b"
Refer to this discussion for an answer.请参阅此讨论以获取答案。 In short, you can use paste inside the [[]] list brackets.简而言之,您可以在 [[]] 列表括号内使用paste 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.