Zero Division in R

Is there an easy way to avoid a 0 division error in R. In particular,

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 to define something / 0 = 0, so that this kind of operation will still be valid.

+7
source share
5 answers

Ok, take a moment. R does NOT return an error. It returns NaN quite correctly. You have a better reason to discard NaN values ​​in your work. Why are you letting any element b be null in the first place? You need to think about what your code is really designed for, and what it means (statistically, let's say), to have fun throwing away all the cases where b[j]==0 .

+14
source

What did you set all the elements in the denominator from 0 to NA and then exclude NA ? in sum ?

 a[a==0] <- NA sum(b/a, na.rm=TRUE) #----- [1] 3.5 

Or without changing a : sum(b/ifelse(a==0,NA,a), na.rm = TRUE)

+8
source

You can change the "/" function to have an exception for zero:

 "/" <- function(x,y) ifelse(y==0,0,base:::"/"(x,y)) 

For example:

 > 10/0 [1] 0 

This is very risky, although, for example, it can break other people's code. If you want to do this, it's probably a good idea to assign a different statement rather than changing / . Also mathematically makes no sense!

+7
source

If you want to hide all the results of NaN and Inf , try something like:

 a <- c(1,0,2,0) b <- c(3,2,1,0) result <- b/a sum(result[is.finite(result)]) [1] 3.5 

Or all in one line:

 sum((b/a)[is.finite(b/a)]) [1] 3.5 
+6
source

I just worked on a similar situation. This works well with ifelse ():

amount (IfElse ( == 0,0, b / a))

0
source

All Articles