Reputation: 7517
Maybe this is too basic of a question. But in my function foo
below, I expected that because of using ifelse
when I input a vector for the input values, I get a vector output.
But I wonder why in the example below instead of getting > [1] 1 6
in the output, I just get > [1] 1
as the output?
foo <- function(mpre = NA, mpos = NA, mdif = NA){
ifelse(!is.na(mdif), mdif, ifelse(!is.na(mpre) & !is.na(mpre) & is.na(mdif), mpos - mpre, NA))
}
## EXAMPLE:
foo(c(1,3), c(2,9))
Upvotes: 1
Views: 53
Reputation: 887048
We can also do
foo <- function(mpre, mpos, mdif = NA){
if(!is.na(mdif)) mdif
else ifelse(!(is.na(mpre) | is.na(mpre)) & is.na(mdif), mpos - mpre, NA)
}
foo(c(1,3), c(2,9))
Upvotes: 1
Reputation: 388907
ifelse
returns output of same length as input (test
). From ?ifelse
ifelse returns a value with the same shape as test
Since mdif
is of length 1 it returns output of same length i.e [1] 1
. Use if
for scalars and ifelse
for vectors.
foo <- function(mpre, mpos, mdif = NA){
if(!is.na(mdif)) mdif
else ifelse(!is.na(mpre) & !is.na(mpre) & is.na(mdif), mpos - mpre, NA)
}
foo(c(1,3), c(2,9))
#[1] 1 6
Upvotes: 3