Dplyr mutate divide two columns with NAs

Advertisements

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!

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

Leave a ReplyCancel reply