Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How i can replace zeros with NAs across all columns in R using dplyr?

i have a dataframe that looks like this :

Date = seq(as.Date("2022/1/1"), by = "day", length.out = 10)
x = c(rnorm(9),NA)
y = c(NA,0,rnorm(4),6,0,0,10)
z = c(rnorm(4),0,0,NA,NA,3,2)
d = tibble(Date,x,y,z);d
# A tibble: 10 x 4
   Date                 x          y          z
   <date>           <dbl>      <dbl>      <dbl>
 1 2022-01-01  2.456174   NA          0.2963012
 2 2022-01-02  0.3648335   0          0.3981664
 3 2022-01-03  0.8283570  -0.1843364  1.194378 
 4 2022-01-04  1.061199    1.507231  -0.2337116
 5 2022-01-05 -0.07824196 -0.6708553  0        
 6 2022-01-06 -0.2654019   0.3008499  0        
 7 2022-01-07  1.426953    6         NA        
 8 2022-01-08 -0.5776817   0         NA        
 9 2022-01-09  0.8706953   0          3        
10 2022-01-10 NA          10          2   

how i can replace all the zeros across all columns with NA using Dplyr package ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With dplyr, you could use na_if():

library(dplyr)

d %>%
  mutate(across(everything(), na_if, 0))

or simply

d[d == 0] <- NA

# Pipeline
d %>%
  `[<-`(d == 0, value = NA)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading