locf: Last observation carried forward

View source: R/utils.R

locfR Documentation

Last observation carried forward

Description

Replaces NA in vectors, data frames, or matrices with most recent non-NA value.

Usage

locf(x, fromLast = FALSE, na.strings = "")

Arguments

x

a vector, matrix, or data frame

fromLast

logical or vector of logicals; if TRUE, observations are carried backward rather than forward; other options such as c(TRUE, FALSE) will call locf first for fromLast = TRUE follwed by calling with fromLast = FALSE on the result

na.strings

a vector of values to be treated as NA; optionally a list of single elements can be used for mixed data types; see examples

Examples

x <- c('', '', 'a', '', 'b', '', '', '', 'c')
locf(x)
locf(x, c(FALSE, TRUE))
locf(x, TRUE)

dd <- data.frame(
  V1 = c('Bob', NA, NA, 'Joe', NA, NA),
  V2 = c(NA, 1, NA, NA, 2, NA),
  stringsAsFactors = FALSE
)

locf(dd)
locf(dd, c(FALSE, TRUE))
locf(dd, na.strings = 2)

## note the differences for numeric and character na.strings
locf(dd, na.strings = c('Joe', 2))
locf(dd, na.strings = list('Joe', 02))
locf(dd, na.strings = list('Joe', '02'))


## with dates
dd$V2 <- as.Date(dd$V2, origin = '2000-01-01')
locf(dd)
locf(dd, TRUE)
locf(dd, c(FALSE, TRUE))


raredd/rawr documentation built on May 19, 2024, 1:02 p.m.