Sunday, July 17, 2011

R: extract column from xts object as a vector

A quickie for the R language... you will look at the answer and think it is hardly worth writing a blog post over. Well it turns out that everyone has thought the same... which is why it took me over half an hour of failed searching and trial and error to work it out.

I've an XTS object, x, and I've added a column which is the sum of the other columns:
  x$sum=apply(x,1,sum)
print(x$sum) shows me the sum for each row, along with the datestamp of that row. I.e. x$sum is still an XTS object. Normally this is good, but I wanted it as a simple vector, without the dates associated. Here is how you do that:
  as.vector(x$sum)
Why did I want that? Simply because summary(x$sum) uses up 7 lines, half of it being noise about the datestamps; summary(as.vector(x$sum)) is 2 lines, all signal, no noise.

6 comments:

Anonymous said...

Thanks very much! You've saved me lots of wasted time.

Anonymous said...

You just saved my day! After three hours of searching, I finally found an answer! Thank you for taking time and writing this.

Matt said...

More than 2 years on, and your "hardly worth it" comment is still helping! Many thanks - answered my question exactly!

Unknown said...

Could you elaborate on the flipside of this. I have a date column and an "x". How to merge these and/or many more to XTS-

Cheers

Unknown said...

Lars, is "x" a vector/matrix? If so, use the xts constructor:
d = as.Date(1:5);v = 6:10
xts(v,d)

This creates an xts object with "1970-01-02 6" as the first row, "1970-01-06 10" as the 5th row.

Unknown said...

Very informative article.Thank you author for posting this kind of article .



http://www.wikitechy.com/view-article/explain-in-detail-about-vectors-in-r-programming



Both are really good,.
Cheers,
Venkat