【问题标题】:R shiny: multiple inputs in reactive{}R 闪亮:反应式中的多个输入{}
【发布时间】:2016-04-12 23:37:07
【问题描述】:

嗨,我对 Shiny 很陌生。我正在尝试为我的用户创建两个交互式 selectInputs 以在表中显示数据。这是我的代码的样子: ui.R

library(shiny)

shinyUI(fluidPage(

  sidebarLayout(
    sidebarPanel(

      selectInput("var", 
                  label = "Country",
                  choices = c("ALL",  "A2", "AE")),
      selectInput("plat", 
                  label = "Platform",
                  choices = c("ALL", "Android", "IPhonePlayer"))
      )
    ),
    mainPanel(

      tableOutput(
        "view"))
  )
))

服务器.R

library(shiny)
library(ggplot2)
library(dplyr)
df <- readRDS("data/df.rds")

shinyServer(function(input, output) {

 datasetInput <- reactive({

    switch(input$var,
           "ALL" = df,
           "A2" = df %>% filter(country == "A2"),
           "AE" = df %>% filter(country == "AE"))


    switch(input$plat,
           "ALL" = df,
           "Android" = df %>% filter(platform == "Android"),
           "IPhonePlayer" = df %>% filter(platform == "IPhonePlayer"))



  })


   output$view <- renderTable({head(datasetInput())})

})

当我运行代码时,只有平台上的选择可以正常工作,而对于国家/地区,我进行选择时没有任何反应。关于我在这里犯了什么愚蠢的错误有什么想法吗?提前非常感谢您!

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    尝试将第一个switch 的结果分配给df。现在两个switch没有连接,reactive只返回第二个的结果。

    df <- switch(input$var,
           "ALL" = df,
           "A2" = df %>% filter(country == "A2"),
           "AE" = df %>% filter(country == "AE"))
    

    【讨论】:

    • 你能再详细点吗?我尝试按照您的建议分配它,但仍然得到相同的结果。我必须以错误的方式分配。谢谢!
    【解决方案2】:

    不是你要求的,但我认为你可以像这样改进你的代码:

    datasetInput <- reactive({
      df %>%
        filter(
          (input$var  == 'ALL' | country == input$var) &
          (input$plat == 'ALL' | country == input$plat)
        )
    })
    

    【讨论】:

    • 谢谢!这确实为我省去了一些麻烦。
    猜你喜欢
    • 2018-05-28
    • 2018-10-09
    • 2020-08-18
    • 2020-07-04
    • 2020-08-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多