簡體   English   中英

在CRAN R中轉換為時間序列時處理不存在的數據

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

我有以下數據集,我正在嘗試將消耗量轉換為時間序列。 某些數據不存在(例如,沒有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

當我在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        

,問題是如何簡單地用零或空白替換不存在的值?

"ts"類要求數據按規則間隔,即每個月都應存在或不適用,但此處並非如此。 動物園包裝可以處理不規則間隔的系列。 使用年/月的"yearmon"類將輸入讀取到zoo中,然后簡單地將其用作"zoo"系列,否則將其轉換為"ts" 如果輸入的是一個文件,但否則是完全一樣的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