R — ошибка «нечисловой аргумент двоичного оператора» в shiny

#r #matrix #shiny

#r #матрица #блестящий

Вопрос:

Я очень новичок в r (и программировании в целом), и нас попросили создать веб-приложение с использованием r shiny, план состоял в том, чтобы создать калькулятор матричных операций из разных входных файлов (первый файл .cvs содержит матрицу 1, второй файл .cvs содержит матрицу 2), но ошибка продолжаетпоявляется

  Listening on http://127.0.0.1:3420
 Warning: Error in FUN: non-numeric argument to binary operator
 99: eval
 98: eval
 97: Ops.data.frame
 96: renderTable [C:/Users/Acer/Desktop/FirstWebApp/app (1).R#45]
 95: func
 82: origRenderFunc
 81: output$oput
  1: runApp
 

это мой пользовательский интерфейс

      ui <- fluidPage(
  titlePanel("Multiple file uploads"),
  sidebarLayout(
    sidebarPanel(
     fileInput("file1",
               label="Upload CSVs here"),
     fileInput("file2", "upload file here"),
     selectInput("ops", "Select Operation",
                 choices = c("addition","subtraction","multiplication","division"))
     
  ),
  mainPanel(
     tableOutput("input_file"),
     tableOutput("input_file2"),
     tableOutput("oput")
 

и мой server выглядит так

 server <- function(input, output) {
output$input_file <- renderTable({
  file_to_read =  input$file1
  if (is.null(file_to_read)) {
    return()
 }
  read.table(file_to_read$datapath, sep = ',', header = FALSE)
})

output$input_file2 <- renderTable({
  file_to_read =  input$file2
  if (is.null(file_to_read)) {
    return()
  }
  read.table(file_to_read$datapath, sep = ',', header = FALSE)
})
output$oput <- renderTable({
switch(input$ops,
       "addtion" = input$file1   input$file2,
       "subtraction" = input$file1 - input$file2,
       "multiplication" = input$file1 * input$file2,
       "division" = input$file1 / input$file2)
})
}
 

как мне это исправить, и если эта ошибка будет исправлена, будет ли программа запущена?

Ответ №1:

Ваш пользовательский интерфейс хорош, нет необходимости что-либо менять. Но в вашем серверном коде есть незначительные исправления. Проблема заключается в вашем случае переключения:

 switch(input$ops,
       "addtion" = input$file1   input$file2,
       "subtraction" = input$file1 - input$file2,
       "multiplication" = input$file1 * input$file2,
       "division" = input$file1 / input$file2)
})
 

здесь вы добавляете входные данные $file1 и вводите $file2. ввод $file1 — это не матрица ваших данных, а фрейм данных:

 Browse[1]> input$file1
       name size     type
1 file1.csv   21 text/csv
                                                                          datapath
1 C:UserstempAppDataLocalTempRtmpCEZJPF/957a518de2fae08f6a7b7201/0.csv
 

Поэтому вам необходимо сохранить ваши матричные данные в reactiveVal() для их последующего использования в случае переключения

 server <- function(input, output) {
  
  file1_Result <- reactiveVal(NULL)
  file2_Result <- reactiveVal(NULL)
  
  
  output$input_file <- renderTable({
    file_to_read =  input$file1
    if (is.null(file_to_read)) {
      return()
    }
   Result <- read.table(file_to_read$datapath, sep = ',', header = FALSE)
   file1_Result(Result)
   return(Result)
  })
  
  output$input_file2 <- renderTable({
    file_to_read =  input$file2
    if (is.null(file_to_read)) {
      return()
    }
    Result <- read.table(file_to_read$datapath, sep = ',', header = FALSE)
    file2_Result(Result)
    return(Result)
  })
  output$oput <- renderTable({
    browser()
    switch(input$ops,
           "addtion" = file1_Result()   file2_Result(),
           "subtraction" = file1_Result() - file2_Result(),
           "multiplication" = file1_Result() * file2_Result(),
           "division" = file1_Result() / file2_Result())
  })
}
 

Надеюсь, это сработает 🙂

Комментарии:

1. Абсолютный спаситель! Спасибо!!