I am trying to run some moving averages over a dataframe with multiple groups. I am interested in the last SMA over a series of 20 for each group. The second example below crashes because one series (C) only has 10 values. What do I need to do to make this not crash? C needs to be kept in the result. I'm happy for C to be NA in the result.
df <- data.frame(x=c(rep("A", 30), rep("B", 30),rep("C", 10)), y=rnorm(n = 70, 100, 20))
df
ddply(df, .(x), summarise, SMA10= tail(SMA(y, n=10), 1)) # Works because all groups have at least 10 values
ddply(df, .(x), summarise, SMA10= tail(SMA(y, n=20), 1)) # Does not work
Error in runSum(x, n) : n = 20 is outside valid range: [1, 10]