迭代累加,其中sum确定要添加的下一个位置 [英] iterative cumsum where sum determines the next position to be added

查看:97
本文介绍了迭代累加,其中sum确定要添加的下一个位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个data.table如下

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

,我想从<$ c $开始c> 1 并迭代累积值,以使 cumsum()的值确定要添加到总和的下一个数字。

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.

在该示例中,我想添加 x 的第一个值,此处为5,然后跳转到值5,并将其添加,在这里2,然后跳转到值编号 5 + 2 = 7 ,在这里8,然后跳转到值编号 5 + 2 + 8 = 15 ,这里是13。

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?

推荐答案

我们可以将 Reduce 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

purrr :: accumulate

library(purrr)

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

这篇关于迭代累加,其中sum确定要添加的下一个位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆