在每日期间复制最后一个值

时间:2016-05-12 10:56:04

标签: r xts

我有一个多天的XTS对象,我正在尝试创建一个曾经为真的指标,在​​当天的剩余时间内保持为真。我正在尝试的方法(但它不起作用)是将na.locf函数与每日应用结合起来:

output <- apply.daily(x, na.locf)

可重复的代码:

y <- as.xts(c(NA,NA,1,NA,NA,NA,NA,NA,NA),as.POSIXct(c(
                                   "2010-01-05 00:00:00", "2010-01-05 00:04:00", "2010-01-05 00:08:00", 
                                   "2010-01-05 00:12:00", "2010-01-05 00:16:00", "2010-01-05 00:20:00",
                                   "2010-01-06 00:00:00", "2010-01-06 00:04:00", "2010-01-06 00:08:00")))

所需的输出是在当天的剩余时间内复制'1'。这样:

y <- as.xts(c(NA,NA,1,1,1,1,NA,NA,NA),as.POSIXct(c(
                                   "2010-01-05 00:00:00", "2010-01-05 00:04:00", "2010-01-05 00:08:00", 
                                   "2010-01-05 00:12:00", "2010-01-05 00:16:00", "2010-01-05 00:20:00",
                                   "2010-01-06 00:00:00", "2010-01-06 00:04:00", "2010-01-06 00:08:00")))

1 个答案:

答案 0 :(得分:2)

一个选项是

y1 <- ave(y, as.Date(index(y)), FUN= function(x) na.locf(x, na.rm=FALSE))
y1
#                      [,1]
#2010-01-05 00:00:00   NA
#2010-01-05 00:04:00   NA
#2010-01-05 00:08:00    1
#2010-01-05 00:12:00    1
#2010-01-05 00:16:00    1
#2010-01-05 00:20:00    1
#2010-01-06 00:00:00   NA
#2010-01-06 00:04:00   NA
#2010-01-06 00:08:00   NA

str(y1)
# An ‘xts’ object on 2010-01-05/2010-01-06 00:08:00 containing:
#  Data: num [1:9, 1] NA NA 1 1 1 1 NA NA NA
#  Indexed by objects of class: [POSIXct,POSIXt] TZ: 
#  Original class: 'double'  
# xts Attributes:  
# NULL

str(y)
#An ‘xts’ object on 2010-01-05/2010-01-06 00:08:00 containing:
#  Data: num [1:9, 1] NA NA 1 NA NA NA NA NA NA
#  Indexed by objects of class: [POSIXct,POSIXt] TZ: 
#  Original class: 'double'  
#  xts Attributes:  
# NULL