首页 > 解决方案 > R闪亮中的多个反应选择输入

问题描述

我一直在使用以下代码来允许多个选择输入相互反应。因此,当一个被更改时,其他框中的值也会更新:

l <- NULL
l$name <- c('b','e','d','b','b','d','e')
l$age <- c(20,20,21,21,20,22,22)
l <- as.data.frame(l)
l$name <- as.character(l$name)
l$age <- as.numeric(l$age)
library(shiny)

server <- shinyServer(function(input,output, session){

  data1 <- reactive({
    if(input$Box1 == "All"){
      l
    }else{
      l[which(l$name == input$Box1),]
    }
  })

  data2 <- reactive({
    if (input$Box2 == "All"){
      l
    }else{
      l[which(l$age == input$Box2),]
    }
  })

  observe({

    if(input$Box1 != "All"){
      updateSelectInput(session,"Box2","Choose an age", choices = c("All",unique(data1()$age)))
    }

    else if(input$Box2 != 'All'){
      updateSelectInput(session,"Box1","Choose a name", choices = c('All',unique(data2()$name)))
    }

    else if (input$Box1 == "All" & input$Box2 == "All"){
      updateSelectInput(session,"Box2","Choose an age", choices = c('All',unique(l$age)))
      updateSelectInput(session,"Box1","Choose a name", choices = c('All',unique(l$name)))
    }
  })


  data3 <- reactive({
    if(input$Box2 == "All"){
      data1()
    }else if (input$Box1 == "All"){
      data2()
    }else if (input$Box2 == "All" & input$Box1 == "All"){
      l
    }
    else{
      l[which(l$age== input$Box2 & l$name == input$Box1),]
    }
  })

  output$table1 <- renderTable({
    data3()
  })


})



ui <-shinyUI(fluidPage(
  selectInput("Box1","Choose a name", choices = c("All",unique(l$name))),
  selectInput("Box2","Choose an age", choices = c("All",unique(l$age))),
  tableOutput("table1")
))

shinyApp(ui,server)

这适用于 2 个选择输入框,但我不知道如何添加更多。

我总共有 4 个选择输入需要相互反应(以及更新反应数据框)。

我是 R 和 Shiny 的新手。

标签: rshinysubsetdropdownreactive

解决方案


如果您只是想获取子集数据和/或过滤值,那么您的工作太辛苦了。该包使用过滤行的索引DT填充输入值,并自动提供适合类的过滤器。请注意,我们subsetted_data()在不同的渲染中使用 来生成更多的 ui 元素。

library("shiny")
library("DT")

ldata <- data.frame(
  name = c('b','e','d','b','b','d','e'),
  age  = c(20,20,21,21,20,22,22)
)

#

server <- shinyServer(function(input,output, session){

  output$ldata_table <- renderDataTable({
    datatable(ldata, filter = "top")
  })

  subsetted_data <- reactive({
    # the input$<shiny-id>_rows_all populated by the DT package,
    # gets the indices of all the filtered rows
    req(length(input$ldata_table_rows_all) > 0)

    ldata[as.numeric(input$ldata_table_rows_all),]
  })

  output$state <- renderPrint({
    summary(subsetted_data())
  })
})

ui <- fluidPage(
  dataTableOutput("ldata_table"),
  verbatimTextOutput("state")
)

shinyApp(ui, server)

在此处输入图像描述


推荐阅读