Conversion to xts does not work because data is of type 'character' and cannot be converted to 'numeric'

我怕爱的太早我们不能终老 提交于 2021-02-05 05:43:10

问题


I have the following data set

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

The class of the date column is

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

The class of the other two columns is

class(data[,2]) [1] "numeric" class(data[,3]) [1] "numeric"

I am now converting this to its with

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

The result is

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"))

Looking at the result, I get

> typeof(df2)
[1] "character"

Clearly, I cannot use this for calculations (such as Return.calculate). When I try to convert columns 2 and 3 with as.numeric(df2[,2]), it remains as type 'character'. Can somebody help me to find a code which does convert this to a proper xts (i.e. columns 2 and 3 are of type 'double'), i.e. the structure of df2 is like in this example

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

Regards Andreas


回答1:


You included the date column in the xts data, so R converted your data.frame into a matrix using the type that wouldn't lose any information (character). There's no need to have the date column as the xts index and in the data, so just omit that column when you call xts().

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


来源:https://stackoverflow.com/questions/19384353/conversion-to-xts-does-not-work-because-data-is-of-type-character-and-cannot-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!