【问题标题】:to.period doesn't work combined with xts formatto.period 不能与 xts 格式结合使用
【发布时间】:2021-06-03 13:57:57
【问题描述】:

让我们考虑以下数据框以作为可重现的示例:

df <- data.frame(
  "Date" =
    c(
      "2009-11-02", "2009-11-03", "2009-11-04", "2009-11-05", "2009-11-06",
      "2009-11-09", "2009-11-10", "2009-11-12", "2009-11-13", "2009-11-16",
      "2009-11-17", "2009-11-18", "2009-11-19", "2009-11-20"
    ),
  "Open" = c(
    64.97971, 64.64817, 63.88567, 64.34973, 67.16770, 67.63186,
    69.48868, 68.95794, 70.08527, 72.47256,
    72.53886, 72.73724, 71.07980, 69.75345
  ),
  "High" = c(
    65.47689, 65.14544, 65.44378, 66.96887, 68.75883, 69.62065, 70.81439, 73.26807,
    71.07980, 73.13536,
    73.26807, 72.93625, 71.87532, 72.27345
  ),
  "Low" = c(
    63.98508, 62.75843, 63.71976, 64.34973, 65.47689, 66.96887, 68.36125, 68.95794,
    69.28966, 72.00803,
    72.00803, 71.14620, 69.68705, 69.75345
  ),
  "Close" = c(
    64.64817, 62.85784, 65.21174, 66.96887, 65.70910, 69.62065, 70.81439, 71.94172, 70.61537, 72.53886,
    72.80355, 71.60999, 69.68705, 70.94709
  )
)

这是一些 OHLC 格式的数据框(开盘价、最高价、收盘价、最低价)。

现在让我们把这个数据框改成 xts 对象:

df <- as.xts(df, order.by = as.Date(df[, 1]))

现在我想申请.period函数,例如:

to.period(df, period = "days", k =3) 

我得到错误:

'to.period(df, period = "days", k = 3)':unsupported type

我读到了这个错误,它的根源在于xts 对象的定义。因为xts 对象是一个矩阵,每个变量都应该具有相同的类型。问题就在这里,因为例如“打开”列是由数值创建的,并且第一列填充了日期格式的值。这就是as.xts() 将所有内容都转换为字符串的原因,这是最常见的数据格式。但是,即使我知道它为什么不起作用的理由——我也不知道如何让to.period 起作用。你知道如何解决吗?

【问题讨论】:

    标签: r dataframe xts


    【解决方案1】:

    问题是在构造xts时没有删除第一列

    df <- as.xts(df[-1], order.by = as.Date(df[, 1]))
    to.period(df, period = "days", k =3) 
    #            df.Open  df.High   df.Low df.Close
    #2009-11-03 64.97971 65.47689 62.75843 62.85784
    #2009-11-06 63.88567 68.75883 63.71976 65.70910
    #2009-11-09 67.63186 69.62065 66.96887 69.62065
    #2009-11-12 69.48868 73.26807 68.36125 71.94172
    #2009-11-13 70.08527 71.07980 69.28966 70.61537
    #2009-11-18 72.47256 73.26807 71.14620 71.60999
    #2009-11-20 71.07980 72.27345 69.68705 70.94709
    

    在不删除第一列即character 类列('Date')的情况下,xts 将整个数据转换为character 类,因为它也是matrixmatrix 只能有单课

    str(as.xts(df, order.by = as.Date(df[, 1])))
    An ‘xts’ object on 2009-11-02/2009-11-20 containing:
      Data: chr [1:14, 1:5] "2009-11-02" "2009-11-03" "2009-11-04"  "2009-11-05" "2009-11-06" "2009-11-09" "2009-11-10" "2009-11-12" ...
     - attr(*, "dimnames")=List of 2
      ..$ : NULL
      ..$ : chr [1:5] "Date" "Open" "High" "Low" ...
      Indexed by objects of class: [Date] TZ: UTC
      xts Attributes:  
     NULL
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 2015-07-11
      • 2015-12-25
      • 1970-01-01
      • 2022-12-18
      相关资源
      最近更新 更多