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

View source: R/rutils.R

nalocfR 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

nalocf(inputv, fromLast = FALSE, narm = FALSE, maxgap = NROW(inputv))

Arguments

inputv

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

fromLast

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

narm

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

maxgap

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

Details

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

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

The function nalocf() performs the same operations as the function zoo::na.locf() from package zoo.

The function nalocf() calls the function xts:::na.locf.xts() from package xts.

Value

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

Examples

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

algoquant/rutils documentation built on June 10, 2025, 3:55 p.m.