【问题标题】:xts assignment changes column classxts 赋值更改列类
【发布时间】:2013-02-17 05:46:41
【问题描述】:

我有一个 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 对象在内部表示为矩阵吗?有没有办法避免这种转换?

【问题讨论】:

  • 看函数xts,好像是这样的(matrix)。

标签: r xts


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 2013-11-27
    • 1970-01-01
    相关资源
    最近更新 更多