6

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.

Ricardo Saporta
  • 54,400
  • 17
  • 144
  • 178
  • 1
    This doesn't exactly help, but `is.finite` will return `FALSE` for `NA`, `NaN` and `Inf`. – Justin Sep 18 '13 at 19:49
  • 4
    not to mention why should R put Inf. dividing by zero is not Inf. it is undefined. it should be NA. I hoped your question would instigate a better discussion of this behavior. – Elad663 May 27 '14 at 23:02
  • 1
    @Elad663 is absolutely correct. Putting 1/0 = Inf is plainly incorrect. Voting up for drawing attention to that. – RudePeopleStepOff May 08 '15 at 17:15

2 Answers2

4

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> 
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • Thanks Dirk, but I dont follow how changing the predicate helps here. What am I missing? – Ricardo Saporta Sep 18 '13 at 20:18
  • Instead of setting `NaN` and then testing for it, just test for `!is.finite()`. You'll be better off in the long run as x / 0 really is Inf for all positive x. – Dirk Eddelbuettel Sep 18 '13 at 20:44
  • 4
    @DirkEddelbuettel above is wrong concerning `x/0`. ` x/0` is not infinity---not in algebra, not in calculus, not in programming. Consider `x =1`. The right- and left-hand limits as `y->0` of `x/y` do not agree. The left-hand limit is `-inf` and the right-hand limit is `inf`. Those are not the same limit. – RudePeopleStepOff May 08 '15 at 17:08
  • 2
    Ooops. Thanks for the correction. `is.finite()` and friends still do the right things though. – Dirk Eddelbuettel May 08 '15 at 17:14
0

Would these properties be helpful? 0*Inf is NaN and NaN+Inf is also NaN, so trying something like this would also give your desired outcome:

quotient <- (num / denom)*0 + (num / denom)
## [1] -0.5 -2.0  NaN  4.0  2.5   NA
Valentin_Ștefan
  • 6,130
  • 2
  • 45
  • 68