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 -
- Base R -
df$column1[is.na(df$column1)] <- 0
- Using
dplyr
coalesce
-
library(dplyr)
df <- df %>% mutate(column1 = coalesce(column1, 0))
CodePudding user response:
In data.table
, we can do
library(data.table)
setDT(df)[is.na(column1), column1 := 0]
Or in dplyr
with case_when
library(dplyr)
df <- df %>%
mutate(column1 = case_when(is.na(column1) ~ 0, TRUE ~ column1))