replace blank with 0 based on value in another column

Viewed 73

I have a df like this:

                 NEW_df <- data.frame(CAR = c("YES","NO","NO","YES","NO"),
                                     BIKE = c(2,0,4,NA,9),
                                     PLANE = c(8,0,6,7,9),
                                   BOAT = c(NA,NA,NA,4,3),
                                   SCOOTER = c(2,3,6,9,0))

I will like to replace NA's in column BOAT with '0'if the column CAR is 'NO', so I can have something like this:

                 NEW_df <- data.frame(CAR = c("YES","NO","NO","YES","NO"),
                                     BIKE = c(2,0,4,NA,9),
                                     PLANE = c(8,0,6,7,9),
                                   BOAT = c(NA,0,0,4,3),
                                   SCOOTER = c(2,3,6,9,0))

I thought something like this, but it didnt work:

NEW_df %>%
  mutate(across(BOAT, ~ if_else(CAR == NO & is.na(.), 0, .)))

Is it even possible to place the replaced values in a new column too.

3 Answers

We can do this easily in base R

NEW_df$BOAT[is.na(NEW_df$BOAT) & NEW_df$CAR == "NO"] <- 0

The %>% doesn't do replacement inplace. We have to assign back with NEW_df <-. Also, if it is single column, there is no need for across along with a syntax error (NO is not quoted)

library(dplyr)
NEW_df <- NEW_df %>%
      mutate(BOAT = replace(BOAT, CAR == "NO" & is.na(BOAT), 0))

An alternative using dplyr ...

library(dplyr)

NEW_df <- 
    NEW_df %>% 
    mutate(BOAT = if_else(CAR=='NO' & is.na(BOAT), 0, BOAT))

You can also use data.table

library(data.table)
NEW_df <- as.data.table(NEW_df)
NEW_df[is.na(BOAT) & CAR == "NO", BOAT := 0]
Related