Skip to content

Help with NaN when 0 divided by 0

4 messages · Jennifer Sabatier, Sarah Goslee, Marc Schwartz +1 more

#
Hi,

Here are two possible ways to deal with it. Which is better depends on
the larger context of your code. There's no right way, just whichever
is more convenient.
[1]   0.00000  13.88889  53.79000   0.00000 150.00000 350.00000
[1]   0.00000  13.88889  53.79000   0.00000 150.00000 350.00000
Sarah

On Tue, Jul 31, 2012 at 4:23 PM, Jennifer Sabatier
<plessthanpointohfive at gmail.com> wrote:

  
    
#
On Jul 31, 2012, at 3:23 PM, Jennifer Sabatier <plessthanpointohfive at gmail.com> wrote:

            
You could use ?ifelse:
[1]   0.00000  13.88889  53.79000   0.00000 150.00000 350.00000

It is very common in programming to include code to handle exceptions, so don't be shy about using conditional coding as may be appropriate.

Regards,

Marc Schwartz
#
On Jul 31, 2012, at 1:23 PM, Jennifer Sabatier wrote:

            
It's possible to define new infix operators (although I have forgotten  
which help page describes this in more detail and I cannot seem to  
find it right now):

  "%/0%" <- function(x,y) { res <- x / y ; res[ is.na(res) ] <- 0;  
return(res) }

# You cannot use %/% because it is already used for integer division.  
I guess you could use "//", but to me that looks too much like "||"  
which is the single-value-OR. You could also use "%div0%".

  var1 %/0% var2

#[1]   0.00000  13.88889  53.79000   0.00000 150.00000 350.00000

If this is a regular need, you can put this in a .profile file or a  
package. See:

?Startup