rnorouzian
rnorouzian

Reputation: 7517

ifelse not returning a vector in BASE R

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

Answers (2)

akrun
akrun

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

Ronak Shah
Ronak Shah

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

Related Questions