0
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. I have tried:

NEW_DF <- df %>% mutate(across(c(-CAR), ~replace(.,CAR == 1, NA)))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
lofus77
  • 181
  • 5

3 Answers3

3

Here is another way -

df[-1][df$CAR == 1 & is.na(df[-1])] <- 0
df

#  CAR BIKE PLANE BOAT SCOOTER
#1   1    2     8    1       2
#2   1    0     0    2       3
#3   3    4     6   NA       6
#4   9   NA     7    4       9
#5   1    9     9    0       0
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • I usually assume (mistakenly, obviously) that chained-`[` does not always use `[<-` where I intend it to do so. – r2evans Jul 14 '21 at 14:05
1

dplyr

library(dplyr)
df %>%
  mutate(across(-CAR, ~ if_else(CAR == 1 & is.na(.), 0, .)))
#   CAR BIKE PLANE BOAT SCOOTER
# 1   1    2     8    1       2
# 2   1    0     0    2       3
# 3   3    4     6   NA       6
# 4   9   NA     7    4       9
# 5   1    9     9    0       0

base R

df[,-1] <- lapply(df[,-1], function(x) ifelse(df$CAR == 1 & is.na(x), 0, x))
df
#   CAR BIKE PLANE BOAT SCOOTER
# 1   1    2     8    1       2
# 2   1    0     0    2       3
# 3   3    4     6   NA       6
# 4   9   NA     7    4       9
# 5   1    9     9    0       0
r2evans
  • 141,215
  • 6
  • 77
  • 149
1

We can also use replace:

libary(dplyr)

df%>%mutate(across(-CAR, ~replace(., is.na(.) & CAR==1, 0)))
GuedesBF
  • 8,409
  • 5
  • 19
  • 37