简体   繁体   中英

Dealing with nonexistent data when converting to time-series in CRAN R

I have got following data set and I am trying to convert the consumption to time series. Some of the data are nonexistent (eg there is no data for 10/2014).

year    month   consumption
2014    7   10617
2014    8   8318
2014    9   3199
2014    12  2066
2015    1   10825
2015    2   3096
2015    3   1665
2015    4   3651
2015    5   5807
2015    7   2951
2015    8   5885
2015    9   3653
2015    10  4266
2015    11  9706

when I use ts() in R, the wrong values are replaced for nonexistent months.

ts(mkt$consumptions, start = c(2014,7),end=c(2015,11), frequency=12)

  Jan   Feb   Mar   Apr   May   Jun   Jul   Aug   Sep   Oct   Nov   Dec
2014                                 10617  8318  3199  2066 10825  3096
2015  1665  3651  5807  2951  5885  3653  4266  9706 10617  8318  3199        

,y question is how to simply replace the nonexistent values with zero or blank?

"ts" class requires that the data be regularly spaced, ie every month should be present or NA but that is not the case here. The zoo package can handle irregularly spaced series. Read the input into zoo using the "yearmon" class for the year/month and then simply use it as a "zoo" series or else convert it to "ts" . If the input is in a file but otherwise is exactly the same as in Lines then replace text = Lines with something like "myfile.dat" .

Lines <- "year    month   consumption
2014    7   10617
2014    8   8318
2014    9   3199
2014    12  2066
2015    1   10825
2015    2   3096
2015    3   1665
2015    4   3651
2015    5   5807
2015    7   2951
2015    8   5885
2015    9   3653
2015    10  4266
2015    11  9706"

library(zoo)

toYearmon <- function(y, m) as.yearmon(paste(y, m), "%Y %m")
z <- read.zoo(text = Lines, header = TRUE, index = 1:2, FUN = toYearmon)

as.ts(z)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM