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)
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))
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With