It's much better if you post a minimal reproducible example i.e. only the code required to illustrate the specific problem that you are encountering. Asking people to read through your entire code and find out what's wrong isn't a good approach (nor is it possible without a reprex).
Since you haven't provided a reprex, I'll illustrate how to calculate rolling means on the iris
data set. You can adapt it to your sales
data frame.
library(zoo, warn.conflicts = FALSE)
iris$Sepal.Length.Mean <- rollmean(iris$Sepal.Length, k = 2, fill = NA, align = "right")
head(iris[, c(1, 6)], n = 10)
#> Sepal.Length Sepal.Length.Mean
#> 1 5.1 NA
#> 2 4.9 5.00
#> 3 4.7 4.80
#> 4 4.6 4.65
#> 5 5.0 4.80
#> 6 5.4 5.20
#> 7 4.6 5.00
#> 8 5.0 4.80
#> 9 4.4 4.70
#> 10 4.9 4.65
Created on 2020-04-30 by the reprex package (v0.3.0)
Note that the first value of Sepal.Length.Mean
has been filled with NA
. You control its value & position by changing the fill
and align
parameters respectively.
As for your second question, I think a good way to diagnose would be to run each line of code step-by-step after reading each Excel file and observe how the data frame is changing. That should help narrow down the issue.