14

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.

Ahdee
  • 4,679
  • 4
  • 34
  • 58
  • Your attempted solution doesn't make any sense. `rnorm(12, AA)` gives you 12 observations from a random normal distribution with `mean=AA[1:12,1]` and sd=1. That's not even close to a rolling mean. And you're trying to add a zoo object as a column of an xts object? Why do you think that should work? – Joshua Ulrich Oct 25 '13 at 21:46

1 Answers1

18

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.

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • This is perfect; even anticipated a problem with rollmean! – Ahdee Oct 25 '13 at 23:00
  • interested to know Josh's opinion on adding a character vector to these xts objects. so you'd have one char column and one int/numeric column.... – d8aninja Jun 11 '17 at 22:01
  • @d8aninja: That's not possible because xts objects are based on the matrix class, and you can't have columns with different types in a matrix. That said, there has been some experimentation with an "xtsdf" class. – Joshua Ulrich Jun 11 '17 at 22:13
  • I see. Trying to think about making these objects ggplot and highcharter friendly. The latter especially has some nice presets for xts ("stock" type) but if you want to dynamically lab the series you've got to switch over to a data.frame and use zoo::index to pull off the xts rownames into a column – d8aninja Jun 11 '17 at 22:32