【发布时间】:2022-11-15 02:40:36
【问题描述】:
如果我有一个 data.frame/data.table 需要过滤多个列,然后传递给其他计算,我如何过滤数据而不使用if else 创建多个过滤条件组合。
例如,如果我有一个包含 Age、Gender、Ethnicity 的数据,并创建了三个 selectInput()。
我想要实现的是,
- 如果我从下拉列表中选择年龄:
10-19,那么这应该传递给数据并执行DT[Age %in% "10-19"] - 类似,如果我选择年龄:
10-19和性别:Female,那么这些应该作为DT[Age %in% "10-19" & Gender %in% "Female"]传递给数据 - 如果我取消选择
Age,那么数据会返回Gender:Female,比如DT[Gender %in% "Female"]如何捕获这些条件,并自动传递给数据过滤器,而无需明确通过这些组合?
这是一个非工作测试示例
df <- data.table(AgeGroup = sample(c("0-9", "10-19", "20-29"), 20, replace = TRUE), Sex = sample(c("Male", "Female"), 20, replace = TRUE)) ui <- fluidPage( sidebarLayout( sidebarPanel( selectInput("AgeGroup", "Age Group", choices = c("", unique(df$AgeGroup))), selectInput("Sex", "Sex", choices = c("", unique(df$Sex))) ), mainPanel( tableOutput("table") ) ) ) server <- function(input, output, session) { # How to modify here so that we don't need to do # `if (input$AgeGroup) df[AgeGroup == input$AgeGroup]` # consider multiple filters, some filters are selected and some are not. # For example, if there are 5 filters, there would be 2^5 combinations df_out <- reactive(df) output$table <- renderTable(df_out()) } shinyApp(ui, server)
【问题讨论】:
-
我真的认为一个最小的可重现示例在这里会有所帮助。预选了您输入的哪一类?首先?一个名为
"all"的类别?您的问题的解决方案部分取决于这些问题。 -
我通常将
choices = c("", Age)用于NULL 选择作为首选。我不知道如何使它在server函数中工作,但描述应该清楚我的意图。否则,我已经修改了一个非工作示例的问题。
标签: r shiny data.table