Learn R Programming

janitor (version 0.2.1)

use_first_valid_of: Returns first non-NA value from a set of vectors.

Description

At each position of the input vectors, iterates through in order and returns the first non-NA value. This is a robust replacement of the common ifelse(!is.na(x), x, ifelse(!is.na(y), y, z)). It's more readable and handles problems like ifelse's inability to work with dates in this way.

Usage

use_first_valid_of(..., if_all_NA = NA)

Arguments

...
the input vectors. Order matters: these are searched and prioritized in the order they are supplied.
if_all_NA
what value should be used when all of the vectors return NA for a certain index? Default is NA.

Value

Returns a single vector with the selected values.

Examples

Run this code
x <- c(1, NA, NA); y <- c(2, 2, NA); z <- c(3, 3, 3)
use_first_valid_of(x, y, z)
use_first_valid_of(y, x, if_all_NA = 0)

Run the code above in your browser using DataLab