【问题标题】:shiny - omitting a userinput with filter when "All" is selected闪亮的 - 选择“全部”时省略带有过滤器的用户输入
【发布时间】:2018-03-23 13:27:01
【问题描述】:

在 Ui.R 我有一些输入选择,其中 Location 是一个,如果选择“All”,我希望能够省略相同,

selectInput('Location', 'Location', choices = c("All", unique(sampleData$Location)), selected = "All"),

我尝试使用响应式 if else,但出现错误提示 -
“评估错误:操作只能用于数字、逻辑或复杂类型。”

我是 Shiny 的新手,我可以这样使用 inpLocation 吗? 任何帮助表示赞赏。

这是我的全部代码 -

library(plotly)
library(shiny)
load("sample_Data.rdata")
nms <- names(sample_Data)

ui <- (pageWithSidebar(
  headerPanel("Demo"),

  sidebarPanel(
    selectInput('sex', 'Sex', choices = unique(sample_Data$sex), selected = "F"),
    selectInput('Location', 'Location', choices = c("All", unique(sample_Data$Location)), selected = "All"),
    selectInput('color1', 'Color1', choices = c('None', nms), selected = "region"),
    selectInput('color2', 'Color2', choices = c('None', nms), selected = "species")
  ),

  mainPanel(
    fluidRow(
      column(12, plotlyOutput("p1"))
    ),
    fluidRow(
      column(12, plotlyOutput("p2"))
    )
  )
))

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

  nms <- row.names(sample_Data)
    dataset <- reactive({
      inpLocation <- reactive({
        if(input$Location == "All"){
          sample_Data$Location
        }else{
          input$Location
        }})

      sample_Data %>%
        filter(sex %in% input$sex, inpLocation())
    })

  output$p1 <- renderPlotly({
    p<-qplot(year,N,data=dataset(),color=species)
    if (input$color1 != 'None') p <- p + aes_string(color=input$color1)
    p<-ggplotly(p)
    p
  })

  output$p2 <- renderPlotly({
    p<-qplot(region,N,data=dataset(),color=species)
    if (input$color2 != 'None') p <- p + aes_string(color=input$color2)
    p <- ggplotly(p)
    p
  })
}

shinyApp(ui, server, options = list(display.mode = "showcase"))

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    在第一个 reactive 调用中不需要第二个 reactive。在外部reactive 内部,只要input$Location 发生更改,它就会被更新。

    dataset <- reactive({
      if(input$Location == "All"){
        inpLocation <- sample_Data$Location
      }else{
        inpLocation <- input$Location
      }
      sample_Data %>%
        filter(sex %in% input$sex, 
               Location %in% inpLocation)
    })
    

    【讨论】:

    • 嗨,非常感谢您澄清这一点,我想知道最后一条语句中“inpLocation()”的用途是什么?根据您的建议,它给了我一个错误 "no applicable method for 'filter_' applied to an object of class "character"
    • 我已经编辑了我的答案。当我应该将位置分配给 inpLocation 时,我不小心将位置分配给了数据集。希望它现在可以工作
    • 我相信它解决了,非常感谢。只是想知道使用“sample_Data$Location”是否会给我整列..?
    • 是的,它会给你一个包含所有值的向量。您可以通过在控制台中输入 sample_Data$Location 来确认这一点(假设您已将 sample_Data 加载到全局环境中)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 2015-01-19
    • 2018-08-09
    • 2021-07-16
    • 2015-05-06
    • 1970-01-01
    • 2017-11-25
    相关资源
    最近更新 更多