Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ADD a new column into an XTS object

Tags:

r

xts

quantmod

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.

like image 692
Ahdee Avatar asked Oct 25 '13 21:10

Ahdee


Video Answer


1 Answers

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.

like image 80
Joshua Ulrich Avatar answered Sep 21 '22 08:09

Joshua Ulrich