road_to_quantdom
road_to_quantdom

Reputation: 1361

How to transform dataframe into time series in R?

I have a matrix called data stored with the following data:

     set.seed(8000)
     data <- matrix(sample(20,60,T),5)
     data
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,]   19    9    6    8    7    2    2   10    3     1     6    13
[2,]    7   15    6   19    5    6   17    4   18    17     1     6
[3,]    4    9    8    6   13   16   17    7   13     8    15    18
[4,]   14   15    5    4   19   13   16    6   16    19    11     6
[5,]    5    8    5    3    7   18   12   13   11     8    14    14

I would like to store this as a ts object with the columns being months of the year January-December and the rows being the years 1991-1995.

data
      Jan  Feb   Mar Apr  May  Jun July  Aug  Sep   Oct   Nov   Dec
1991   19    9    6    8    7    2    2   10    3     1     6    13
1992    7   15    6   19    5    6   17    4   18    17     1     6
1993    4    9    8    6   13   16   17    7   13     8    15    18
1994   14   15    5    4   19   13   16    6   16    19    11     6
1995    5    8    5    3    7   18   12   13   11     8    14    14

Basically if my data is stored with years as rows and months as columns, how can I store it as a time series object? I have tried doing:

data <- ts(data,freq=12,start=c(1991,1))

however, this does not seem to be working as I cannot plot the data later on. This is the error I am receiving:

error: cannot plot more than 10 series as "multiple".

Any advice would be appreciated. Thanks!

Upvotes: 0

Views: 115

Answers (2)

doctorG
doctorG

Reputation: 1731

Hint: please include the warning/error messages you get to clarify what you mean by "does not seem to be working". Your example was nice and reproducible, though, and I got the error: cannot plot more than 10 series as "multiple". Your problem is keeping the data as a matrix. Replace your last code line above with:

data <- ts(as.vector(t(data)),freq=12,start=c(1991,1))

which transposes (to vectorize it row-wise) and then converts to a single vector before passing to ts().

Upvotes: 1

Shen
Shen

Reputation: 183

data <- sample(20,60,T)
data <- ts(data,freq=12,start=c(1991,1))

Upvotes: 1

Related Questions