简体   繁体   English

R - 将 dataframe 转换为 xts 添加报价(在 xts 中)

[英]R - converting dataframe to xts adds quotations (in xts)

I am using a dataframe to create an xts.我正在使用 dataframe 创建 xts。 The xts gets created but all values (except the index in the xts) are within quotation. xts 被创建,但所有值(xts 中的索引除外)都在引号内。 This leads that I cannot use the data, since many functions such as sum, does not work.这导致我无法使用数据,因为 sum 等许多函数不起作用。

Any ideas how I can get an xts produced without the quotations?有什么想法可以在没有报价的情况下生成 xts 吗?

Here is my code [updated due to comment of inconsisty names of dataframes/xts]:这是我的代码 [由于数据帧/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

You need to realize that the underlying data structure that stores your data in the xts object is an R matrix object, which can only be of one R type (eg all numeric or all character). 您需要意识到,在xts对象中存储数据的基础数据结构是一个R矩阵对象,它只能是一个R类型(例如所有数字或所有字符)。 The timestamps are stored as a separate vector (your date column in this case) which is used for indexing/subsetting the data by time. 时间戳存储为单独的向量(在本例中为日期列),用于按时间对数据进行索引/子集化。

The cause of your problem is that your date column is forcing the matrix of data to convert to character type matrix (in the xts object) instead of numeric. 您的问题的原因是您的date列强制数据矩阵转换为字符类型矩阵(在xts对象中)而不是数字。 It seems that the date class converts to character when it is included in the matrix: 似乎date类在包含在矩阵中时转换为字符:

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

Any time you have non-numeric data in your data you're converting to xts (in the x argument of xts ), you'll get this kind of problem. 你有你的数据你转换为XTS(在非数字数据的任何时间x的参数xts ),你会得到这样那样的问题。

Your issue can be resolved as follows (which wici has shown in the comments) 您的问题可以解决如下(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"

The date part should be in the index, not part of the data.日期部分应该在索引中,而不是数据的一部分。 read.zoo will do that for you producing a zoo object. read.zoo会为您制作动物园 object。 You can then convert that to xts if you need it in that form.然后,如果您需要该格式,您可以将其转换为 xts。

library(xts)
as.xts(read.zoo(mydf3))
##            plus minus
## 2013-12-10    4    -1
## 2015-04-01    3    -2
## 2016-01-03    2    -4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM