Home > OS >  How do I "do nothing" when using the dplyr ifelse() in R?
How do I "do nothing" when using the dplyr ifelse() in R?

Time:10-28

I am looking to use the ifelse() with mutate(), and if the condition is false, leave the value what is. Here is what I am working with:

df <- df %>% mutate(column1 = ifelse(is.na(column1), 0, "insert code to do nothing"))

CodePudding user response:

df <- df %>% mutate(column1 = ifelse(is.na(column1), 0, column1))

Note you also more directly use the recode function to turn missings into 0.

Or you can also use:

df <- df %>%
  mutate(column1 = replace_na(column1, 0))

CodePudding user response:

Here are couple of options -

  1. Base R -
df$column1[is.na(df$column1)] <- 0
  1. Using dplyr coalesce -
library(dplyr)
df <- df %>% mutate(column1 = coalesce(column1, 0))
  • Related