1

I am trying to create a vectorial function in R using the command ifelse as follows

temp <- function(p){
ifelse(p < 0.5 *(1 + 0.5), (1 + 0.5) * qnorm(p/(1 +0.5)), (1 - 0.5) * qnorm((p - 0.5)/(1 - 0.5)))
}

The function works well with scalar values, for example

> temp(0.1)
[1] -2.251629
> temp(0.9)
[1] 0.4208106

but not for vectors:

> temp(c(0.1,0.9))
[1] -2.2516289  0.4208106
Warning message:
In qnorm((p - 0.5)/(1 - 0.5)) : NaNs produced

The weird thing is that it returns the right answer, but indicating a warning.

What am I doing wrong? It seems that the ifelse is evaluating both functions in all the entries of the vector p, which is supposed to be avoided with this command.

1 Answers1

1

ifelse is basically doing this:

p<- c(.1,.9)
a<-(1 + 0.5) * qnorm(p/(1 +0.5))
b<- (1 - 0.5) * qnorm((p - 0.5)/(1 - 0.5))
c<-NULL
c[which(p < 0.5 *(1 + 0.5))] <-a[which(p < 0.5 *(1 + 0.5))]
c[which(!(p < 0.5 *(1 + 0.5)))] <-b[which(!(p < 0.5 *(1 + 0.5)))]

That is, it creates a vector for 'yes' and a vector for 'no'. The 'no' vector it creates throws the warning.

The examples in the documentation allude to this.

x <- c(6:-4)
sqrt(x)  #- gives warning
sqrt(ifelse(x >= 0, x, NA))  # no warning

## Note: the following also gives the warning !
ifelse(x >= 0, sqrt(x), NA)
mgriebe
  • 908
  • 5
  • 8
  • Thanks. Then, why this doesn't happen with scalar inputs? – Jake Jackson Sep 24 '14 at 09:29
  • @JakeJackson : If you look at the first few lines of `ifelse` it is tested if `length(test) == 1` and either "yes" or "no" is evaluated; not both. – alexis_laz Sep 24 '14 at 09:32
  • @alexis_laz Many thanks. Then, I will need to either ignore the warning messages, which are harmless in this case, or to evaluate the function entry-wise. – Jake Jackson Sep 24 '14 at 09:34
  • Also, note that you will not get an warning if the test is always `TRUE` or always `FALSE`, provided `yes` or `no` evaluate without `NA` respectively. For instance, `temp(c(0.1,0.1))`. In general, if a function does not use an argument passed to it, it will not evaluate it. – mgriebe Sep 24 '14 at 09:40