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

Dplyr mutate divide two columns with NAs

Below is an example dataframe:

a = c("x","y","z")
b = c(1,2,NA)
c = c(4,NA,6)
c_b = c(4,NA,6)
df=data.frame(a,b,c,c_b)

I want to mutate as:

dplyr::mutate(c_b = c/b)

The issue is I want to keep the NA values when c (numerator) is NA, but keep the value of c when b is NA!

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

Any help will be much appreciated. Thanks

>Solution :

We could use coalesce

library(dplyr)
df %>%
   mutate(c_b = coalesce(c/b, c))

-output

   a  b  c c_b
1 x  1  4   4
2 y  2 NA  NA
3 z NA  6   6
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