【问题标题】:Time series - Convert every column of dataframe to time series时间序列 - 将数据帧的每一列转换为时间序列
【发布时间】:2022-01-10 15:41:10
【问题描述】:

我在 R 中有一个数据框 df

month  abc1   def2   xyz3
201201    1      2      4 
201202    2      5      7
201203    4     11      4
201204    6     23     40

我想使用decompose 函数将每一列(其中有约 50 个,每列有约 100 个每月观察值)转换为时间序列格式,以便检查数据中的季节性。

我认为使用ts 函数的for 循环将是执行此操作的最佳方式。我想在下面的循环中使用一些东西,尽管我意识到使用<- 左侧的函数会产生错误。有没有办法动态命名循环生成的变量?

for(i in 2:ncol(df)) {
  paste(names(df[, i]), "_ts") <- ts(df[ ,i], start = c(2012, 1), end = c(2021,11), frequency = 12)
}

【问题讨论】:

    标签: r for-loop time-series


    【解决方案1】:

    你可以试试zoo:

    test = data.frame(month=c("201201", "201202", "201203", "201204"), abc1=c(1,2,3,4), def2=c(4,6,7,10), xyz3=c(12,15,16,19))
    
    library(zoo)
    
    ZOO =zoo(test[, c("abc1", "def2", "xyz3")], order.by=as.Date(paste0(test$month, "01"), format="%Y%m%d"))
    
    ts(ZOO, frequency=12)
    

    输出:

          abc1 def2 xyz3
    Jan 1    1    4   12
    Feb 1    2    6   15
    Mar 1    3    7   16
    Apr 1    4   10   19
    attr(,"index")
    [1] 2012-01-01 2012-02-01 2012-03-01 2012-04-01
    

    更新: 现在频率正确。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-23
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      • 2015-05-16
      • 1970-01-01
      相关资源
      最近更新 更多