Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force Division by zero default to NaN instead of Inf

I'm wondering if there might be a setting I'm overlooking to force R to return NaN instead of ±Inf when dividing by zero.

I too often findmyself doing something like

 results[is.infinite(results)] <- NaN

I'm hoping to skip the filtering/search process altogether.


Example:

### Example:

num <- c(1:5, NA)
denom <- -2:3

quotient <- num / denom
[1] -0.5 -2.0  Inf  4.0  2.5   NA

# desired results
[1] -0.5 -2.0  NaN  4.0  2.5   NA

Simple way of achieving the desired results is:

quotient[is.infinite(quotient)] <- NaN

What I am wondering is if that last step can be avoided while still getting the same desired results.

like image 518
Ricardo Saporta Avatar asked Oct 03 '22 22:10

Ricardo Saporta


1 Answers

I would switch my predicate rather than trying to redefine math:

 R> is.finite(c(Inf, NA, NaN))    
 [1] FALSE FALSE FALSE 
 R> is.infinite(c(Inf, NA, NaN))   
 [1]  TRUE FALSE FALSE 
 R> is.na(c(Inf, NA, NaN)) 
 [1] FALSE  TRUE  TRUE
 R> 
like image 147
Dirk Eddelbuettel Avatar answered Oct 12 '22 11:10

Dirk Eddelbuettel