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.

4
  • What's the warning message? Please provide example input that replicates your issue.
    – Roland
    Sep 24, 2014 at 9:03
  • What is the warning?
    – mgriebe
    Sep 24, 2014 at 9:03
  • Because when p == 0.1, qnorm((p - 0.5)/(1 - 0.5)) gives an error.
    – user3710546
    Sep 24, 2014 at 9:07
  • ifelse evaluates both clauses and then subsets and combines them according to the condition
    – James
    Sep 24, 2014 at 9:30

1 Answer 1

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)
4
  • Thanks. Then, why this doesn't happen with scalar inputs? Sep 24, 2014 at 9: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, 2014 at 9: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. Sep 24, 2014 at 9: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, 2014 at 9:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.