[英]R: choose elements from list based on values in vector with same names
[Probably this question already has an answer here, but I didn't manage to find one, also because I have some difficulty in formulating it concisely. 【大概这个问题这里已经有了答案,但是我没能找到答案,也是因为我在简明扼要地制定它时遇到了一些困难。 Suggestions for reformulating the title of the question are appreciated.]
对重新表述问题标题的建议表示赞赏。]
I have我有
Let's construct, as a working example:让我们构建,作为一个工作示例:
mynames <- c('a', 'c')
mylist <- list(a=matrix(1:4,2,2), b=matrix(1:6,3,2), c=matrix(1:8,4,2))
myvec <- 2:4
names(myvec) <- names(mylist)
chooseCol <- 2
I'd like to construct a vector having as elements the rows taken from myvec
and column chooseCol
, for the names appearing in mynames
.我想构成具有作为元素取自行的矢量
myvec
和列chooseCol
,对于出现在名称mynames
。 My attempt is我的尝试是
sapply(mynames, function(elem){mylist[[elem]][myvec[elem], chooseCol]})
which correctly yields正确产生
a c
4 8
but I was wondering if there's a faster, base
(non- tidyverse
) method of doing this.但我想知道是否有更快的
base
(非tidyverse
)方法来执行此操作。
Also important or relevant: the order of the names in mylist
and myvec
can be different, so I can't rely on position indices.同样重要或相关:
mylist
和myvec
名称的顺序可以不同,所以我不能依赖位置索引。
I would use mapply
-我会使用
mapply
-
mapply(function(x, y) x[y, chooseCol], mylist[mynames], myvec[mynames])
#a c
#4 8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.