简体   繁体   English

条件向量化到向量命名列表的匹配

[英]conditional vectorized matching to named list of vectors

I have a named list of vectors, y. 我有一个向量的命名列表,y。 The names of the list correspond to the values of variable, x. 列表的名称对应于变量x的值。 I need to return the value of the vector in y that matches the value of x at position i. 我需要返回y中与位置i处的x值匹配的向量的值。 For example, if x == "b" at index 25, I expect to return the 25th value of the "b" vector contained in the list y. 例如,如果在索引25处x ==“ b”,则我希望返回列表y中包含的“ b”向量的第25个值。

This is my current solution: 这是我目前的解决方案:

x <- sample(letters[1:4], 100, replace = T)

y <- list("a"=rnorm(100), "b"=rnorm(100), "c"=rnorm(100))

i <- match(x, names(y))
m <- sapply(i, function(i) {out <- rep(0,3); out[i] <- 1; out})

final <- apply(t(m) * do.call(cbind, y), 1, sum)

I am hoping for something more idiomatic. 我希望有一些更惯用的东西。 As part of the solution, the answer handle cases where values in x do not appear in the names of y. 作为解决方案的一部分,答案可以处理x中的值未出现在y名称中的情况。

The real world use case I am trying to solve is the case where I have several segmented model predictions applied to the entire population that I need to assign to their appropriate segment. 我要解决的实际用例是将几个细分模型预测应用于整个人口的情况,需要将其分配给相应的细分。

EDIT Also, trying to avoid the clunky usage of ifelse . 编辑也,试图避免ifelse的笨拙用法。 Since the names are known, I shouldn't have to specify them manually. 由于名称是已知的,因此我不必手动指定它们。

使用带有二维索引的矩阵子集,您可以简单地执行

do.call(cbind, y)[cbind(1:length(i), i)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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