Default division force by zero on NaN instead of Inf

I am wondering if there could be a setting that I skip to get R return NaN instead of Β± Inf when dividing by zero.

Too often I find myself doing something like

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

I hope to skip the filtering / search process in general.


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 

A simple way to achieve the desired results:

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

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

+4
source share
2 answers

I would switch my predicate, rather than trying to redefine the 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> 
+5
source

Will these properties help? 0*Inf is NaN and NaN+Inf also NaN , so trying something like this will also give the desired result:

 quotient <- (num / denom)*0 + (num / denom) ## [1] -0.5 -2.0 NaN 4.0 2.5 NA 
0
source

Source: https://habr.com/ru/post/1502899/


All Articles