Reputation: 715
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
Upvotes: 2
Views: 69
Reputation: 887163
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
Upvotes: 2