Is there an easy way of avoiding 0 division error in R. Specifically,
a <- c(1,0,2,0)
b <- c(3,2,1,0)
sum(b/a)
This code gives an error due to division by zero. I would like a way to define anything/0 = 0 so that this kind of operation would still be valid.
What is you set all items in the denominator to 0 to NA
and then exclude NA
? in your sum
?
a[a==0] <- NA
sum(b/a, na.rm=TRUE)
#-----
[1] 3.5
Or without modifying a
: sum(b/ifelse(a==0,NA,a), na.rm = TRUE)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With