【发布时间】:2018-06-21 07:21:01
【问题描述】:
我需要知道如何根据在 ConditionalPanel() 上选择的输入值使用 filter() 函数从数据集中进行过滤。目前,我可以通过仅过滤反应数据中的一个值来实现这一点。但是,当我为数据集上的所有值完成命名过滤器时,无论在条件面板上选择什么选项,我都会得到一个图形作为输出。
这是用户界面
library(shiny)
ui <- fluidPage(
sidebarLayout(sidebarPanel(selectInput('brand', h4("Select brand"),
choices=c("Mazda", "Other")),
conditionalPanel(condition = "input.brand=='Mazda'",
selectInput("mazda", h4("Model"),
choices=c("RX4", "RX4 Wag"))),
conditionalPanel(condition = "input.brand=='Other'",
selectInput("other", h4("Model"),
choices=c("Toyota", "Other")))),
mainPanel(
plotOutput("graph")
)))
这里是服务器
server <- function(input, output) {
library(ggplot2)
library(dplyr)
#Here I adapt the mtcars data frame so the first column gives me the brand name#
mtcars2 <- tibble::rownames_to_column(mtcars)
colnames(mtcars2)[1] <- "brand"
#Done! now on to define reactive data#
plotdata <- reactive ({
if(input$mazda == "RX4") {
filter(mtcars2, brand=="Mazda RX4")}
else
if(input$mazda == "RX4 Wag") {
filter(mtcars2, brand=="Mazda RX4 Wag")}
else
if(input$other == "Toyota") {
filter(mtcars2, brand=="Toyota Corolla")}
else
if(input$other == "Other") {
filter(mtcars2, brand!="RX4")}
})
output$graph <- renderPlot({
datos <- plotdata()
ggplot(datos, aes(cyl, drat)) +
geom_col()
})}
shinyApp(ui = ui, server = server)
【问题讨论】: