na_omit_if {naflex} | R Documentation |
Conditionally omit missing values
Description
na_omit_if
removes missing values from x
if the specified
checks are satisfied, and returns x
unmodified otherwise. When used
within summary functions, na_omit_if
provides greater flexibility than
the na.rm
option e.g. sum(na_omit_if(x, prop = 0.05))
.
Usage
na_omit_if(
x,
prop = NULL,
n = NULL,
consec = NULL,
n_non = NULL,
prop_strict = FALSE
)
Arguments
x |
Vector to omit missing values in if checks pass. |
prop |
The maximum proportion (0 to 1) of missing values allowed. |
n |
The maximum number of missing values allowed. |
consec |
The maximum number of consecutive missing values allowed. |
n_non |
The minimum number of non-missing values required. |
prop_strict |
A logical (default |
Details
There are four type of checks available:
a maximum proportion of missing values allowed (
prop
)a maximum number of missing values allowed (
n
)a maximum number of consecutive missing values allowed (
consec
), anda minimum number of non-missing values required (
n_non
).
Any number of checks may be specified, including none. If multiple checks are specified, they must all pass in order for missing values to be omitted. If no checks are specified then missing values are omitted, since this is considered as "all" checks passing.
Value
A vector of the same type as x
. Either x
with missing
values removed if all checks pass, or x
unmodified if any checks
fail.
For consistency with na.omit
, if missing
values are removed, the indices of the removed values form an
na.action
attribute of class omit
in the result.
If missing values are not removed (because the checks failed or there were
no missing values in x
) then no na.action
attribute is added.
Examples
x <- c(1, 3, NA, NA, NA, 4, 2, NA, 4, 6)
sum(na_omit_if(x, prop = 0.45, n = 10, consec = 5))
sum(na_omit_if(x, prop = 0.45))
require(magrittr)
sum(x %>% na_omit_if(prop = 0.45))
# WMO specification for calculating monthly values from daily data
daily_rain <- rnorm(30)
daily_rain[c(3, 5, 6, 7, 8, 9, 24, 28)] <- NA
sum(daily_rain %>% na_omit_if(n = 10, consec = 4))