Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: converting xts or zoo object to a data frame

What is an easy way of coercing time series data to a data frame, in a format where the resulting data is a summary of the original?

This could be some example data, stored in xts or zoo object:

t,                  V1
"2010-12-03 12:00", 10.0
"2010-11-04 12:00", 10.0
"2010-10-05 12:00", 10.0
"2010-09-06 12:00", 10.0
...and so on, monthly data for many years.

and I would like to transform it to a data frame like:

year, month, V1
2010, 12,    a descriptive statistic calculated of that month's data
2010, 11,    ...
2010, 10,    ...
2010, 9,     ...

The reason I'm asking this, is because I want to plot monthly calculated summaries of data in the same plot. I can do this quite easily for data in the latter format, but haven't found a plotting method for the time series format.

For example, I could have temperature data from several years measured in a daily interval and I would like to plot the curves for the monthly mean temperatures for each year in the same plot. I didn't figure out how to do this using the xts-formatted data, or if this even suits the purpose of the xts/zoo formatting of the data, which seems to always carry the year information along it.

like image 593
user442446 Avatar asked Dec 06 '10 16:12

user442446


1 Answers

Please provide a sample of data to work with and I will try to provide a less general answer. Basically you can use apply.monthly to calculate summary statistics on your xts object. Then you can convert the index to yearmon and convert the xts object to a data.frame.

x <- xts(rnorm(50), Sys.Date()+1:50)
mthlySumm <- apply.monthly(x, mean)
index(mthlySumm) <- as.yearmon(index(mthlySumm))
Data <- as.data.frame(mthlySumm)
like image 113
Joshua Ulrich Avatar answered Sep 24 '22 03:09

Joshua Ulrich