Блестящее приложение запускается, когда код представлен в консоли, но не при нажатии кнопки «Запустить приложение». - PullRequest
0 голосов
/ 10 мая 2019

Я создаю блестящее приложение и замечаю, что когда я отправляю код на консоль, все загружается правильно и работает как положено;Однако, когда я рендерим приложение с помощью кнопки «Запустить приложение», я получаю ошибки.

В частности, когда я использую кнопку «Запустить приложение», в приложении появляется следующая ошибка: «Ошибка: не удается открыть соединение».Кроме того, я получаю эту ошибку в консоли: «Ошибка: не удается открыть соединение», в то время как консоль гласит: «Предупреждение в gzfile (file,« rb »): невозможно открыть сжатый файл« DATA // grm_mod.rds »Возможная причина: «Нет такого файла или каталога»

Приложение простое: пользователь загружает файл данных, в то время как на сервер загружается объект R-модели, оценки оцениваются из модели и результатыотобразить в таблице, которую пользователь может загрузить.

Какова вероятная причина этой ошибки?Обратите внимание, что вероятный источник ошибки находится под комментарием кода «Шаги преобразования» в логике сервера.

Спасибо.

# load packages
if(!require("pacman"))install.packages("pacman")
p_load(dplyr, shiny, shinythemes, mirt)

# Define UI for data upload app ----
ui <- fluidPage(

  # Set theme ----
  theme = shinytheme("superhero"),

  # App title ----
  titlePanel("Raw Score to MAP Score Conversion"),

  # Sidebar layout with input and output definitions ----
  sidebarLayout(

    # Sidebar panel for inputs ----
    sidebarPanel(

      # Input: Select a file ----
      fileInput("file1", "Choose CSV File",
                multiple = FALSE,
                accept = c("text/csv",
                           "text/comma-separated-values,text/plain",
                           ".csv")),

      # Horizontal line ----
      tags$hr(),

      # Input: Checkbox if file has header ----
      checkboxInput("header", "Header", TRUE),

      # Input: Select separator ----
      radioButtons("sep", "Separator",
                   choices = c(Comma = ",",
                               Semicolon = ";",
                               Tab = "\t"),
                   selected = ","),

      # Input: Select quotes ----
      radioButtons("quote", "Quote",
                   choices = c(None = "",
                               "Double Quote" = '"',
                               "Single Quote" = "'"),
                   selected = '"'),

      # Horizontal line ----
      tags$hr(),

      # Input: Select number of rows to display ----
      radioButtons("disp", "Display",
                   choices = c(Head = "head",
                               All = "all"),
                   selected = "head")
    ),

    # Main panel for displaying outputs ----
    mainPanel(

      # Output: Data file ----
      tableOutput("contents"),

      # Download button
      downloadButton('downloadData', 'Download')

    )

  )
)

# Define server logic to read selected file ----
server <- function(input, output) {

  output$contents <- renderTable(striped = TRUE,
    {

    # input$file1 will be NULL initially. After the user selects
    # and uploads a file, head of that data file by default,
    # or all rows if selected, will be shown.

    req(input$file1)

    # when reading semicolon separated files,
    # having a comma separator causes `read.csv` to error
    tryCatch(
      {
        df <- read.csv(input$file1$datapath,
                       header = input$header,
                       sep = input$sep,
                       quote = input$quote)
      # Conversion steps ----

       # import the model object
       mod <- readRDS('DATA//grm_mod.rds')

       # generate scores 
       df <- data.frame(fscores(obj = mod, type = 'MAP', response.pattern = df))

       # transform scores
       x10_50 <- function(x) {
         10 * x + 50
       }

       df <- 
         df %>%
         mutate_at(vars(matches("^F.$")), .funs = list(T = ~x10_50(.)))

       # add download handler
       output$downloadData <- downloadHandler(
         filename = function() { paste(input$file1, '.csv', sep='') },
         content = function(file) {
           write.csv(df, file, row.names = FALSE)
         }
       )

      },
      error = function(e) {
        # return a safeError if a parsing error occurs
        stop(safeError(e))
      }
    )

    if(input$disp == "head") {
      return(head(df))
    }
    else {
      return(df)
    }

    # download 
    output$downloadData <- downloadHandler(
      filename = function() {
        paste('data-', Sys.Date(), '.csv', sep='')
      },
      content = function(file) {
        write.csv(data, file)
      }
    )
  })

}

# Create Shiny app ----
shinyApp(ui, server)

1 Ответ

1 голос
/ 10 мая 2019

Путь к файлу относится к Shiny App, а не к вашему рабочему каталогу, поэтому при использовании runApp() и вызове readRDS('DATA//grm_mod.rds') он ожидает каталог DATA, который является подкаталогом каталога, в котором находится файл .R, который содержит ваше приложение хранится. Если вы переместите DATA в тот же каталог, что и app.r, это должно сработать.

...