Hi: I have an xts object as such:
AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
2013-09-09 505.00 507.92 503.48 506.17 12116200 506.17
2013-09-10 506.20 507.45 489.50 494.64 26490200 494.64
2013-09-11 467.01 473.69 464.81 467.71 32031600 467.71
2013-09-12 468.50 475.40 466.01 472.69 14409400 472.69
I try to calculate a rolling mean and attach it to a new column as such
AA["AAPL.Rolling"] <- rollmean(AA[,"AAPL.Adjusted"],12)
Although the rollmean(AA[,"AAPL.Adjusted"],12)
works on its own; I get an error message when I try to attach to a new column.
** also what makes this hard is that the new rolling mean will not have data in every row since the first 12 should be "NA" Can anyone help? Thank you much.
You can't add columns to zoo/xts objects like that. You can use the $<-
function though.
AA$AAPL.Rolling <- rollmean(AA[,"AAPL.Adjusted"], 12)
Also note that rollmean
is center-aligned by default. You may want to use rollmeanr
to get right-alignment. Padding with NA
will happen automatically, since you're merging the rolling mean with the original object. Use fill=NA
if you want rollmean
to add them explicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With