Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)
edited by

In the function named foo, I assumed that because of working with the if-else when I input a vector for the input values, I get a vector output.

The following function should return > [1] 1   6 in the output, but I am only getting > [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))

1 Answer

0 votes
by (107k points)

Let me tell you that in R programming, the output of the if-else returns the same length as input (test). From? if-else, you will get to know that if-else returns a value with the same shape as a test.

As, the mdif is of length 1 it provides the output of the same length i.e [1] 1. So it is better to use if for scalars and if-else 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

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...