-2

I want to calculate a running sum of the next 5 rows. In this case, on row 1 it will show the sum of numbers from row 2 to row 6. The last 5 rows of the data frame can be filled with NA.

The data looks like this

enter image description here

And the ideal result would look like

enter image description here

Thank you!

zx8754
  • 52,746
  • 12
  • 114
  • 209
Xavier Tran
  • 27
  • 1
  • 3

2 Answers2

3

First, please consider to read How to make a great R reproducible example? and add sample data using dput next time.

df <- data.frame(t = c(1,3,5,2,1,3,4,6,7,2,1))

library(zoo)
library(dplyr)

df$V2 <- rollsum(lead(df$t), 5, align = "left", fill = NA)
df

   t V2
1  1 14
2  3 15
3  5 16
4  2 21
5  1 22
6  3 20
7  4 NA
8  6 NA
9  7 NA
10 2 NA
11 1 NA
Lennyy
  • 5,932
  • 2
  • 10
  • 23
1

You can use rollsum from the zoo package.

library(zoo)
rollsum(df$column, 5)

The second argument is the number of lines to sum, here it is five.

Natheer Alabsi
  • 2,790
  • 4
  • 19
  • 28