Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero divison in R

Tags:

r

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.

like image 947
Ashin Mukherjee Avatar asked Oct 27 '12 01:10

Ashin Mukherjee


1 Answers

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)

like image 162
Chase Avatar answered Nov 15 '22 21:11

Chase