replace_na: Replace NAs with specified values

View source: R/replace_na.R

replace_naR Documentation

Replace NAs with specified values


Replace NAs with specified values


replace_na(data, replace, ...)



A data frame or vector.


If data is a data frame, replace takes a named list of values, with one value for each column that has missing values to be replaced. Each value in replace will be cast to the type of the column in data that it being used as a replacement in.

If data is a vector, replace takes a single value. This single value replaces all of the missing values in the vector. replace will be cast to the type of data.


Additional arguments for methods. Currently unused.


replace_na() returns an object with the same type as data.

See Also

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


# 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 documentation built on Feb. 16, 2023, 7:40 p.m.