Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ifelse() return single-value output? [duplicate]

Tags:

r

Those two functions should give similar results, don't they?

f1 <- function(x, y) {
   if (missing(y)) {
      out <- x
   } else {
      out <- c(x, y)
   }
   return(out)
}

f2 <- function(x, y) ifelse(missing(y), x, c(x, y))

Results:

> f1(1, 2)
[1] 1 2
> f2(1, 2)
[1] 1
like image 262
Tim Avatar asked Jan 05 '15 11:01

Tim


People also ask

What does ifelse() do in R?

The 'ifelse()' function is the alternative and shorthand form of the R if-else statement. Also, it uses the 'vectorized' technique, which makes the operation faster. All of the vector values are taken as an argument at once rather than taking individual values as an argument multiple times.

Can Ifelse return vector in R?

In R, the ifelse() function is a shorthand vectorized alternative to the standard if...else statement. Most of the functions in R take a vector as input and return a vectorized output.


1 Answers

This is not related to missing, but rather to your wrong use of ifelse. From help("ifelse"):

ifelse returns a value with the same shape as test which is filled with elements selected from either yes or no depending on whether the element of test is TRUE or FALSE.

The "shape" of your test is a length-one vector. Thus, a length-one vector is returned. ifelse is not just different syntax for if and else.

like image 101
Roland Avatar answered Nov 15 '22 15:11

Roland