【问题标题】:R: Best way to convert a mts to a non-time series dataframe with time indexesR:将 mts 转换为具有时间索引的非时间序列数据帧的最佳方法
【发布时间】:2011-06-25 19:11:04
【问题描述】:

我目前正在使用以下方法将 mts 数据集转换为以时间索引为列的数据框。有没有更优雅的方法来做到这一点?

z <- ts(matrix(rnorm(300), 100, 3), start=c(1961, 1), frequency=12)
YM<-cbind(Year=as.numeric(floor(time(z))),Month=as.numeric(cycle(z)))
z<-cbind(as.data.frame(YM),as.data.frame(z))

str(z)

【问题讨论】:

    标签: datetime r data-structures time-series


    【解决方案1】:

    您可以使用index()(来自zoo包)从ts中提取索引

    zindex <- index(z)
    zdf <- data.frame(Year = trunc(zindex), Month = (zindex - trunc(zindex)) * 12, z)
    

    或者生成日期序列

    Year = rep(1961:1969, each = 12)[1:100]
    Month = rep(1:12, times = 9)[1:100]
    

    【讨论】:

    • 我以为有一个函数可以做x - trunc(x),但我现在画的是空白……
    • index() 不是基本函数,因此您应该指定它在 zoo 包中。
    • zoo中的index()和base中的time()有什么区别?
    • @Zach:好问题。 time 在 base 中,有一个 zoo::time,它只是调用 index
    【解决方案2】:

    与@jonw 类似的解决方案,但使用 xts:

    x <- as.xts(z)
    d <- data.frame(Year=.indexyear(x)+1900, Month=.indexmon(x)+1, coredata(x))
    

    【讨论】:

      【解决方案3】:

      试试这个:

      data.frame(Year = c(floor(time(z) + .01)), Month = c(cycle(z)), z)
      

      as.data.frame(cbind(Year = floor(time(z) + .01), Month = cycle(z), z))
      

      【讨论】:

      • 这个解决方案效果很好,除了在少数情况下它产生了一个非常令人烦恼的错误。我建议使用以下函数来确保正确计算年份。 as.data.frame(cbind(Year = trunc(round(time(z),1))), Month = cycle(z), z))
      • 在这种情况下添加一个小数字以避免浮点问题。我已经编辑了解决方案以显示这一点。
      猜你喜欢
      • 1970-01-01
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-08
      • 2017-12-13
      相关资源
      最近更新 更多