Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)

I'm trying to use R to calculate the moving average over a series of values in a matrix. The normal R mailing list search hasn't been very helpful though. There doesn't seem to be a built-in function in R will allow me to calculate moving averages. Do any packages provide one? Or do I need to write my own?

1 Answer

0 votes
by

You can use the functions from the zoo package to find the rolling means/maximums/medians/sums as follows:

library("zoo")

z.Date <- as.Date(paste(2017, rep(5:9), sample(1:28, 10), sep = "-"))

z.Date

x <- zoo(rnorm(12), z.Date)

rollmean(z, 3)

rollmax(z, 3)

rollmedian(z, 3)

rollsum(z, 3)

Output:

rollmean(z, 3)

      v1 v2 v3

 [1,]  2 2 2

 [2,]  3 3 3

 [3,]  4 4 4

 [4,]  5 5 5

 [5,]  6 6 6

 [6,]  7 7 7

 [7,]  8 8 8

 [8,]  9 9 9

 [9,] 10 10 10

[10,] 11 11 11

[11,] 12 12 12

[12,] 13 13 13

[13,] 14 14 14

[14,] 15 15 15

[15,] 16 16 16

[16,] 17 17 17

[17,] 18 18 18

[18,] 19 19 19

You can also use functions available in TTR and forecast packages to calculate moving averages in R.

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...