I have a data frame and some columns have NA
values.
How do I replace these NA
values with zeroes?
With dplyr
0.5.0, you can use coalesce
function which can be easily integrated into %>%
pipeline by doing coalesce(vec, 0)
. This replaces all NAs in vec
with 0:
Say we have a data frame with NA
s:
library(dplyr)
df <- data.frame(v = c(1, 2, 3, NA, 5, 6, 8))
df
# v
# 1 1
# 2 2
# 3 3
# 4 NA
# 5 5
# 6 6
# 7 8
df %>% mutate(v = coalesce(v, 0))
# v
# 1 1
# 2 2
# 3 3
# 4 0
# 5 5
# 6 6
# 7 8