Error: non-numeric argument to binary operator

1.8k views Asked by At

Good Day, making application in RStudio/Shiny is very new to me and I am working with a project in which an external file is to be used as the input data. Here is my CSV: Click to see: Wattage of an Appliance

my supposed to be app:

Click to see: calculator to compute electric bill

So the user insert a csv with appliance name in row 1 and their wattage in row 2 just like in the picture above, then the selectInput will be updated. The user choose what appliance and hours of usage then it will be calculated for its cost

Here is my server code:

server <- function(input,output,session) {
  
  observeEvent(input$file1, {
    
    mytable <- read.csv(input$file1$datapath)
    
    updateSelectInput(session, "select", "Appliances", 
                      choices = colnames(mytable))
    
  })
  
  dataset_day <- reactive ({
    costday <- ((input$select * input$hour) / 1000) * 8.9535
    costday <- data.frame(costday)
    names(costday)  <- "Electricity Cost per day (Philippine Peso)"
    print(costday)
  })
  
  dataset_month <- reactive ({
    costmonth <- (((input$select * input$hour) / 1000) * 8.9535) * 30
    costmonth <- data.frame(costmonth)
    names(costmonth)  <- "Electricity Cost per month (Philippine Peso)"
    print(costmonth)
  })

I need help in putting the value written in the CSV of the chosen appliance by the user to the equation.

In short how to fix the non-numeric argument to binary operator error.

I think the error is in the input$select but I am lost about this.

((input$select * input$hour) / 1000) * 8.9535

Do I need to change or add something in order to fix this? Is this app possible to do? Thank you in advance!

1

There are 1 answers

4
MrGumble On

This utterly non-descriptive error message is totally spot on, when you understand this backwards non-message:

You are trying to do math with something that is not numbers.

In this case, you are probably correct in that it occurs in input$select * input$hour, because either or both are probably characters. On the HTML side of your app, there are no numbers in the values. Only strings. So what do we get back?

Try inserting the Best Debugging Tool known to programmer: print-statements. Here, try simply adding an observer e.g.:

observe({
  cat('This is observer\n')
  str(input$select)
  str(input$hour)
})

You should now see something in your console like this:

This is observer
  chr "Bulb"
  num 12.0

or

This is observer
  chr "11"
  num 12.0

What does this imply? That input$select is not numeric, but a character string.

Solution: Convert it to numeric with e.g. as.numeric (latter case), or map it to something numeric (former case).