0

I want to ask the user to select any of the options from 1 to 4 and then use the switch statement to transfer the flow accordingly. I have followed this

How to use the switch statement in R functions?

interactive()
num1 <-readline("Select any one of the options")
num <- noquote(num1)
switch(num, 
1={
  cat('You have selected option 1')
},
2={
  print('You have selected option 2')    
},
3={
  #Option 3
  print('You have selected option 3')    
},
4={
  #Option 4
  print('You have selected option 4')    
},
{
   print('dah make your mind,look at the options again')
}
)

The thing is its not working when I pass a string or number from the readline into switch. I removed the quotes and checked again but still it doesn't work.

I just saved the file and running it like source("file_name.R") Ultimately I want to build an interactive environment, where I collect the variables from the user and perform different tasks based on the options selected by the user.

How can I make it work?

Community
  • 1
  • 1
cppiscute
  • 707
  • 2
  • 10
  • 33
  • 2
    Don't use `noquote`, use `as.integer` – Julián Urbano May 29 '14 at 19:30
  • @JuliánUrbano thanks. I worked out with as.numeric but forgot to check as.integer. and also "=" did not work here for me, so I replaced with "==" and its fine now. thanks. – cppiscute May 29 '14 at 19:34
  • @JuliánUrbano , if I enter special character or a value other than integer it shows warning message like "Warning message: In eval(expr, envir, enclos) : NAs introduced by coercion " ........How can I show proper error message for this. like the default statement in the code. – cppiscute May 29 '14 at 19:36
  • 1
    `switch` works differently for numeric and character inputs. You need to read the help page more carefully. It's a primitive function so if you want the error messages to be different you will need to wrap the call and pre-pend your tests and messaging on your own. – IRTFM May 29 '14 at 20:13
  • @BondedDust...Thanks. thats too technical for me. but this is what I think that works in this scenario ....I can check the class of num1 and if its numeric then only I will pass it on to switch, may be I need to wrap the switch statement inside a function call....I will work on it.....does it sound good? – cppiscute May 29 '14 at 20:26
  • Right, just like I said :-) – IRTFM May 29 '14 at 21:58

0 Answers0