更改数据集时,在闪亮的应用程序中动态显示列名称会闪烁错误

时间:2019-02-22 00:00:36

标签: r shiny dplyr

我有一个闪亮的应用程序,我想让用户根据一组上传的文件选择一个数据集,然后指定要从所选数据集中显示的列。如果我选择了一些列然后切换数据集,则会闪烁一个错误,并输出到控制台,指出在应用程序切换数据集并正确显示之前,所选列是未知的。但是,在我的完整应用程序中,该应用程序崩溃了,尽管我无法弄清楚如何重现崩溃。我认为这可能与某些预处理有关,该预处理完成了添加其他列的操作,这些列在数据集中是相同的,并且仍保持选中状态,但是如果没有该功能,则错误是相同的。

library(shiny)
library(tidyverse)
library(DT)


ui <- fluidPage(
  checkboxGroupInput("select_var", label = "Select Variables"),
  selectInput("dataset", label = NULL, choices = c("mtcars", "rock")),
  DT::dataTableOutput("table")

)


server <- function(session, input, output) {
  # define the dataset
  data <- reactive({switch(input$dataset,"rock" = rock,"mtcars" = mtcars)})

  # add a common column name that is always selected
  dataprocessed <- reactive({data <- data()
                             data$num <- seq(1:nrow(data))
                             return(data)})

  # dynamically generate the variable names
  observe({
    vchoices <- names(dataprocessed())
    updateCheckboxGroupInput(session, "select_var", choices = vchoices, selected = c("num"))
  })

  # select the variables based on checkbox
  data_sel <- reactive({
    req(input$select_var)
    df_sel <- dataprocessed() %>% select(input$select_var) 
      })

  output$table <- DT::renderDataTable(data_sel())
}

# Run the application 
shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:1)

我们可以使用req()添加一个条件需求,以在呈现之前测试列是否存在:

library(shiny)
library(tidyverse)
library(DT)

ui <- fluidPage(
  checkboxGroupInput("select_var", label = "Select Variables"),
  selectInput("dataset", label = NULL, choices = c("mtcars", "rock")),
  DT::dataTableOutput("table")

)

server <- function(session, input, output) {
  # define the dataset
  data <- reactive({
    switch(input$dataset,"rock" = rock,"mtcars" = mtcars)
  })

  # add a common column name that is always selected
  dataprocessed <- reactive({
    data <- data()
    data$num <- seq(1:nrow(data))
    return(data)
  })

  # dynamically generate the variable names
  observe({
    vchoices <- names(dataprocessed())
    updateCheckboxGroupInput(session, "select_var", choices = vchoices, selected = c("num"))
  })

  # select the variables based on checkbox
  data_sel <- reactive({
    req(input$select_var)
    req(names(dataprocessed()) %in% input$select_var)
    a <- names(dataprocessed())[names(dataprocessed()) %in% input$select_var]
    df_sel <- dataprocessed() %>% select(a) 
  })

  output$table <- DT::renderDataTable(data_sel())
}

# Run the application 
shinyApp(ui = ui, server = server)