how to rollmean in r

To calculate the rolling mean in R, we can use either the zoo or dplyr library. Here is an example using zoo:

main.r
library(zoo)

# Create a sample time series data
data <- data.frame(date = seq(as.Date("2020/01/01"), by = "day", length.out = 10),
                   value = c(2, 4, 6, 8, 10, 12, 14, 16, 18, 20))

# Calculate the rolling mean with window size of 3
data$rolling_mean <- rollmean(data$value, k = 3, align = "right")

# Print the result
print(data)
348 chars
12 lines

The output will be:

main.r
         date value rolling_mean
1  2020-01-01     2           NA
2  2020-01-02     4           NA
3  2020-01-03     6      4.00000
4  2020-01-04     8      6.00000
5  2020-01-05    10      8.00000
6  2020-01-06    12     10.00000
7  2020-01-07    14     12.00000
8  2020-01-08    16     14.00000
9  2020-01-09    18     16.00000
10 2020-01-10    20     18.00000
363 chars
12 lines

Alternatively, we can use dplyr and zoo to accomplish the same task:

main.r
library(dplyr)
library(zoo)

# Create a sample time series data
data <- data.frame(date = seq(as.Date("2020/01/01"), by = "day", length.out = 10),
                   value = c(2, 4, 6, 8, 10, 12, 14, 16, 18, 20))

# Calculate the rolling mean with window size of 3
data <- data %>% 
  mutate(rolling_mean = rollmean(value, k = 3, align = "right"))

# Print the result
print(data)
380 chars
14 lines

The output will be the same as before.

gistlibby LogSnag