rdataframena

Replace 0 with NA in certain columns in R


This is probably a duplicate but I can't find it. I just want to replace 0s with NA in a list of specific columns in my data set, for example, columns 2 and 4:

col1   col2   col3   col4
1       0      4      1
0       3      0      3
5       2      2      0
3       0      2      1

And get:


col1   col2   col3   col4
1       NA     4      1
0       3      0      3
5       2      2      NA
3       NA      2     1


I know how to replace them in one column or for the whole data frame, but how can I do just certain columns?


Solution

  • In tidyverse:

    library(dplyr)
    library(tidyr)
    
    dat %>% 
      mutate(across(c(col2, col4), ~ na_if(., 0)))
    

    In base R:

    sub <- dat[, c("col2", "col4")]
    sub[sub == 0] <- NA
    

    or

    replace(sub, sub == 0, NA)