R Shiny проверить номер столбца входного файла - PullRequest
0 голосов
/ 21 ноября 2019

Я копирую пример приложения Shiny File Upload. Как видите, я добавил функцию проверки для типа файла. Я также установил фиксированные имена столбцов, потому что я хочу разрешить пользователю загружать только дату максимум для 5 столбцов.

Прямо сейчас, когда пользователь загружает файл, который содержит больше столбцов, чем разрешено, сообщение R будетотображается: more columns than column names.

Я хотел бы иметь функцию проверки / требовать, которая проверяет количество столбцов и показывает более удобное для пользователя сообщение. Моя идея состояла в том, чтобы использовать функцию validate с (ncol(input$file1)<=5)==TRUE, но почему-то это не работает. У кого-нибудь есть идеи, как проверить количество столбцов во входном файле и изменить отображаемое сообщение пользователя? (если это можно сделать с Шиньялертом, это было бы потрясающе!).

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

Заранее спасибо!

library(shiny)
library(tools)

ui <- fluidPage(

  # App title ----
  titlePanel("Uploading Files"),

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

    )

  )
)

server <- function(input, output) {

  output$contents <- renderTable({

    # 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 = F,
                       sep = input$sep,
                       quote = input$quote,
                       col.names = c("COL1","COL2","COL3","COL4","COL5"),
                       check.names = F)
      },

      validate(
        need(file_ext(input$file1$datapath) %in% c(
          'text/csv',
         'text/comma-separated-values',
          'text/tab-separated-values',
          'text/plain',
          'csv'
        ), "Data was not recognized. Please use a CSV file!")),

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

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

  })

}

shinyApp(ui,server)






1 Ответ

1 голос
/ 21 ноября 2019

Я попытался создать пример программы, в которой пользователь может загружать только набор данных csv только с 5 столбцами. Вы можете изменить согласно вашему требованию.

UI.R

library(shiny)
library(shinydashboard)
library(shinyjs)
library(shinyalert)


dashboardPage(
   dashboardHeader(title = "Basic dashboard"),
   dashboardSidebar(
      sidebarMenu(
         menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard"))
      )
   ),
   dashboardBody(
      useShinyalert(),
      tabItems(
         tabItem(tabName = "dashboard",
                 fluidRow(
                           column(3,

                                     fileInput("file1", "Choose CSV File",
                                               multiple = FALSE,
                                               accept = c("text/csv",
                                                          "text/comma-separated-values,
                                                            text/plain",
                                                          ".csv"))
                                  )

                        ),
                 fluidRow(
                    tableOutput("contents")
                        )
                 )
      )
   )
)

Server.R

library(shiny)
library(shinydashboard)


shinyServer(function(input,output){

  output$contents <- renderTable({
    inFile <- input$file1

    if (is.null(inFile))
    {
      returnValue()
    }
    else
    {
      data<-read.csv(inFile$datapath)
      if(ncol(data)<5)
      {
        shinyalert("Column Error","Uploaded Data has less than 5 Col",type="error")
        returnValue()
      }
      else if(ncol(data)>5)
      {
        shinyalert("Column Error","Uploaded Data has more than 5 Col",type = "error")
        returnValue()
      }
      else
      {
        return(data)
      }
    }

  })

})
...