NA values with explicit values.
1 2 3
vector in which
scalar, length(x)-vector or function used to replace
additional arguments passed to
na.replace replaces missing values in
.na if possible.
In R, replacement of values can cause a change in the class/type of an object.
This is not often desired.
na.replace is class/type-safe and length-safe.
It replaces missing values without changing the
x's class or length
regardless of the value provided by
x is categorical (e.g. character or factor),
.na is optional.
The default is "(NA)" and can be set with
options( NA_explicit_ = new_value ). It can also be
referenced directly with NA_explicit_.
x is a factor, unique values of
.na not in already present in
levels(x) will be added. They are appended silently unless
getOption('verbose')==TRUE in which a message reports the added levels.
.na can be either a scalar, vector or function.
If a scalar, each missing value of
x is replaced by
If a vector,
.na must have length(x)
. Missing values ofx
are replaced by corresponding elements of.na
. Recycling values of.na
is not allowed. An error will be thrown in the event thatlength(.na)
If a function,
x is transformed by .na' with:
then preceding with normal operations.
na.explicit is an alias for na.replace that uses NA_explicit_ for '.na“;
it returns x unchanged if it cannot change the value.
A vector with the class and length of
x will be replaced by
.na is coerced as necessary.
forcats::fct_explicit_na - which only handles factors
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
# Integers and numerics na.replace( c(1,NA,3,NA), 2 ) # 1 2 3 2 na.replace( c(1,NA,3,NA), 1:4 ) # 1 2 3 4 # This produces an error because it would change the type ## Not run: na.replace( c(1,NA,3,NA), letters[1:4] ) # "1" "b" "3" "d" ## End(Not run) # Characters lets <- letters[1:5] lets[ c(2,4) ] <- NA na.replace(lets) # replace with NA_explicit_ # Factors fct <- as.factor( c( NA, letters[2:4], NA) ) fct na.replace(fct, "z") # z b c d z -- level z added na.replace(fct, letters[1:5] ) na.replace(fct) ## Not run: na.replace( rep(NA,3), rep(NA,3) ) ## End(Not run)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.