na_replace: Replace NA values

Description Usage Arguments Details Examples

View source: R/na_replace.R

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
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 NA must be replaced

...

When x is a data.frame: columns of x to affect. This supports tidy evaluation without the need to quote the columns, see Examples.

replacement

value to replace NA with. This is at default: 0 for numeric values and class matrix, FALSE for class logical, today for class Date, and "" otherwise. Can also be a vector with the length of the number of NAs of x (sum(is.na(x))). When x is a data.frame, this can be a vector with the length of the number of columns to be affected, see Examples.

Details

All functions preserve attributes. Within a list or data.frame, all attributes per index/item/column are also preserved.

Examples

 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
28
29
30
31
32
33
34
35
36
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)

cleaner documentation built on June 13, 2021, 5:06 p.m.