R - 将数据框转换为 xts 添加引号(在 xts 中)

R - converting dataframe to xts adds quotations (in xts)

我正在使用数据框创建 xts。 xts 已创建,但所有值(xts 中的索引除外)都在引号内。这导致我无法使用数据,因为很多功能(例如求和)都不起作用。

有什么想法可以在没有引号的情况下生成 xts 吗?

这是我的代码[由于 dataframes/xts 名称不一致的评论而更新]:

# creates a dataframe with dates and currency
mydf3 <- data.frame(date = c("2013-12-10", "2015-04-01", 
"2016-01-03"), plus = c(4, 3, 2), minus = c(-1, -2, -4))
# transforms the column date to date-format
mydf3 = transform(mydf3,date=as.Date(as.character(date),format='%Y-%m-%d'))
# creates the xts, based on the dataframe mydf3
myxts3 <- xts(mydf3, order.by = mydf3$date)
# removes the column date, since date is now stored as index in the xts
myxts3$date <- NULL

您需要意识到,在 xts 对象中存储数据的底层数据结构是一个 R 矩阵对象,它只能是一种 R 类型(例如全数字或全字符)。时间戳存储为单独的向量(在本例中为您的日期列),用于按时间 indexing/subsetting 数据。

你的问题的原因是你的 date 列强制数据矩阵转换为字符类型矩阵(在 xts 对象中)而不是数字。似乎 date class 包含在矩阵中时会转换为字符:

> as.matrix(mydf3)
     date         plus minus
[1,] "2013-12-10" "4"  "-1" 
[2,] "2015-04-01" "3"  "-2" 
[3,] "2016-01-03" "2"  "-4" 

只要你的数据中有非数字数据,你就会将其转换为 xts(在 xtsx 参数中),你就会遇到这种问题。

您的问题可以通过以下方式解决(wici已在评论中说明)

myxts3 <- xts(x= mydf3[, c("plus", "minus")], order.by = mydf3[, "date"])

> coredata(myxts3)
plus minus
[1,]    4    -1
[2,]    3    -2
[3,]    2    -4
> class(coredata(myxts3))
[1] "matrix"