将前一个值的一部分与其下一个值累积相加
Cumulatively sum a portion of a previous value with its next value
我想创建一个列,将相邻值与另一列中先前值的 80% 相加。所以,如果 x 列是 1、2、3...10,我希望 z 列是 1、2.8、5.24、8.192,等等
然而,这是我失败的尝试:
x <- c(1:10)
y <- c("")
df <- data.frame(x,y)
df1 <- df %>%
mutate(y = cumsum(x*0.8))
Result:
x y
1 1 0.8
2 2 2.4
3 3 4.8
4 4 8.0
5 5 12.0
6 6 16.8
7 7 22.4
8 8 28.8
9 9 36.0
10 10 44.0
我会使用 for
循环来执行此操作。首先初始化向量很重要,尤其是在处理大型数据集时。
# initialize
newx <- vector("numeric", length(df$x))
newx[1] <- df$x[1]
for(i in 2:length(df$x)){
newx[i] <- df$x[i] + (0.8 * newx[i-1])
}
newx
# [1] 1.00000 2.80000 5.24000 8.19200 11.55360 15.24288 19.19430 23.35544 27.68435 32.14748
加上purrr
,你可以做:
df %>%
mutate(y = accumulate(x, ~ .x * 0.8 + .y))
x y
1 1 1.00000
2 2 2.80000
3 3 5.24000
4 4 8.19200
5 5 11.55360
6 6 15.24288
7 7 19.19430
8 8 23.35544
9 9 27.68435
10 10 32.14748
尝试使用 Reduce
函数:
Reduce(function(last, current) current + last * .8, x = x, accumulate = T)
# [1] 1.00000 2.80000 5.24000 8.19200 11.55360 15.24288 19.19430 23.35544 27.68435 32.14748
我想创建一个列,将相邻值与另一列中先前值的 80% 相加。所以,如果 x 列是 1、2、3...10,我希望 z 列是 1、2.8、5.24、8.192,等等
然而,这是我失败的尝试:
x <- c(1:10)
y <- c("")
df <- data.frame(x,y)
df1 <- df %>%
mutate(y = cumsum(x*0.8))
Result:
x y
1 1 0.8
2 2 2.4
3 3 4.8
4 4 8.0
5 5 12.0
6 6 16.8
7 7 22.4
8 8 28.8
9 9 36.0
10 10 44.0
我会使用 for
循环来执行此操作。首先初始化向量很重要,尤其是在处理大型数据集时。
# initialize
newx <- vector("numeric", length(df$x))
newx[1] <- df$x[1]
for(i in 2:length(df$x)){
newx[i] <- df$x[i] + (0.8 * newx[i-1])
}
newx
# [1] 1.00000 2.80000 5.24000 8.19200 11.55360 15.24288 19.19430 23.35544 27.68435 32.14748
加上purrr
,你可以做:
df %>%
mutate(y = accumulate(x, ~ .x * 0.8 + .y))
x y
1 1 1.00000
2 2 2.80000
3 3 5.24000
4 4 8.19200
5 5 11.55360
6 6 15.24288
7 7 19.19430
8 8 23.35544
9 9 27.68435
10 10 32.14748
尝试使用 Reduce
函数:
Reduce(function(last, current) current + last * .8, x = x, accumulate = T)
# [1] 1.00000 2.80000 5.24000 8.19200 11.55360 15.24288 19.19430 23.35544 27.68435 32.14748