1

I have an xts object. I would like to take an average for each row and merge it back to my object. Ex:

require(xts)
obj = xts(matrix(1:100, ncol=2), order.by=seq.Date(from=as.Date("2012-01-01"), by=1, length=50))
another_obj = apply(obj, 1, mean)

This is now just a vector with dates as names.

class(another_obj)
   [1]  "numeric"

I could again convert this to xts and use the names as the order.by and then merge everything back to obj but this is quite tedious.

another_obj = as.xts(another_obj, order.by=as.Date(names(another_obj)))
obj = merge(obj, another_obj)

What's the correct way to do this?

Alex
  • 19,533
  • 37
  • 126
  • 195

2 Answers2

4

This will add a column with the mean of each row

obj <- cbind(obj, rowMeans(obj))

EDIT clarify why the cbind is working here:

Here I am using cbind.xts wich is a call merge.xts. So the above is equivalent to :

obj <- merge(obj, rowMeans(obj))
agstudy
  • 119,832
  • 17
  • 199
  • 261
  • thanks! always get a bit worried with just `cbinding` time-series together but i guess in this case it's guaranteed they will line up. – Alex Mar 11 '13 at 19:54
  • could you please explain how this works? `rowMeans` will return a vector not an `xts` so how will merging be called here? – Alex Mar 11 '13 at 20:05
  • I think it will assign the same dates to the rowMeans(obj), merge the 2 , and return an xts object because the default `retcalss` of `merge` is xts. – agstudy Mar 11 '13 at 20:12
  • right so this is basically the classic `cbind`. it works great here just want to make sure – Alex Mar 11 '13 at 20:19
2

You mean something like this?

   obj <- as.xts(transform(obj, another_obj=rowMeans(obj)))
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138