How to parse a string in a calculator in R?

Viewed 87

I wrote a calculator program in which the User enters two numbers and an arithmetic operation between the numbers, then presses Enter and gets the result, or rather did a string parsing, but it doesn't work. What can this be related to? I also wrote the code so that I could exit the function

  add<- function(x,y){
      return(x+y)
    }
      subtract <- function(x,y){
      return(x-y)
    }
      multiply <- function(x, y) {
         return(x * y)
    }
      div <- function(x,y){
        if(y==0){
          return("Error")
          break
    }
      else if(y!=0){
        return(x%/%y)
      }
      
    }
    
   
      res<-NA
       repeat{
    print("9", quote=FALSE)
    user_string <-
      readline(prompt = ("Enter: "))
    
    if(user_string== 9){
      break # to stop the programme
    }
    
    components_of_user_string <-
      unlist(strsplit(user_string, split = '')) #splitting the line

      num1<-as.numeric(components_of_user_string[1]) #first number
      num2<-as.numeric(components_of_user_string[3]) # second number


    us_chosen_operation <-
      components_of_user_string[2]
    operations_vector <-
      c('+', '-', '*', '/') 
    choice <- match(us_chosen_operation, operations_vector)
    operator <- switch(choice, ' + ', ' - ', ' * ', ' / ')
    
    result <-
      switch(
        choice,
        add(num1, num2),
        subtract(num1, num2),
        multiply(num1, num2),
        divide(num1, num2)
      )
    print(paste(num1, operator, num2, "=", result))
}
1 Answers

String parsing with eval(parse(...)) could be an option :

repeat {
  input <- readline(prompt = ("Enter: "))
  print(eval(parse(text = input))) 
}

# Enter: (-4)+2
# [1] -2
# Enter: raise_to_degree(2,3)
# [1] 8

Related