简体   繁体   English

在CRAN R中转换为时间序列时处理不存在的数据

[英]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). 某些数据不存在(例如,没有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. 当我在R中使用ts()时,错误的值将替换为不存在的月份。

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. "ts"类要求数据按规则间隔,即每个月都应存在或不适用,但此处并非如此。 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" . 使用年/月的"yearmon"类将输入读取到zoo中,然后简单地将其用作"zoo"系列,否则将其转换为"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 ,然后替换text = Lines的东西,如"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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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