id var1 var2 var3 var4
1 3 5 NA 10
2 0 NA 7 NA
3 1 3 NA 6
4 0 NA NA 6
Hello I have this example as a data set. I am trying to replace the na based on the condition that if var1 =0 then replace all nas of the row as 0, but not the other na of the other rows.
I have tried the following
mydf <- replace(mydf, is.na(mydf), 0)
but as you understand this replaces all na values
I want to replace all nas of the row based on my condition not just for one column.
Could you provide me with some help please? Thank you
>Solution :
We may create a condition with the var1 column as well to only consider those rows where ‘var1’ is 0
i1 <- is.na(mydf[-c(1, 2)])
i2 <- (mydf$var1 == 0)[row(mydf[-c(1,2)])]
mydf[-c(1,2)][i1 & i2] <- 0
-output
> mydf
id var1 var2 var3 var4
1 1 3 5 NA 10
2 2 0 0 7 0
3 3 1 3 NA 6
4 4 0 0 0 6
Or instead of subsetting the data, it can be applied to the whole data as well
replace(mydf, is.na(mydf) & mydf$var1 == 0, 0)
id var1 var2 var3 var4
1 1 3 5 NA 10
2 2 0 0 7 0
3 3 1 3 NA 6
4 4 0 0 0 6
Or using dplyr
library(dplyr)
mydf %>%
mutate(across(var2:var4, ~ replace(.x, is.na(.x) & var1 == 0, 0)))
-output
id var1 var2 var3 var4
1 1 3 5 NA 10
2 2 0 0 7 0
3 3 1 3 NA 6
4 4 0 0 0 6
data
mydf <- structure(list(id = 1:4, var1 = c(3L, 0L, 1L, 0L), var2 = c(5L,
NA, 3L, NA), var3 = c(NA, 7L, NA, NA), var4 = c(10L, NA, 6L,
6L)), class = "data.frame", row.names = c(NA, -4L))