1

When I execute 0 / 0 in R, I would get a NaN as an output. But is there any way I could print 0 / 0 as 1? I know I could use some if statements to achieve it. I would like to know if there is any other way to achieve this.

Kalees Waran
  • 659
  • 6
  • 13
  • 1
    Can you just replace your `NaN`s with `1`? `x[is.nan(x)] <- 1`? – Phil Jul 07 '17 at 10:44
  • 1
    See the answers to this question, https://stackoverflow.com/questions/8022979/operator-overloading-and-class-definition-in-r-use-a-different-base-field-corpu It describe how to overload math Ops. – kangaroo_cliff Jul 07 '17 at 10:45
  • An easier option would be to define a function, say, `div` and use it for division. – kangaroo_cliff Jul 07 '17 at 10:46
  • If this is about something like `sin(x)/x` at `x=0` then it would be better to have this continuation in the function definition, in C-like syntax `(1+x*x==1)?1:sin(x)/x`. – Lutz Lehmann Jul 07 '17 at 15:19

2 Answers2

4

You could define your own division symbol especially for this. For example,

'|' <- function(a,b)ifelse(a==0 & b==0, 1, a/b)

> 0|0
[1] 1
> 3|4
[1] 0.75
Dan
  • 11,370
  • 4
  • 43
  • 68
  • If you prefer a more telling name, you can define an operator enclosed in `%`, as in `%div%`. If efficiency is a concern, I would recommend `%div% <- function(a, b){ x <- a/b; x[is.nan(x)] <- 1; x}` (but the improvement in efficiency is very small) – Benjamin Jul 07 '17 at 11:03
0

Other way than using If statement would be

# Assign NaN to vector
a <- 0 / 0
# If is NaN assign value 1
a[is.nan(a)] <- 1
Miha
  • 2,559
  • 2
  • 19
  • 34