1
votes

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?

2

2 Answers

4
votes

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))
2
votes

You mean something like this?

   obj <- as.xts(transform(obj, another_obj=rowMeans(obj)))