R根据索引列值将函数应用于数据

时间:2015-03-11 19:34:50

标签: r data.table vectorization

示例:

require(data.table)
example = matrix(c(rnorm(15, 5, 1), rep(1:3, each=5)), ncol = 2, nrow = 15)
example = data.table(example)
setnames(example, old=c("V1","V2"), new=c("target", "index"))
example


threshold = 100

accumulating_cost = function(x,y) { x-cumsum(y) }
whats_left = accumulating_cost(threshold, example$target)
whats_left

我希望whats_leftthresholdexample$targetexample$index = 1,以及2和3的累积值之和组成。我使用了以下for循环:

rm(whats_left)

whats_left = vector("list")
for(i in 1:max(example$index)) {
  whats_left[[i]] = accumulating_cost(threshold, example$target[example$index==i])
}

whats_left = unlist(whats_left)
whats_left

plot(whats_left~c(1:15))

我知道循环不是R中的恶魔,但是我习惯于在可能的情况下使用矢量化(包括远离apply,作为for循环包装器)。我很确定这里有可能,但我无法弄清楚如何做到这一点。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

您要做的就是通过 index累积费用。因此,您可能希望使用

中的by参数
example[, accumulating_cost(threshold, target), by = index]