Replace NA's by column (value) specific condition

df <- data.frame(CAR = c(1,1,3,9,1),
BIKE = c(2,NA,4,NA,9),
PLANE = c(8,NA,6,7,9),
BOAT = c(1,2,NA,4,NA),
SCOOTER = c(2,3,6,9,NA))

Hi, I have a df like this. I will like to replace NA values across every row where ‘CAR’ has a value of 1 only; so you get something like this

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

I know to replace NA’s across the whole dataset, but cant get around this. Any help on this please.

Here's one option. In the code below we use across to mutate every column except CAR. We use the replace function to set the desired condition and replacement value.

library(tidyverse)

df <- data.frame(CAR = c(1,1,3,9,1),
                 BIKE = c(2,NA,4,NA,9),
                 PLANE = c(8,NA,6,7,9),
                 BOAT = c(1,2,NA,4,NA),
                 SCOOTER = c(2,3,6,9,NA))

df.new = df %>% 
  mutate(across(-CAR, ~ replace(., is.na(.) & CAR==1, 0)))

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

identical(df.new, NEW_df)
#> [1] TRUE

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.