简体   繁体   English

R:根据向量中具有相同名称的值从列表中选择元素

[英]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我有

  • a list of matrices with different numbers of rows,具有不同行数的矩阵列表,
  • a vector of integer values with the same names as the list's,一个与列表同名的整数值向量,
  • a list of names that appear in the list and vector above,出现在上面的列表和向量中的名称列表,
  • an integer variable telling which column to choose from those matrices.一个整数变量,告诉从这些矩阵中选择哪一列。

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.同样重要或相关: mylistmyvec名称的顺序可以不同,所以我不能依赖位置索引。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM