Logical OR with NA tolerance
or.RdCompute a position-wise logical OR across multiple logical inputs.
When no TRUE is present, it allows up to a specified fraction of missing values per position before returning NA.
Arguments
- ...
Logical vectors of equal length, or a single logical matrix/data.frame. Matrix/data.frame inputs must have at least one column. Inputs are coerced to logical via
as.logical, preservingNA.- .na_allowed
(Scalar numeric:
0.2;[0, 1])
Maximum allowed fraction ofNAper position before the result is set toNAwhen noTRUEis present.
Details
Standard logical disjunction over multiple vectors (e.g., x | y | z).
Each output position corresponds to one vector index, or to one row when a matrix or data.frame is supplied.
Returns TRUE for a position if at least one element is TRUE, regardless of missing values.
Returns NA for a position if no TRUE is present and the fraction of NA exceeds .na_allowed.
Otherwise, missing values are treated as FALSE when evaluating the OR.
For each position (row) \(i\) across \(p\) inputs, let \(m_i\) be the number of NAs and \(t_i\) be the number of TRUEs.
Define the missing fraction \(r_i = m_i / p\).
Then:
$$
\text{or\_na}_i =
\begin{cases}
\text{TRUE}, & \text{if } t_i \ge 1, \\
\mathrm{NA}, & \text{if } t_i = 0 \text{ and } r_i > \text{.na\_allowed}, \\
\text{FALSE}, & \text{if } t_i = 0 \text{ and } r_i \le \text{.na\_allowed}.
\end{cases}
$$
Notes:
When
.na_allowed = 0, behavior matches strict OR:NApropagates only when noTRUEis present.When \(\text{.na\_allowed} = 1\), missingness never forces
NA.NAs are treated asFALSE, so the result isTRUEiff anyTRUEis present, otherwiseFALSE.
Examples
#----------------------------------------------------------------------------
# or() examples
#----------------------------------------------------------------------------
library(bkbase)
x <- c(FALSE, FALSE, FALSE, TRUE, FALSE)
y <- c(FALSE, FALSE, NA, FALSE, NA)
z <- c(FALSE, NA, NA, NA, TRUE)
# Base R strict OR
x | y | z
#> [1] FALSE NA NA TRUE TRUE
# NA tolerance at 20%
or(x, y, z, .na_allowed = 0.2)
#> [1] FALSE NA NA TRUE TRUE
# NA tolerance at 40%
or(x, y, z, .na_allowed = 0.4)
#> [1] FALSE FALSE NA TRUE TRUE
# Single data.frame input
df <- data.frame(x = x, y = y, z = z)
or(df, .na_allowed = 0.4)
#> [1] FALSE FALSE NA TRUE TRUE
# TRUE dominates even when NA is present
or(TRUE, NA, .na_allowed = 0)
#> [1] TRUE