Plotting Moving Average

I am trying to calculate the moving average of some time series data. I would like to calculate the moving average every 9 years, for the variable phosphorus yield. My code is below, and the error I am receiving is as follows:
Error: Aesthetics must be either length 1 or the same as the data (4080): x, y

P_yiled_m<-rollmean(P_yield_time$P_Yield, 9)
Year_m<-rollmean(P_yield_time$Year, 9)
Ptime = ggplot(P_yield_time, aes(x=Year_m, y=Moving, color=as.factor(Nutrient_Management))) + facet_wrap(~Climate+as.factor(Perennial_Cover))+
  geom_line()+
  theme(panel.background = element_rect(fill = "white", colour = "grey50"),
        axis.text=element_text(size=12, color = "black"),
        axis.title=element_text(size = 12),
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank())+
  xlab("Year") + ylab("Phosphorus Yield [kg/ha?]") + 
  scale_color_manual(values=c('#edf8e9','#bae4b3','#74c476','#238b45'))+
  xlim(2010,2065)
Ptime

Thanks!

Hello,
Can you provide a reprex of your issue ? This would make it easier to help you.

I suspect that the object Year_m has a shorter length than the number of rows in your data frame. Use

length(Year_m)
nrow(P_yield_time)

to check that.
If that does not help, a reprex, as suggested, would be very helpful.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.