Ferit
Ferit

Reputation: 648

Read Data into Time Series Object in R

My data looks as follows:

Month/Year;Number
01/2010; 1.0
02/2010;19.0
03/2010; 1.0
...

How can I read this into a ts(object) in R?

Upvotes: 1

Views: 1517

Answers (2)

David Arenburg
David Arenburg

Reputation: 92282

Try this (assuming your data is called df)

ts(df$Number, start = c(2010, 01), frequency = 12)
##      Jan Feb Mar
## 2010   1  19   1

Edit: this will work only if you don't have missing dates and your data is in correct order. For a more general solution see @Anandas answer below

Upvotes: 3

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193497

I would recommend using zoo as a starting point. This will ensure that if there are any month/year combinations missing, they would be handled properly.

Example (notice that data for April is missing):

mydf <- data.frame(Month.Year = c("01/2010", "02/2010", "03/2010", "05/2010"),
                   Number = c(1, 19, 1, 12))
mydf
#   Month.Year Number
# 1    01/2010      1
# 2    02/2010     19
# 3    03/2010      1
# 4    05/2010     12

library(zoo)
as.ts(zoo(mydf$Number, as.yearmon(mydf$Month.Year, "%m/%Y")))
#      Jan Feb Mar Apr May
# 2010   1  19   1  NA  12

Upvotes: 2

Related Questions