iterative cumsum where sum determines the next position to be added

后端 未结 3 1205
天涯浪人
天涯浪人 2021-01-29 07:17

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         


        
相关标签:
3条回答
  • 2021-01-29 07:53

    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
    
    0 讨论(0)
  • 2021-01-29 08:03

    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
    
    0 讨论(0)
  • 2021-01-29 08:12

    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
    }
    
    0 讨论(0)
提交回复
热议问题