na_replace {cleaner} | R Documentation |
Replace NA values
Description
This is a generic function to replace NA values in data. It takes most data types as input and is extendible by other packages.
Usage
na_replace(x, ...)
## Default S3 method:
na_replace(x, replacement = "", ...)
## S3 method for class 'data.frame'
na_replace(x, ..., replacement = NULL)
## S3 method for class 'matrix'
na_replace(x, replacement = 0, ...)
## S3 method for class 'list'
na_replace(x, replacement = NULL, ...)
## S3 method for class 'numeric'
na_replace(x, replacement = 0, ...)
## S3 method for class 'Date'
na_replace(x, replacement = Sys.Date(), ...)
## S3 method for class 'logical'
na_replace(x, replacement = FALSE, ...)
Arguments
x |
any vector, data.frame, matrix or list with values of which |
... |
When |
replacement |
value to replace |
Details
All functions preserve attributes. Within a list
or data.frame
, all attributes per index/item/column are also preserved.
Examples
mtrx <- matrix(c(1, 2, NA, 3), nrow = 2)
mtrx
na_replace(mtrx)
na_replace(c(1, 2, NA, NA))
na_replace(c(1, 2, NA, NA), replacement = -1)
na_replace(c(1, 2, NA, NA), replacement = c(0, -1))
na_replace(c(Sys.Date(), NA)) # replacement defaults to 'today'
na_replace(c(TRUE, FALSE, NA))
na_replace(c(TRUE, FALSE, NA), replacement = TRUE)
# we're flexible, the class only remains the same if
# the replacement value allows it
na_replace(c(1, 2, 3, NA), replacement = "-")
# data.frame is a special case
mtcars[1:6, c("mpg", "hp")] <- NA
head(mtcars)
head(na_replace(mtcars, mpg, hp)) # no need to quote columns (but you can)
head(na_replace(mtcars, mpg, hp, replacement = c(999, 123)))
## Not run:
# practical way using tidyverse
library(dplyr)
starwars %>%
na_replace()
# even maintains groups
starwars %>%
group_by(hair_color) %>%
na_replace(hair_color, replacement = "TEST!") %>%
summarise(n = n())
## End(Not run)