fold_na | R Documentation |
Given two or more atomic vectors, fold each vector element-wise left-to-right, carrying forward the first non-missing value
fold_na(...)
... |
Atomic vectors or a |
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.
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).
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
.
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!
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.