【问题标题】:Conversion to xts does not work because data is of type 'character' and cannot be converted to 'numeric'无法转换为 xts,因为数据属于“字符”类型,无法转换为“数字”
【发布时间】:2013-10-23 10:36:48
【问题描述】:

我有以下数据集

data
     date PX_LAST.USGG10YR Index PX_LAST.GSWISS10 Index
1  2012-12-31                 1.7574                  0.526
2  2013-01-31                 1.9849                  0.789
3  2013-02-28                 1.8756                  0.698
4  2013-03-29                 1.8486                  0.716
5  2013-04-30                 1.6717                  0.570
6  2013-05-31                 2.1282                  0.722
7  2013-06-28                 2.4857                  1.027
8  2013-07-31                 2.5762                  1.023
9  2013-08-30                 2.7839                  1.069
10 2013-09-30                 2.6100                  1.021

日期列的类是

> class(data[,1])
[1] "POSIXct" "POSIXt"

另外两列的类是

类(数据[,2]) [1] “数字” 类(数据[,3]) [1] “数字”

我现在将其转换为 with

df2=xts(data,order.by=data$date)

结果是

structure(c("2012-12-31", "2013-01-31", "2013-02-28", "2013-03-29", 
"2013-04-30", "2013-05-31", "2013-06-28", "2013-07-31", "2013-08-30", 
"2013-09-30", "1.7574", "1.9849", "1.8756", "1.8486", "1.6717", 
"2.1282", "2.4857", "2.5762", "2.7839", "2.61", "0.526", "0.789", 
"0.698", "0.716", "0.57", "0.722", "1.027", "1.023", "1.069", 
"1.021"), .Dim = c(10L, 3L), .Dimnames = list(NULL, c("date", 
"PX_LAST.USGG10YR Index", "PX_LAST.GSWISS10 Index")), index = structure(c(1356912000, 
1359590400, 1362009600, 1364515200, 1367280000, 1369958400, 1372377600, 
1375228800, 1377820800, 1380499200), tzone = "UTC", tclass = c("POSIXct", 
"POSIXt")), .indexCLASS = c("POSIXct", "POSIXt"), tclass = c("POSIXct", 
"POSIXt"), .indexTZ = "UTC", tzone = "UTC", class = c("xts", 
"zoo"))

看结果,我明白了

> typeof(df2)
[1] "character"

显然,我不能将其用于计算(例如 Return.calculate)。当我尝试使用 as.numeric(df2[,2]) 转换第 2 列和第 3 列时,它仍然是“字符”类型。有人可以帮我找到一个将其转换为适当 xts 的代码(即第 2 列和第 3 列的类型为“双”),即 df2 的结构就像在这个例子中

library(quantmod)
getSymbols('AAA',src='FRED')
class(AAA)
typeof(AAA)
> class(AAA)
[1] "xts" "zoo"
> typeof(AAA)
[1] "double

问候 安德烈亚斯

【问题讨论】:

    标签: r character numeric xts data-conversion


    【解决方案1】:

    您在 xts 数据中包含 date 列,因此 R 使用不会丢失任何信息(字符)的类型将您的 data.frame 转换为矩阵。不需要将date 列作为数据中的xts 索引,因此当您调用xts() 时,只需省略该列即可。

    df2 <- xts(data[,-1], order.by=data$date)
    

    【讨论】:

    • 亲爱的 Joshua,非常感谢您的解决方案。它工作得很好,我是一个快乐的露营者。最好的问候,安德烈亚斯
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    • 2020-05-07
    • 2022-01-10
    • 1970-01-01
    • 2018-08-12
    相关资源
    最近更新 更多