R:将数据帧(混合因子和数字)转换为R中的XTS [英] R: Converting data frame (mixed factor and numeric) to XTS in R
问题描述
将混合因子和数字列的数据框转换为xts时,我的所有数据都将转换为字符串。这不是问题的因素,但它是非常烦人的数字。是否有解决方法?
When converting a data frame with mixed factor and numeric columns to an xts, all of my data gets converted to strings. This isn't a problem with the factors, but it's extremely annoying with the numerics. Is there a workaround?
例如:
> x
marketTimestamp price id
1 2010-12-17 11:38:31.100 83.89 b-0
2 2010-12-17 11:38:31.100 83.88 b-1
3 2010-12-17 11:38:31.100 83.87 b-2
4 2010-12-17 11:38:31.300 83.91 o-0
5 2010-12-17 11:38:31.300 83.92 o-1
6 2010-12-17 11:38:31.300 83.93 o-2
> as.xts(x[,-1],as.POSIXct(x[,1]))
price id
2010-12-17 11:38:31 "83.89" "b-0"
2010-12-17 11:38:31 "83.88" "b-1"
2010-12-17 11:38:31 "83.87" "b-2"
2010-12-17 11:38:31 "83.91" "o-0"
2010-12-17 11:38:31 "83.92" "o-1"
2010-12-17 11:38:31 "83.93" "o-2"
理想情况下,我想要第一列保持数字,而第二个转换为字符串。解决方案需要完全自动化,因为我正在使用大量列的数据集,我不能总是预测哪些是因素,哪些是数字。
Ideally I want the first column to remain numeric, whilst the second is converted to a string. The solution needs to be fully automated, as I am working with data sets with a large number of columns, and I can't always predict which ones will be factor and which will be numeric.
-
编辑:
我试图通过定义来解决这个问题以下函数:
I've tried to get around this problem by defining the following function:
to.xts <- function(data) {
timestamp <- as.POSIXct(data[,1])
coredata <- data[,-1]
headers <- names(coredata)
data.type <- c()
for (header in headers) {
data.type[headers==header] <- class(coredata[[header]])
}
data.factor <- xts(coredata[,data.type=="factor"],timestamp)
data.numeric <- xts(coredata[,data.type=="numeric"],timestamp)
data.xts <- cbind(data.factor,data.numeric)
}
但是当合并两个XTS对象时,字符串数据将转换为NAs:
but when merging the two XTS objects, the string data is converted to NAs:
> x
id side
2010-12-17 11:38:31 "b-0" "BID"
2010-12-17 11:38:31 "b-1" "BID"
2010-12-17 11:38:31 "b-2" "BID"
> y
price
2010-12-17 11:38:31 83.89
2010-12-17 11:38:31 83.88
2010-12-17 11:38:31 83.87
> merge(x,y)
id side price
2010-12-17 11:38:31 NA NA 83.89
2010-12-17 11:38:31 NA NA 83.88
2010-12-17 11:38:31 NA NA 83.87
Warning message:
In merge.xts(x, y) : NAs introduced by coercion
这是XTS包的一个已知问题,还是我做错了?
Is this a known problem with the XTS package, or am I doing something wrong?
推荐答案
你不能这样做,因为xts需要一个数字矩阵。
You cannot do this as xts requires a numeric matrix.
这篇关于R:将数据帧(混合因子和数字)转换为R中的XTS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!