复制每日期间的最后一个值 [英] Copy down last value over a daily period
本文介绍了复制每日期间的最后一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个多日 XTS 对象,我正在尝试创建一个指标,该指标一旦为真,就在当天剩余时间内保持为真.我正在尝试的方法(但它不起作用)是将 na.locf 函数与 apply daily 结合起来:
I have a multi-day XTS object, and I am trying to create an indicator that once true, remains true for the rest of the day. The approach I am trying (but its not working) is combining the na.locf function with the apply daily:
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".所以:
Desired output is to copy down the '1' for the rest of that day. so:
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")))
推荐答案
一种选择是
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
这篇关于复制每日期间的最后一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文