我试图在一个简单的闪亮应用程序中使用 group_by 和 checkboxGroupInput 的输入,如下所示。
我期待如果我选中 2 个框(气缸和齿轮),我将获得与运行时相同的输出:
mtcars%>%
group_by(cyl, gear) %>%
count()
# A tibble: 8 x 3
# Groups: cyl, gear [8]
cyl gear n
<dbl> <dbl> <int>
1 4 3 1
2 4 4 8
3 4 5 2
4 6 3 2
5 6 4 4
6 6 5 1
7 8 3 12
8 8 5 2
这是简单的闪亮应用程序。当我选中从下面的代码创建的框时,我将如何模仿上面的输出?
# UI
ui <- fluidPage(
checkboxGroupInput("variable", "Variables to show:",
c("Cylinders" = "cyl",
"Transmission" = "am",
"Gears" = "gear"
)
),
tableOutput("data")
)
# Server
server <- function(input, output) {
output$data <- renderTable({
mtcars %>%
group_by(!!as.name(input$variable)) %>%
count()
},
rownames = TRUE)
} # Server function close
# Run the app
shinyApp(ui, server)
谢谢!
在 中server
,我们可以将其更改为group_by_at
需要字符串输入的,并且它可以通过包装来容纳多个组变量输入vars
server <- function(input, output) {
output$data <- renderTable({
mtcars %>%
group_by_at(vars(input$variable)) %>%
count()
},
rownames = TRUE)
}
此外,在 OP 的代码中,group_by
可能需要多个组,因此我们可以转换为具有syms
(更多多个元素)的符号,然后评估 ( !!!
)。如果我们使用sym
and !!
,它一次只能对一个变量起作用
server <- function(input, output) {
output$data <- renderTable({
mtcars %>%
group_by(!!! rlang::syms(input$variable)) %>%
count()
},
rownames = TRUE)
}
-输出
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句