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
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.
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.
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 astest
which is filled with elements selected from eitheryes
orno
depending on whether the element oftest
isTRUE
orFALSE
.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With