coalesce: Find first non-missing element

View source: R/coalesce.R

coalesceR Documentation

Find first non-missing element

Description

Given a set of vectors, coalesce() finds the first non-missing value at each position. It's inspired by the SQL COALESCE function which does the same thing for SQL NULLs.

Usage

coalesce(..., .ptype = NULL, .size = NULL)

Arguments

...

One or more vectors.

.ptype

The type to cast the vectors in ... to. If NULL, the vectors will be cast to their common type, which is consistent with SQL.

.size

The size to recycle the vectors in ... to. If NULL, the vectors will be recycled to their common size.

Examples

# Use a single value to replace all missing values
x <- sample(c(1:5, NA, NA, NA))
coalesce(x, 0L)

# The equivalent to a missing value in a list is NULL
coalesce(list(1, 2, NULL), list(NA))

# Or generate a complete vector from partially missing pieces
y <- c(1, 2, NA, NA, 5)
z <- c(NA, NA, 3, 4, 5)
coalesce(y, z)

# Supply lists by splicing them into dots:
vecs <- list(
  c(1, 2, NA, NA, 5),
  c(NA, NA, 3, 4, 5)
)
coalesce(!!!vecs)

tidyverse/funs documentation built on May 21, 2022, 12:12 p.m.