【问题标题】:R:Transforming my xts to ts: automatically detecting the same datesR:将我的 xts 转换为 ts:自动检测相同的日期
【发布时间】:2018-08-17 00:11:00
【问题描述】:

假设我有一个这样的 xts 格式:

foo 

2000-01-01   2.6
2000-02-01   4.0
2000-03-01   2.6
2000-04-01   1.0
2000-05-01   2.4
...
...
2012-12-01   3.2

现在,我想将我的 xts 格式转换为 ts 系列。

配合使用

foo_ts<-ts(foo, freq=12, start=index(foo)[1])

我失去了日期格式,只得到数值而不是年份。

结果应如下所示:

      Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec
2000  2.6  4.0  2.6  1.0  2.4
2001 
2002 
2003 
2004

我不想用 c(2000,1) 手动设置它。我正在寻找一种自动处理问题的方法。

【问题讨论】:

    标签: date time-series xts


    【解决方案1】:

    这是需要在 xts 中修复的问题,但这里有一个解决方法:

    # first, some sample 'foo' data
    foo <- as.xts(sunspot.month)["2000/2012"]
    # Now convert to 'ts' via zooreg()
    foo_ts <- as.ts(as.zooreg(foo))
    foo_ts
    #        Jan   Feb   Mar   Apr   May   Jun   Jul   Aug   Sep   Oct   Nov   Dec
    # 2000  90.1 112.9 138.5 125.5 121.6 124.9 170.1 130.5 109.7  99.4 106.8 104.4
    # 2001  95.6  80.6 113.5 107.7  96.6 134.0  81.8 106.4 150.7 125.5 106.5 132.2
    # 2002 114.1 107.4  98.4 120.7 120.8  88.3  99.6 116.4 109.6  97.5  95.5  80.8
    # 2003  79.7  46.0  61.1  60.0  54.6  77.4  83.3  72.7  48.7  65.5  67.3  46.5
    # 2004  37.3  45.8  49.1  39.3  41.5  43.2  51.1  40.9  27.7  48.0  43.5  17.9
    # 2005  31.3  29.2  24.5  24.2  42.7  39.3  40.1  36.4  21.9   8.7  18.0  41.1
    # 2006  15.3   4.9  10.6  30.2  22.3  13.9  12.2  12.9  14.4  10.5  21.4  13.6
    # 2007  16.8  10.7   4.5   3.4  11.7  12.1   9.7   6.0   2.4   0.9   1.7  10.1
    # 2008   3.3   2.1   9.3   2.9   3.2   3.4   0.8   0.5   1.1   2.9   4.1   0.8
    # 2009   1.3   1.4   0.7   0.8   2.9   2.9   3.2   0.0   4.3   4.8   4.1  10.8
    # 2010  13.2  18.8  15.4   8.0   8.7  13.6  16.1  19.6  25.2  23.5  21.5  14.4
    # 2011  18.8  29.6  55.8  54.4  41.6  37.0  43.8  50.6  78.0  88.0  96.7  73.0
    # 2012  58.3  32.9  64.3  55.2  69.0  64.5  66.5  63.0  61.4  53.3  61.8  40.8
    

    【讨论】:

    • 用你的例子,它工作得很好。但是对于我的数据集,结果是完全错误的。未检测到频率、起点和终点。生成的 ts 格式包含很多 NA,大约有 9000 行,而我的 xts 有 152 行。我的 xts 的日期格式就像上面的“2000-02-01”,你的是“2000 年 2 月”。也许这就是问题所在。有没有办法用我的日期格式做到这一点?
    • @Leo96:如果您可以编辑您的问题以包含包含您的数据的reproducible example,那将是最简单的。你可以试试:index(foo) &lt;- as.yearmon(index(foo)).
    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 2020-05-22
    • 1970-01-01
    • 2013-12-10
    • 2021-01-26
    • 2021-01-01
    • 2011-10-09
    • 2017-12-17
    相关资源
    最近更新 更多