Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Best way to convert a mts to a non-time series dataframe with time indexes

I'm currently using the following method to convert a mts dataset to a data frame with time indexes as columns. Is there a more elegant way to do this?

z <- ts(matrix(rnorm(300), 100, 3), start=c(1961, 1), frequency=12)
YM<-cbind(Year=as.numeric(floor(time(z))),Month=as.numeric(cycle(z)))
z<-cbind(as.data.frame(YM),as.data.frame(z))

str(z)
like image 376
Zach Avatar asked Dec 13 '22 15:12

Zach


2 Answers

Try this:

data.frame(Year = c(floor(time(z) + .01)), Month = c(cycle(z)), z)

or

as.data.frame(cbind(Year = floor(time(z) + .01), Month = cycle(z), z))
like image 192
G. Grothendieck Avatar answered Dec 28 '22 06:12

G. Grothendieck


You can extract the index from the ts with index() (from zoo package)

zindex <- index(z)
zdf <- data.frame(Year = trunc(zindex), Month = (zindex - trunc(zindex)) * 12, z)

Or generate a sequence of dates with

Year = rep(1961:1969, each = 12)[1:100]
Month = rep(1:12, times = 9)[1:100]
like image 27
J. Win. Avatar answered Dec 28 '22 06:12

J. Win.