How to replace NA values with a specific value in R

· 2 min read · Updated March 15, 2026 · beginner
r na missing-data dplyr data.table

NA values represent missing data in R. Replacing them with a specific value is a common data cleaning task. Here is how to do it efficiently.

Replace NA in a Vector

Base R

Use logical subsetting to replace NA values:

x <- c(1, 2, NA, 4, NA, 6)
x[is.na(x)] <- 0
# [1] 1 2 0 4 0 6

You can also use ifelse():

x <- c(1, 2, NA, 4, NA, 6)
x <- ifelse(is.na(x), 0, x)
# [1] 1 2 0 4 0 6

With dplyr and tidyr

Use coalesce() to replace NA with a specific value:

library(dplyr)

x <- c(1, 2, NA, 4, NA, 6)
x <- coalesce(x, 0)
# [1] 1 2 0 4 0 6

Replace NA in a Data Frame

With dplyr

Use mutate() with coalesce() to replace NA in specific columns:

library(dplyr)

df <- data.frame(
  id = 1:4,
  score = c(85, NA, 72, NA)
)

df <- df %>% mutate(score = coalesce(score, 0))

Replace NA across multiple columns:

df <- df %>% mutate(across(everything(), ~coalesce(.x, 0)))

With tidyr

Use replace_na() for a simple approach:

library(dplyr)
library(tidyr)

df <- df %>% replace_na(list(score = 0))

With data.table

library(data.table)

dt <- data.table(df)
dt[is.na(score), score := 0]

Replace NA across all columns:

for (j in names(dt)) {
  set(dt, which(is.na(dt[[j]])), j, 0)
}

Base R

df$score[is.na(df$score)] <- 0

Replace NA with Mean or Median

Often you will want to impute missing values with column statistics:

library(dplyr)

df <- data.frame(
  id = 1:5,
  value = c(10, NA, 15, NA, 25)
)

# Replace with mean
df <- df %>% mutate(value = replace_na(value, mean(value, na.rm = TRUE)))

# Replace with median
df <- df %>% mutate(value = replace_na(value, median(value, na.rm = TRUE)))

Conditional Replacement

Replace NA only when another column meets a condition:

library(dplyr)

df <- data.frame(
  id = 1:4,
  type = c("A", "A", "B", "B"),
  score = c(85, NA, 72, NA)
)

df <- df %>% 
  mutate(score = ifelse(is.na(score) & type == "A", 90, score))

See Also