0

I've just encounter a weird behaviour of R which I would like to understand.

When I do NA^0 it gives 1 and not NA as I would have expected.

example:

v1 <- c(2,NA,1)
v1^0
[1] 1 1 1
v1**0
[1] 1 1 1

^ and ** are arithmetic operators (help("^")) like -, +, etc. which in their case gives NA:

v1+0
[1]  2 NA  1
v1-0
[1]  2 NA  1

Why are the different operators performe differently with NAs?

Bastien
  • 3,007
  • 20
  • 38
  • 6
    I remember my mathematics teacher saying ***"Anything raise to 0 is 1".*** – Ronak Shah Mar 13 '17 at 12:39
  • 1
    This is what it does. This result has been exploited on a number of SO answers to produce vectorized solutions in the presence of NA values. – lmo Mar 13 '17 at 12:40
  • You can look at this: http://stackoverflow.com/questions/17863619/why-does-nan0-1 – PKumar Mar 13 '17 at 12:41
  • @Ronak Shah Even a NULL value??? I know the mathematical law for numbers, but from a computer point of view, I would have expected (and prefer) that NULL value stay NULL when raised to 0... – Bastien Mar 13 '17 at 12:42
  • 3
    `NULL^0 = numeric(0)` – Sotos Mar 13 '17 at 12:44
  • 3
    NA is *not* equivalent to NULL. From the help file `?NA`: "NA is a logical constant of length 1 which contains a missing value indicator." and from `?NULL`, "NULL represents the null object in R." These are distinct concepts. Consider a data.frame, df, with variable v1. `df$v1 <- NA` sets the values of the variable to missing, whereas `df$v1 <- NULL` removes the variable. – lmo Mar 13 '17 at 12:45
  • After a quick read of the like posted (which I missed in my search, I apologise), I see the point of that behaviour. Personnaly, I would have prefer the other behaviour to be able to use this operation as a `is.na` alternative. Anyway, thanks for the explanations. – Bastien Mar 13 '17 at 12:50

1 Answers1

0

I voted to close this as a duplicate, but since your question seems to be "how can I avoid this behavior and return NA instead":

your_exp <- Vectorize(function(base, exp) ifelse(is.na(base),NA,base^exp))
v1 <- c(2,NA,1)

your_exp(v1,0)
# returns [1]  1 NA  1

Please see the accepted answer for why NA^0 == 1.

Community
  • 1
  • 1
C8H10N4O2
  • 18,312
  • 8
  • 98
  • 134