我有一个如下所示的 data.table:
萼片长度 | 萼片宽度 | 花瓣长度 | 花瓣宽度 | 物种 | A | B | C | D | E |
---|---|---|---|---|---|---|---|---|---|
5.1 | 3.5 | 1.4 | 0.2 | 山楂 | 0 | 1 | 0 | 1 | 1 |
4.9 | 3.0 | 1.4 | 0.2 | 山楂 | 1 | 0 | 0 | 0 | 0 |
4.7 | 3.2 | 1.3 | 0.2 | 山楂 | 1 | 0 | 0 | 1 | 0 |
4.6 | 3.1 | 1.5 | 0.2 | 山楂 | 0 | 0 | 1 | 0 | 0 |
set.seed(14)
n = 15
dt[, A := rbinom(n, 1, 0.4)]
dt[, B := rbinom(n, 1, 0.14)]
dt[, C := rbinom(n, 1, 0.57)]
dt[, D := rbinom(n, 1, 0.70)]
dt[, E := rbinom(n, 1, 0.11)]
A 至 E 列代表类别。
我想在一个闪亮的应用程序中创建一个过滤器,包含以下 5 个类别:
library(shiny)
library(data.table)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput(
"category",
"Choose a category",
choices = c("A", "B", "C", "D", "E"),
selected = c("A", "B", "C", "D", "E"),
multiple = T
)
),
mainPanel(
tableOutput("table")
)
)
)
server <- function(input, output) {
filter_data <- reactive({
# filters
dt
})
output$table <- renderTable({
filter_data()
})
}
shinyApp(ui = ui, server = server)
一种选择是使用例如基
Reduce
循环选定的列并过滤数据:
library(shiny)
library(data.table)
set.seed(14)
n <- 15
dt <- as.data.table(iris[seq(n), ])
dt[, A := rbinom(n, 1, 0.4)]
dt[, B := rbinom(n, 1, 0.14)]
dt[, C := rbinom(n, 1, 0.57)]
dt[, D := rbinom(n, 1, 0.70)]
dt[, E := rbinom(n, 1, 0.11)]
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput(
"category",
"Choose a category",
choices = c("A", "B", "C", "D", "E"),
selected = c("A", "D"),
multiple = TRUE
)
),
mainPanel(
tableOutput("table")
)
)
)
server <- function(input, output) {
filter_data <- reactive({
Reduce(
\(x, y) {
x[x[[y]] == 1, ]
},
input$category, init = dt
)
})
output$table <- renderTable({
filter_data()
})
}
shinyApp(ui = ui, server = server)
#>
#> Listening on http://127.0.0.1:4947