Home > Software design >  how to define a rank of values for an argument inside a function?
how to define a rank of values for an argument inside a function?

Time:09-17

Let's suppose the next function:

demo_function <- function(x){

  if(is.na(x)){

    return(NA)

  } else if(1 < x < 2){
    
    return("something")
    
  } else {
    return("Nothing")
  }
}

The idea is that when the argument x is between 1 and 2, say x=0.001, then the function returns something.

However when trying to run the above function, the next error arises:

Error: no function to go from, jumping to a higher level

How could I adjust the function in order to get "something" for the specified argument?

CodePudding user response:

The issue is in the else if i.e. the syntax in R is different than the mathematical notation - multiple expressions are connected by logical operators

else if(1 < x  && x < 2)

i.e.

demo_function <- function(x){
 
   if(is.na(x)){
 
     return(NA)
 
   } else if(1 < x && x < 2){
     return("something")
   } else {
     return("Nothing")
   }
 
 }
> demo_function(0.01)
[1] "Nothing"
> demo_function(1.5)
[1] "something"
> demo_function(NA)
[1] NA
  • Related