[英]Convert a list into a nested named vector with the same length in R
Suppose for the list x
假设列表
x
x <- list(a = c(1, 2, 3), b = c(4, 5))
I want to get back a named vector with the same length that looks like我想取回一个具有相同长度的命名向量,看起来像
c(a = c(1, 2, 3), b = c(4, 5))
My first thoughts use a for loop我的第一个想法是使用 for 循环
out <- vector(typeof(x), length(x))
x_names <- names(x)
for (i in seq_along(x)) {
out[i] <- x[[i]]
}
names(out) <- c(x_names)
Is there a way to do this without a for loop?有没有办法在没有 for 循环的情况下做到这一点?
How about using do.call()
with c()
?如何将
do.call()
与c()
一起使用?
do.call(c,x)
or或者
unlist(x)
Output Output
a1 a2 a3 b1 b2
1 2 3 4 5
lapply(1:length(x) , \(i) unlist(x[i]))
#> [[1]]
#> a1 a2 a3
#> 1 2 3
#>
#> [[2]]
#> b1 b2
#> 4 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.