repeat_last: A "Last Observation Carried Forward" function

View source: R/last_obs_carried_fwd.R

repeat_lastR Documentation

A "Last Observation Carried Forward" function

Description

Repeat the last non NA value. "Fill forward" NAs with the closest previous non-NA value. There are lots of alternatives out there to this function. My fave is tidyr::fill().

Usage

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

Arguments

x

A vector

forward

Logical; default is TRUE. Direction to carry forward. By specifying forward = FALSE, you can carry the last observation backward.

maxgap

Numeric; By specifying maxgap, you can choose not to bridge overly long gaps.

na.rm

Logical; default is FALSE. Whether to remove NAs.

Value

A similar vector to x

References

https://stackoverflow.com/questions/7735647/replacing-nas-with-latest-non-na-value

Examples

repeat_last(c(1,2,3,4,NA,NA))
repeat_last(c(1,NA,3,4,NA,NA), forward = FALSE)
repeat_last(c(1,NA,3,4,NA,NA, 5), forward = FALSE)

x = c(NA, NA, 1, 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)

emilelatour/lamisc documentation built on April 9, 2024, 10:33 a.m.