Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

replace_na

Replace NAs with specified values


Description

Replace NAs with specified values

Usage

replace_na(data, replace, ...)

Arguments

data

A data frame or vector.

replace

If data is a data frame, replace takes a list of values, with one value for each column that has NA values to be replaced.

If data is a vector, replace takes a single value. This single value replaces all of the NA values in the vector.

...

Additional arguments for methods. Currently unused.

Value

  • If data is a data frame, replace_na() returns a data frame.

  • If data is a vector, replace_na() returns a vector, with class given by the union of data and replace.

See Also

dplyr::na_if() to replace specified values with NAs; dplyr::coalesce() to replaces NAs with values from other vectors.

Examples

# Replace NAs in a data frame
df <- tibble(x = c(1, 2, NA), y = c("a", NA, "b"))
df %>% replace_na(list(x = 0, y = "unknown"))

# Replace NAs in a vector
df %>% dplyr::mutate(x = replace_na(x, 0))
# OR
df$x %>% replace_na(0)
df$y %>% replace_na("unknown")

# Replace NULLs in a list: NULLs are the list-col equivalent of NAs
df_list <- tibble(z = list(1:5, NULL, 10:20))
df_list %>% replace_na(list(z = list(5)))

tidyr

Tidy Messy Data

v1.1.3
MIT + file LICENSE
Authors
Hadley Wickham [aut, cre], RStudio [cph]
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.