Search code examples
rreturn

return value and end function


I want to return value from the function and end the function on the line where value is returned.

myfunc <- function(){   
    if(TRUE){
        return(1) #end function here and do not execute the rest of the code.
    }
    if(FALSE){
        return(2)
    }
   return(3)
} 

but when execute this function it returns 3. how can I return only value if the first condition is true?


Solution

  • myfunc <- function(condition){   
        if(condition) return(1)
        else return(2)
    } 
    
    myfunc <- function(condition){   
        if(condition) return(1)
        2 # the last call in a function is returned
    } 
    
    myfunc()
    
    [1] 1