LeMarque
LeMarque

Reputation: 783

error in function evaluation and running if else loop for specific condition based upon user input

I am trying to write a function that accepts the user input from the command prompt. If user gives input either 'Y' or 'y' or 'Yes' or '1' then the execution of the function happens otherwise it exits from the if else loop:

myfunc <- function(){ 
  if( exists("result") ) { remove(result) }

  while(identical(flg_cont <- readline("Do you want to continue? :"), "y")){
   ## some code here ##
   if(!exists("result")){

    ## some other code here ##

  } else {

    ## some other code here ##

  }    
}
}

I want to check for user input either 'Y' or 'y' or 'yes' or 'YES' or 'Yes' or '1' is true the function should run for 'empty' (NULL) entry or 0, the function would exit.

Also it seems that if( exists("result") ) { remove(result) } is not correctly placed in the loop, because multiple iterations are deleting the result vector.

Upvotes: 0

Views: 31

Answers (1)

Cedric
Cedric

Reputation: 2474

You don't need to remove result if you are in a function, by default it will be removed from the functions environment only rm(pos=-1). Read this to understand what are functions environment http://adv-r.had.co.nz/Environments.html#function-envs.

You could use the %in% statement like

flg_cont <- readline("Do you want to continue? :")
if (flg_cont %in% c("y","Y",1)) {

your statement there

}

From your code, it is also unclear what is result clearly it's not what the user return. So it's not easy to understand what you want to do.

Finally you shoud add a return() statement to your function, while not necessary, it makes your code clearer, it is the input that is finally returned .GLobalEnv

Upvotes: 2

Related Questions