xts赋值更改列类

时间:2013-03-02 21:16:35

标签: r xts

我有一个data.frame earlyCloses定义如下:

earlyCloses <- read.table('EarlyCloses.txt', header=T, colClasses= c(rep("character", 3)))
earlyCloses

   StartDate    EndDate EarlyClose
1 2012-12-24 2012-12-24      13:00

我将xts对象的价格定义如下:

prices <- read.table('sample.txt', header=T, colClasses=c("character", "numeric"))
pricesXts = xts(prices$Close, as.POSIXct(prices$Date, tz='America/New_York'))
colnames(pricesXts) = c("Close")
pricesXts$CloseTime = NA
pricesXts

              Close CloseTime
2012-12-21 13190.84        NA
2012-12-24 13139.08        NA
2012-12-26 13114.59        NA
2012-12-27 13096.31        NA
2012-12-28 12938.11        NA

现在我在earlyCloses的行上执行for循环,并设置priceXts的CloseTime。

for (i in 1:nrow(earlyCloses)) {
   pricesXts[paste(earlyCloses[i,"StartDate"], earlyCloses[i,"EndDate"], sep='/'), 2] = earlyCloses[i,"EarlyClose"]
}
pricesXts

           Close      CloseTime
2012-12-21 "13190.84" NA       
2012-12-24 "13139.08" "13:00"  
2012-12-26 "13114.59" NA       
2012-12-27 "13096.31" NA       
2012-12-28 "12938.11" NA       

为什么xts对象中Close列的类从numeric更改为character?这是因为xts对象在内部表示为矩阵吗?有没有办法避免这种转换?

1 个答案:

答案 0 :(得分:2)

xts在内部编码为矩阵(性能更好)。由于您只想存储早期关闭,您可以将其转换为数字,例如:

strptime(earlyCloses$EarlyClose,'%H:%M')$hour

然后

for (i in 1:nrow(earlyCloses))
   pricesXts[paste(earlyCloses[i,"StartDate"], 
                   earlyCloses[i,"EndDate"], 
                   sep='/'), 2] <- strptime(earlyCloses$EarlyClose,'%H:%M')$hour


           Close CloseTime
2012-12-21 13191        NA
2012-12-24 13139        13
2012-12-26 13115        NA
2012-12-27 13096        NA
2012-12-28 12938        NA