[英]Create a list of named lists from three vectors in R
I'm trying to combine three vectors into a list of lists, with one vector being the indexes for the list. 我正在尝试将三个向量组合成一个列表列表,其中一个向量是列表的索引。
Given 特定
names<-c("a","b","c","d")
id1<-c(1,1,2,2)
id2<-c(3,4,5,6)
I would like to build a list looking like this: 我想建立一个如下所示的列表:
mylist <- list("a" = list(1,3), "b" = list(1,4), "c" = list(2,5), "d" = list(2,6))
I think you are looking for Map
我想你正在寻找Map
l <- Map(list, id1, id2) # thanks to @thelatemail for suggested improvement
names(l) <- names
identical(mylist, l)
# TRUE
You can do this using mapply
and the c
function to concatenate the vectors element-wise. 你可以使用mapply
和c
函数来连接元素。 setNames
conveniently names the result as the function returns: setNames
在函数返回时方便地命名结果:
ll <- setNames( mapply( c , id1 , id2 , SIMPLIFY = FALSE ) , names )
#$a
#[1] 1 3
#$b
#[1] 1 4
#$c
#[1] 2 5
#$d
#[1] 2 6
or perhaps taking advantage of mapply()
's' USE.NAMES
argument you can name the first vector to do this, achieving the same result without setNames
: 或者也许利用mapply()
的' USE.NAMES
参数,你可以命名第一个向量来做到这一点,在没有setNames
情况下实现相同的结果:
names(id1) <- names
mapply( c , id1 , id2 , SIMPLIFY = FALSE )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.