【发布时间】:2014-01-23 00:10:13
【问题描述】:
使用 R:
我有一个长度为 n 的向量列表,对应于一个长度为 n 的 id 向量。所以列表中的每个向量都有 m 个 id。我还有一个值向量,长度为 m:
L1 = c(1,65,23)
L2 = c(1,23,45)
L3 = c(45,23)
L4 = c(45,65)
V2 = list(L1,L2,L3,L4)
IDs = c(1, 23, 45, 65)
Values = c(400, 500, 100, 150)
dat = data.frame(IDs, Values)
我想从相应的(按索引)列表中减去每个值。 在一个循环中,这将是这样的:
testFun = function(dat){
y = list()
for (i in 1:nrow(dat)){
y[[i]] = dat$Value[i] - dat$Value[which(dat$IDs %in% V2[[i]])]
}
return(y)
}
testFun(dat)
基本上,这是可行的,但不能很好地扩展。 任何帮助将非常感激!谢谢
【问题讨论】:
-
什么是
y? (您的示例不可重现) -
@mnel y = list() 抱歉遗漏
-
注意,你的
[ ]中不需要which
标签: r performance list for-loop