1

While writing a function, I need to write the following:

x<-rnorm(10)
y<-ifelse(mean(x)>=0,rexp(10,1/mean(x)),-rexp(10,-1/mean(x)))

Like x, I expect y to be a vector with length 10, but surprisingly it only outputs a single numeric value. Reproducible example as follows.

set.seed(10)
x<-rnorm(10)
y<-ifelse(mean(x)>=0,rexp(10,1/mean(x)),-rexp(10,-1/mean(x)))

> x
 [1]  0.01874617 -0.18425254 -1.37133055 -0.59916772  0.29454513  0.38979430
 [7] -1.20807618 -0.36367602 -1.62667268 -0.25647839

y<-ifelse(mean(x)>=0,rexp(10,1/mean(x)),-rexp(10,-1/mean(x)))

> y
[1] -0.2092798

What am I missing here? why is y not a list with length 10, even when specified in the condition?

Interestingly, when I encoded the same condition with separate if-else blocks, and it works as expected. But why doesn't the same logic work when executed in this way? some clarification would surely help. Thanks in advance.

nb1
  • 111
  • 2

1 Answers1

1

ifelse can only return one value. Try with a common if else statement instead:

if(mean(x)>=0) y <- rexp(10,1/mean(x)) else y <- -rexp(10,-1/mean(x))

Val
  • 6,585
  • 5
  • 22
  • 52
  • Thanks, and that's what I did in the end, just wanted to know if it could be done using ifelse as well. So one can't use ifelse if list output is required? – nb1 Jun 20 '17 at 15:28
  • 1
    Got it, thanks. One should just make the output as list(). Will add the answer, taking a clue from dupe. – nb1 Jun 20 '17 at 15:31
  • 1
    With clue from this: https://stackoverflow.com/questions/40340081/return-a-matrix-with-ifelse If one just adds list() for the outputs, it works as expected, i.e. y<-ifelse(condition, list(output1), list(output2)). – nb1 Jun 20 '17 at 15:32