R - 将数据帧转换为 xts 添加引号(在 xts 中) [英] R - converting dataframe to xts adds quotations (in xts)

查看:32
本文介绍了R - 将数据帧转换为 xts 添加引号(在 xts 中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用数据框来创建 xts.xts 被创建,但所有值(xts 中的索引除外)都在引号内.这导致我无法使用数据,因为 sum 等许多函数不起作用.

I am using a dataframe to create an xts. The xts gets created but all values (except the index in the xts) are within quotation. This leads that I cannot use the data, since many functions such as sum, does not work.

任何想法如何在没有引号的情况下制作 xts?

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]:

# 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 类型(例如全数字或全字符).时间戳存储为单独的向量(在本例中为您的日期列),用于按时间索引/子集数据.

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 (e.g. all numeric or all character). The timestamps are stored as a separate vector (your date column in this case) which is used for indexing/subsetting the data by time.

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

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. It seems that the date class converts to character when it is included in the matrix:

> 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 参数中),您都会得到这种问题.

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.

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

Your issue can be resolved as follows (which wici has shown in the comments)

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"

这篇关于R - 将数据帧转换为 xts 添加引号(在 xts 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆