问题
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.
Any ideas how I can get an xts produced without the quotations?
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
回答1:
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.
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"
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.
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"
来源:https://stackoverflow.com/questions/39855315/r-converting-dataframe-to-xts-adds-quotations-in-xts