Explore Courses Blog Tutorials Interview Questions
0 votes
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(!, mdif, ifelse(! & ! &, mpos - mpre, NA))



foo(c(1,3), c(2,9))

1 Answer

0 votes
by (108k 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(! mdif 

     else ifelse(! & ! &, mpos - mpre, NA)


foo(c(1,3), c(2,9))

#[1] 1 6

Browse Categories