Управление кадром данных в блестящем через несколько вкладок - PullRequest
0 голосов
/ 28 декабря 2018

Я только начинаю с «блестящего», и у меня возникают трудности с пониманием того, как я могу импортировать фрейм данных из локального каталога и сохранить его как набор данных для использования в следующих шагах.По сути, я хотел бы иметь вкладку импорта, подобную этой: https://shiny.rstudio.com/gallery/file-upload.html

Во второй я хотел бы иметь возможность фильтровать фрейм данных по именам столбцов, как здесь:

https://shiny.rstudio.com/gallery/datatables-demo.html

И, наконец, сохраните фрейм данных.

Первая вкладка для импорта работает, однако вторая не распознает импортированный фрейм данных и не отображает его.

Ниже приведен код, который я использую

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

mainPanel(
tabsetPanel(id = "mainPanel",
  # Uplaod panel ----------------
  tabPanel("Upload",
           # 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: 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")
             )
           ) 
  ),
  # Data manipulation ------------------------
  tabPanel('Data manipulation',
    titlePanel("Filtering columns"),
    sidebarLayout(
      sidebarPanel(
        conditionalPanel(
          'input.file1',
          checkboxGroupInput("show_vars", "Columns in data frame to keep:",
                             names(output$contents), selected = names(output$contents))
        )),
      mainPanel(
          tabPanel(tableOutput("dfFilter"))
        )
      )
    ),
  # Saving Data -----------------------------
  tabPanel("Output", tableOutput("table"))
)
)
)
# Define server logic to read selected file ----
server <- function(input, output) {

df <- eventReactive(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,
                   row.names = 
    )
  },
  error = function(e) {
    # return a safeError if a parsing error occurs
    stop(safeError(e))
  }
)

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

})
output$contents = renderTable({
df()
})
# choose columns to display
output$dfFilter = renderTable(
{
  df()[, colnames(df()) %in% input$show_vars]
 }
 )
 }
 options(shiny.maxRequestSize=30*1024^2) 
 shinyApp(ui = ui , server = server)

Редактировать 1 --------------------------------------------------------------------------

Спасибо за ваш комментарий Стефан Лоран.Мне удалось отобразить checkboxGroupInput в соответствии с введенным пользователем фреймом данных, однако у меня возникла новая проблема, касающаяся фильтрации этого фрейма данных по столбцам, выбранным в checkboxGroupInput (я пытался отрендерить его через renderUI, но он не работал).

Ниже приведен новый код

library(shiny)
library(shinythemes)
# Define UI for data upload app ----
ui <- fluidPage(
  theme = shinytheme("darkly"),
  mainPanel(
    tabsetPanel(id = "mainPanel",
      # Uplaod panel ----------------
      tabPanel("Upload",
               # 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")
                 )
               ) 
      ),
      # Data manipulation ------------------------
      tabPanel('Column selection',
        sidebarLayout(
          sidebarPanel(
            conditionalPanel(
              condition = "output.contents",
              uiOutput("cols")
            )),
          mainPanel(
              uiOutput("dfFilter")
            )
          )
        ),
      # Saving Data -----------------------------
      tabPanel("Save", tableOutput("table"))
    )
  )
)

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

  df <- eventReactive(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,
                       row.names = 
        )
      },
      error = function(e) {
        # return a safeError if a parsing error occurs
        stop(safeError(e))
      }
    )

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

  })
  output$contents = renderTable({
    df()
  })
  output$cols <- renderUI({
    names <- colnames(df())
    checkboxGroupInput("show_vars", "Columns in data frame to keep:",
                      names, selected = names)
  })

  # choose columns to display
  output$dfFilter = renderUI(
    {
      renderTable(
        {reactive({
          df()[, colnames(df()) %in% output$cols]
        })
        }
      )
    }
  )
}
options(shiny.maxRequestSize=30*1024^2) 
shinyApp(ui = ui , server = server)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...