R:如何(不)在 shinydashboard 中过滤
R: how (not to) filter in shinydashboard
这是一个非常简单的闪亮仪表板:
# Load libraries
library(shiny)
library(shinydashboard)
library(tidyverse)
data <- data.frame(sex = sample(c("Male", "Female"), size=100, replace=TRUE),
smoker = sample(c("yes", "no"), size=100, replace=TRUE))
## UI ##
ui <- dashboardPage(
dashboardHeader(
title = "My Dashboard"
),
dashboardSidebar(
sidebarMenu(
)
),
dashboardBody(
box(
title="Barplot", status='primary', solidHeader = T,
plotOutput("myBarplot")
),
box(
title="Filter", status='warning', solidHeader = T,
selectInput("findSex", "Choose sex:", c("All", "Male", "Female"))
)
)
)
## Server ##
server <- function(input, output){
set.seed(122)
filtered_df <- reactive({
data <- data %>% filter(sex == input$findSex)
data})
output$myBarplot <- renderPlot({
filtered_df() %>% ggplot(aes(x = smoker)) + geom_bar() + ylab("Prozente")
})
}
shinyApp(ui, server)
仪表板显示 smokers/non-smokers 的数量,您可以按性别筛选。实现方式如下:
data <- data %>% filter(sex == input$findSex)
现在我有两个问题:
- 如何默认显示所有案例(男性和女性)?
- 如何在选择男性或女性后再次显示所有案例? (R 中有类似
filter(sex == '*')
的东西吗?在使用 selectInput()
时有没有办法区分标签和值?(例如,在 HTML 中,您可以使用 <select><option value='1'>Male</option> <option value='2'>Female</option></select>
)
您可以在 c('Male','Female')
中转换 'All'
并使用 %in%
:
filtered_df <- reactive({
if (input$findSex == "All") {
sexSelect <- c('Male','Female')
}
else {
sexSelect <- input$findSex
}
data %>% filter(sex %in% sexSelect)
})
这是一个非常简单的闪亮仪表板:
# Load libraries
library(shiny)
library(shinydashboard)
library(tidyverse)
data <- data.frame(sex = sample(c("Male", "Female"), size=100, replace=TRUE),
smoker = sample(c("yes", "no"), size=100, replace=TRUE))
## UI ##
ui <- dashboardPage(
dashboardHeader(
title = "My Dashboard"
),
dashboardSidebar(
sidebarMenu(
)
),
dashboardBody(
box(
title="Barplot", status='primary', solidHeader = T,
plotOutput("myBarplot")
),
box(
title="Filter", status='warning', solidHeader = T,
selectInput("findSex", "Choose sex:", c("All", "Male", "Female"))
)
)
)
## Server ##
server <- function(input, output){
set.seed(122)
filtered_df <- reactive({
data <- data %>% filter(sex == input$findSex)
data})
output$myBarplot <- renderPlot({
filtered_df() %>% ggplot(aes(x = smoker)) + geom_bar() + ylab("Prozente")
})
}
shinyApp(ui, server)
仪表板显示 smokers/non-smokers 的数量,您可以按性别筛选。实现方式如下:
data <- data %>% filter(sex == input$findSex)
现在我有两个问题:
- 如何默认显示所有案例(男性和女性)?
- 如何在选择男性或女性后再次显示所有案例? (R 中有类似
filter(sex == '*')
的东西吗?在使用selectInput()
时有没有办法区分标签和值?(例如,在 HTML 中,您可以使用<select><option value='1'>Male</option> <option value='2'>Female</option></select>
)
您可以在 c('Male','Female')
中转换 'All'
并使用 %in%
:
filtered_df <- reactive({
if (input$findSex == "All") {
sexSelect <- c('Male','Female')
}
else {
sexSelect <- input$findSex
}
data %>% filter(sex %in% sexSelect)
})