根据另一列中指定的前导 n 值计算列上数据框中的滚动总和

问题描述 投票:0回答:2

我正在尝试计算 b 列中指定的 n 个主值的“a”列中值的滚动总和,以便我得到 c 列中指定的答案

enter image description here

我尝试使用slide_sum,但是当我将参数“after”的值作为b列传递时,它会抛出错误。

d %>% mutate(c = slide_sum(a, after = b))
Error:
Error in `mutate()`:
ℹ In argument: `c = slide_sum(a, after = b)`.
Caused by error:
! `after` must have size 1, not 10.
Run `rlang::last_trace()` to see where the error occurred.
r dplyr
2个回答
2
投票

这里是用

purrr
代替
slider
的选项:

df %>%
 mutate(c = map2_int(.x = seq_along(a), 
                     .y = b,
                     ~ sum(a[.x:(.x + .y - 1)], na.rm = TRUE)))

       a     b     c
   <int> <dbl> <int>
 1     1     2     3
 2     2     2     5
 3     3     2     7
 4     4     3    15
 5     5     1     5
 6     6     2    13
 7     7     2    15
 8     8     2    17
 9     9     3    19
10    10     1    10

0
投票

在基数R中:

i <- sequence(df$b)
j <- cumsum(i == 1)
transform(df, c = tapply(a[i + j - 1], j, sum, na.rm =TRUE))

    a b  c
1   1 2  3
2   2 2  5
3   3 2  7
4   4 3 15
5   5 1  5
6   6 2 13
7   7 2 15
8   8 2 17
9   9 3 19
10 10 1 10
© www.soinside.com 2019 - 2024. All rights reserved.