fold_na: Return the first non-missing value from two or more atomic...

View source: R/fold_na.R

fold_naR Documentation

Return the first non-missing value from two or more atomic vectors

Description

Given two or more atomic vectors, fold each vector element-wise left-to-right, carrying forward the first non-missing value

Usage

fold_na(...)

Arguments

...

Atomic vectors or a list containing atomic vectors of the same type and length. Inputs of length 1 are allowed and potentially recycled to the length of the longest input, but this behavior varies depending on the input order. See details.

Details

This is very similar to SQL's coalesce function, but is intentionally named to avoid clashing with the dplyr implementation. This is strictly written in base R and follows the same class-handling rules as implemented by ifelse.

The function will exit when it detects that no additional NA values are present or when all inputs have been evaluated, whichever comes first. If you supply e.g. a non-missing vector of length 1 as the first input, then the function will only ever return that supplied value because one of the two aforementioned conditions will have been satisfied. See examples.

Value

An atomic vector of the same type as the inputs (although any class attributes will be stripped). The length will be either 1 if the first supplied input is a non-missing atomic vector of length 1 or the length of the inputs – assuming input lengths are otherwise equivalent (but greater than 1).

Note

The non-exported helper function .fold_na_base() has slightly different behavior when handling vectors of length 1 combined with vectors of length > 1, regardless of argument order. The helper ensures outputs are always the length of the longest input(s). If this is desirable, then you can effectively achieve the same result by calling the helper along with e.g. Reduce. If so, make sure you pass the inputs as a (flat) list.

Examples

x <- 1:10L
y <- c(1L, NA, 3L, NA, 5L, NA, 7L, NA, 9L, NA)
z <- c(NA, 2L, NA, 4L, NA, 6L, NA, 8L, NA, 10L)

fold_na(x) # returns x

fold_na(y, z) # regenerates x
fold_na(list(y, z)) # same

# works the same on data.frames
df <- data.frame(y, z, x)
fold_na(df)
fold_na(df[, c("y", "z")])

# These are not equivalent
fold_na(y, 0L) # NA in y substituted with 0
fold_na(0L, y) # only returns zero as vector of length 1!

slin30/wzMisc documentation built on Jan. 27, 2023, 1 a.m.