| na.replace {na.tools} | R Documentation |
Replace Missing Values
Description
Replaces NA values with explicit values.
Usage
na.replace(x, .na, ...)
na.explicit(x)
Arguments
x |
vector in which |
.na |
scalar, length(x)-vector or function used to replace |
... |
additional arguments passed to |
Details
na.replace replaces missing values in x by .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 .na.
Param: x
If 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_.
If 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.
Param: .na
.na can be either a scalar, vector or function.
If a scalar, each missing value of x is replaced by na.
If a vector, .na must have length(x). Missing values ofxare replaced by corresponding elements of.na. Recycling values of.nais not allowed. An error will be thrown in the event thatlength(.na)is not1orlength(x).
If a function, x is transformed by .na' with:
.na(x, ...)
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.
Value
A vector with the class and length of x.
NAs in x will be replaced by .na. .na is coerced as necessary.
See Also
-
forcats::fct_explicit_na- which only handles factors
Examples
# 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)