Copy down last value over a daily period

后端 未结 2 1376
一个人的身影
一个人的身影 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)
    
    0 讨论(0)
  • 2021-01-22 06:24

    One option is

    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
    
    0 讨论(0)
提交回复
热议问题