iterative cumsum where sum determines the next position to be added

谁说我不能喝 提交于 2019-12-20 07:46:47

问题


I have a data.table as follows

set.seed(5)
x <- data.table(x=sample(1:20,15))

> x
     x
 1:  5
 2: 14
 3: 17
 4: 20
 5:  2
 6: 11
 7:  8
 8: 15
 9: 12
10: 16
11:  3
12: 18
13: 10
14:  4
15: 13

and I would like to start at 1 and cumulate values iteratively such that the value of cumsum() determines the next number to be added to the sum.

In the example I want to add the first value of x, here 5, then jump to value number 5 and add that, here 2, then jump to value number 5+2=7, here 8, then value number 5+2+8=15, here 13.

That is, I want to get a vector

> res
[1]  1  5  7 15

Has anyone any idea for this problem?


回答1:


We can use Reduce with accumulate = TRUE

accum <- Reduce(function(i, j) i + x$x[i], x$x, accumulate = TRUE)
c(1, accum[!is.na(accum)])
# [1]  1  5  7 15 28

or purrr::accumulate

library(purrr)

accum <- accumulate(x$x, ~ .x + x$x[.x])
c(1, accum[!is.na(accum)])
# [1]  1  5  7 15 28



回答2:


A base R solution:

i = 1
v = i
sum = 0
while (i <= nrow(x)) {
   v = c(v, i)
   sum = sum + x$x[i]
   i = sum
}



回答3:


Here's a function that takes how long you want your vector to be and produces a vector of that length:

recursiveadd<-function(x, n) {k<-x$x[1]
 for (i in 1:(n-1)) {
     k[i+1]<-sum(x$x[k[i]],k[i])
   }
 k
}

recursiveadd(x,4)
[1]  5  7 15 28


来源:https://stackoverflow.com/questions/53780944/iterative-cumsum-where-sum-determines-the-next-position-to-be-added

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!