Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read a numeric expression from user in R studio

I want to read a numeric expression (ex:- 9/3) from the user during runtime and print the answer(3). I used readline() but since it reads the line as a string, when as.numeric() function is applied the output is NaN. How do I convert the expression to get a numeric value?

This is the code I used.

expression = readline(prompt = "Enter the expression : ");

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

exp = as.numeric(expression)

>Solution :

expression = readline(prompt = "Enter the expression : ")
exp = eval(parse(text=expression))
  • this is potentially dangerous (the user could enter, e.g., system('del important_file.txt'))
  • both exp and expression also refer to built-in functions in R; this code will work, but it’s best practice to avoid names of existing functions
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading