Will repeat the last non-NA value. This is also known as carrying the last observation forward/backward. It's faster than zoo::na.locf http://rpubs.com/rubenarslan/repeat_last_na_locf and other alternatives. By specifying maxgap, you can choose not to bridge overly long gaps. By specifying forward = FALSE, you can carry the last observation backward.

repeat_last(x, forward = TRUE, maxgap = Inf, na.rm = FALSE)

Arguments

x

vector to be repeated

forward

carry last observation forward? or backward (FALSE)

maxgap

bridge only up to x NAs (defaults to Inf)

na.rm

whether to omit NAs at the beginning (defaults to FALSE)

Examples

x = c(NA,NA,1,NA,NA,NA,NA,NA,NA,NA,NA,2,3,4,NA,NA,NA,NA,NA,5, NA) data.frame(x, repeat_last(x), repeat_last(x, forward = FALSE), repeat_last(x, maxgap = 5), check.names = FALSE)
#> x repeat_last(x) repeat_last(x, forward = FALSE) repeat_last(x, maxgap = 5) #> 1 NA NA 1 NA #> 2 NA NA 1 NA #> 3 1 1 1 1 #> 4 NA 1 2 NA #> 5 NA 1 2 NA #> 6 NA 1 2 NA #> 7 NA 1 2 NA #> 8 NA 1 2 NA #> 9 NA 1 2 NA #> 10 NA 1 2 NA #> 11 NA 1 2 NA #> 12 2 2 2 2 #> 13 3 3 3 3 #> 14 4 4 4 4 #> 15 NA 4 5 4 #> 16 NA 4 5 4 #> 17 NA 4 5 4 #> 18 NA 4 5 4 #> 19 NA 4 5 4 #> 20 5 5 5 5 #> 21 NA 5 NA 5