1

Example:

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

I want whats_left to consist of the difference between threshold and the cumulative sum of values in example$target for which example$index = 1, and 2, and 3. So I used the following for loop:

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))

I know for loops aren't the devil in R, but I'm habituating myself to use vectorization when possible (including getting away from apply, being a for loop wrapper). I'm pretty sure it's possible here, but I can't figure out how to do it. Any help would be much appreciated.

4
  • 1
    If you already using data.table you might as well use it most basic capabilities, more specifically, the by argument. Try example[, accumulating_cost(threshold, target), by = index] Commented Mar 11, 2015 at 21:17
  • That's it! These basic capabilities are exactly what I'm struggling to learn. Thanks! Care to make this the answer? Commented Mar 11, 2015 at 21:19
  • 1
    @NigelStackhouse, check the new HTML vignettes. Keep track of this post for the vignettes that are planned. Commented Mar 11, 2015 at 21:24
  • Very cool! Thanks @Arun, that will help me a lot. Commented Mar 11, 2015 at 21:26

1 Answer 1

3

All you trying to do is accumulate the cost by index. Thus, you might want to use the by argument as in

example[, accumulating_cost(threshold, target), by = index]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.