2

我有一个 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 对象 priceXts,如下所示:

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

现在我在 earlyClose 的行上执行一个 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 列的类从数字变为字符?这是因为 xts 对象在内部表示为矩阵吗?有没有办法避免这种转换?

4

1 回答 1

2

xts在内部编码为矩阵(更好的性能)。由于您只想存储 Early Close,因此可以将其转换为 numeric ,例如:

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
于 2013-03-02T22:04:17.663 回答