Copy down last value over a daily period

后端 未结 2 1385
一个人的身影
一个人的身影 2021-01-22 05:33

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 com

2条回答
  •  借酒劲吻你
    2021-01-22 06:11

    I think period.apply called by apply.daily does not like the value returned by na.locf. Haven't investigated very thoroughly why. Anyway, I tried to do what it should be doing in a round-about manner. I can see that akrun's answer is definitely superior than this. Just leaving this here.

    R> 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")))
    R> endpoints(y, "days")
    [1] 0 6 9
    R> ep <- endpoints(y, "days")
    R> diff(ep)
    [1] 6 3
    R> dep <- diff(ep)
    R> rep.int(1:length(dep), times=dep)
    [1] 1 1 1 1 1 1 2 2 2
    R> runs <- rep.int(1:length(dep), times=dep)
    R> lapply(split(y, runs), na.locf, na.rm=FALSE)
    $`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
    
    $`2`
    
    2010-01-06 00:00:00 NA
    2010-01-06 00:04:00 NA
    2010-01-06 00:08:00 NA
    
    R> splits <- lapply(split(y, runs), na.locf, na.rm=FALSE)
    R> do.call('rbind', splits)
    
    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
    R> ynew <- do.call('rbind', splits)
    

提交回复
热议问题