Search code examples
ruser-input

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 : ");

exp = as.numeric(expression)


Solution

  • If you want to avoid the danger mentionned by @BenBolker you can use the Ryacas package:

    library(Ryacas)
    expression <- readline(prompt = "Enter the expression : ")
    yac_str(expression)