Search code examples
rdplyrlag

Modifying dplyr::lag function


I am trying to use the lag function from the dplyr package. However when I give a lag > 0 I want the missing values to be replaced by the first value in x. How can we achieve this

library(dplyr)
x<-c(1,2,3,4)
z<-lag(x,2)
z
## [1] NA NA  1  2

Solution

  • Here's a modified function mylag:

    mylag <- function(x, k = 1, ...)
      replace(lag(x, k, ...), seq(k), x[1])
    
    x <- 1:4
    mylag(x, k = 2)
    # [1] 1 1 1 2