I wanted to use movavg from the pracma package (with moving average of 6) on iris and have used the following and variations of the code with no luck. For example the below gives: Error in movavg(x = data, n = 6) : is.numeric(x) is not TRUE
The same approach can be used with other functions. I haven't used the pracma library but here's how to calculate rolling means using zoo.
library(zoo)
iris %>%
group_by(Species) %>%
mutate_all(.funs = rollmean, k = 6, fill = NA)
# A tibble: 150 x 5
# Groups: Species [3]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
<dbl> <dbl> <dbl> <dbl> <fct>
1 NA NA NA NA setosa
2 NA NA NA NA setosa
3 4.95 3.38 1.45 0.233 setosa
4 4.87 3.37 1.45 0.25 setosa
5 4.88 3.43 1.47 0.25 setosa
6 4.83 3.38 1.48 0.25 setosa
k defines the width of the rolling window as you'd expect. The fill parameter is required to ensure that the output contains the same number of rows as the input. You can change the fill value to suit your requirement.
Note: By default rollmean uses a center-aligned window. As a result, you will find rows of NA values at the top and bottom of the output data frame. If you'd rather have the NAs at the beginning instead, you can pass the align parameter like so:
iris %>%
group_by(Species) %>%
mutate_all(.funs = rollmean, k = 6, fill = NA, align = "right")
# A tibble: 150 x 5
# Groups: Species [3]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
<dbl> <dbl> <dbl> <dbl> <fct>
1 NA NA NA NA setosa
2 NA NA NA NA setosa
3 NA NA NA NA setosa
4 NA NA NA NA setosa
5 NA NA NA NA setosa
6 4.95 3.38 1.45 0.233 setosa