Skip to contents

Detect missing values in vector data and replace via methods from the zoo package.

Usage

replace_missing(x, method = c("linear", "locf"), maxgap = Inf)

Arguments

x

A numeric vector.

method

A character string indicating how to handle missing data.

"linear"

(The default) Linear interpolation across missing NA values using zoo::na.approx() .

"locf"

Stands for 'last observation carried forward'. Replaces each NA with the most recent non-NA value prior to it, or following it for leading NAs.

maxgap

A numeric value for the maximum number of consecutive NAs to fill. Any longer gaps will be left unchanged. Default is Inf.

Value

A numeric vector of filtered data.

Details

Leading and trailing missing NA values will be replaced either by linear extrapolation for method = "linear" by applying rule = 2 (see stats::approx()). Or by NOCB 'next observation carried backward' for method = "locf".

This function will also replace c(NaN, Inf, -Inf).

Examples

(x <- c(1, 2, NA, Inf, 5, 6, NA))
#> [1]   1   2  NA Inf   5   6  NA
replace_missing(x, method = "linear")
#> [1] 1 2 3 4 5 6 6
replace_missing(x, method = "locf")
#> [1] 1 2 2 2 5 6 6