'Add rollapply vector to a data frame
I have the following data:
Year Month Total
2015 1 123
2015 2 435
2015 3 543
which are total by month over a three year period. I used rollapply to calculate a rolling cumulative total. Like below:
rollapply(results$Total, 12, sum)
however this returns a vector which (obviously) has 11 fewer observations and no index value.
How do I join it back to the dataframe as a column indexed correctly?
Solution 1:[1]
You can add the vector to your main dataframe as a new column:
results$rolling <- rollapply(results$Total, width = 3, sum , fill = NA)
then you should get the results as:
Year Month Total rolling
2015 1 123 na
2015 2 435 na
2015 3 543 1101
I changed the window size to 3 just for illustration in this example!
Solution 2:[2]
Use library zoo. val is for the column where you want to get the sum
library(zoo)
rsum <- function(df, val, k) {
df %>%
mutate(
rsum = rollapply(val, k, FUN = sum, partial=T, align="center"))
)
}
df %>% rsum(., .$col, 12)
if there's groupping information, then
df %>% group_by(a,b,c) %>% group_modify(~ { .x %>% rsum(.x$col,12)})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user3322581 |
| Solution 2 |
