na_locf: Replace 'NA' values with the most recent non-'NA' values...

View source: R/rutils.R

na_locfR Documentation

Replace NA values with the most recent non-NA values prior to them.

Description

Replace NA values with the most recent non-NA values prior to them.

Usage

na_locf(input, from_last = FALSE, na_rm = FALSE, max_gap = NROW(input))

Arguments

input

A numeric or Boolean vector or matrix, or xts time series.

from_last

A Boolean argument: should non-NA values be carried backward rather than forward? (default is FALSE)

na_rm

A Boolean argument: should any remaining (leading or trailing) NA values be removed? (default is FALSE)

max_gap

The maximum number of neighboring NA values that can be replaced (default is NROW(input)).

Details

The function na_locf() replaces NA values with the most recent non-NA values prior to them.

If the from_last argument is FALSE (the default), then the previous or past non-NA values are carried forward to replace the NA values. If the from_last argument is TRUE, then the following or future non-NA values are carried backward to replace the NA values.

The function na_locf() performs the same operation as function xts:::na.locf.xts() from package zoo, but it also accepts vectors as input.

The function na_locf() calls the compiled function na_locf() from package xts, which allows it to perform its calculations about three times faster than xts:::na.locf.xts().

Value

A vector, matrix, or xts time series with the same dimensions and data type as the argument input.

Examples

# Create vector containing NA values
input <- sample(22)
input[sample(NROW(input), 4)] <- NA
# Replace NA values with the most recent non-NA values
rutils::na_locf(input)
# Create matrix containing NA values
input <- sample(44)
input[sample(NROW(input), 8)] <- NA
input <- matrix(input, nc=2)
# Replace NA values with the most recent non-NA values
rutils::na_locf(input)
# Create xts series containing NA values
input <- xts::xts(input, order.by=seq.Date(from=Sys.Date(),
  by=1, length.out=NROW(input)))
# Replace NA values with the most recent non-NA values
rutils::na_locf(input)

algoquant/rutils documentation built on April 18, 2024, 12:05 a.m.