r语言 - to.period 不能与 XTS 格式结合使用



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

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 (Open, High, Close, Low)格式的数据帧。

现在让我们把这个数据帧变成xts对象:

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

现在我想申请。周期函数,例如:

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

I get error:

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

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

问题是在构建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

最新更新