R Shiny:eventReactive和renderUI交互

时间:2017-11-26 17:44:34

标签: r shiny

我正在尝试为这个Shiny做一个类似的应用程序:动态数据帧构造; renderUI,observe,reactiveValues。我想创建一个选项,例如,选择列表中的柱面数。这样在选择号码后表格会自动更新。有人可以向我解释我做错了什么吗?正如您在图形程序中看到的那样,效果不佳。enter image description here

我的代码:

UI:

library(shiny)

hw <- mtcars

shinyUI(fluidPage(
  title = 'Examples of DataTables',
  sidebarLayout(
    sidebarPanel(

      radioButtons(
        inputId="radio",
        label="Variable Selection Type:",
        choices=list(
          "All",
          "Manual Select"
        ),
        selected="All"),

      conditionalPanel(
        condition = "input.radio != 'All'",
        selectizeInput(
          'show_vars', 
          'Columns in cars to show:',
          choices=names(hw), 
          selected = names(hw),
          multiple =TRUE),

        uiOutput("category1")
      )

    ),
    mainPanel(
      verbatimTextOutput("summary"), 
      tabsetPanel(
        id = 'dataset',
        tabPanel('hw', dataTableOutput('mytable1'))
      )
    )
  )
))

服务器:

library(shiny)
library(ggplot2)

shinyServer(function(input, output) {


  Data <- reactive({

    if(input$radio == "All"){
      hw
    } else {
      hw[,input$show_vars,drop=FALSE]
    }

  })

  output$category1 <- renderUI({
    selectizeInput('cat1', 'Select cyl:', choices = c("All",sort(as.character(unique(hw$cyl)))),selected = "All")

  })

  df_subset <- eventReactive(input$cat1,{
    if(input$cat1=="All") {df_subset <- hw}
    else{df_subset <- hw[hw$Position == input$cat1,]}
  })


  output$mytable1 <- renderDataTable({
     df_subset()
      hw[, input$show_vars, drop = FALSE]
  })
})

1 个答案:

答案 0 :(得分:1)

以下是您示例的信息中心:

# Packages
library(shiny)
library(DT)
library(dplyr)

# UI
ui <- fluidPage(   
  # Application title
  titlePanel("Example"),

  # Sidebar
  sidebarLayout(
     sidebarPanel(selectInput("si_cylinders", "Cylinders", 
                 choices = sort(unique(mtcars$cyl)), selected = "4")),
     mainPanel(dataTableOutput("dt_mtcars"))))

  # Server
  server <- function(input, output) {

  # Data set for output
  df_mtcars <- reactive({
    # 1. Read UI element
    cylinder_selected <- as.numeric(input$si_cylinders[1])

    # 2. Filter data set
    df <- mtcars %>% filter(cyl == cylinder_selected)

   # 3. Return result
   return(df)
  })

  # 2. Data table for output
  output$dt_mtcars <- renderDataTable({
    datatable(df_mtcars())
  })

 }

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