gpt4 book ai didi

r - Shiny 的应用程序中的多个 group_by

转载 作者:行者123 更新时间:2023-12-04 01:56:35 25 4
gpt4 key购买 nike

我有一个 Shiny 的应用程序,它接受一个数据帧,并应用 group_by 中的 dplyr 。我可以让它接受单个组,但我希望 selectInput 接受多个分组变量。

我可以通过添加另一个 selectInput ,然后将其传递给 group_by 语句来解决这个问题,但我希望将其扩展到任意数量的变量。因此,我需要单个 selectInput 来接受多个参数。

仅添加 multiple = TRUE 不会以 group_by 理解的方式传递变量,并且 this answer 由于 group_by_ 已弃用,我无法适应

笔记,

此应用程序的完整版本使用 fileInput ,而不是硬编码数据集,因此调用 renderUIreactive

library(shiny)
library(DT)
library(dplyr)

ui <- fluidPage(

titlePanel("app"),

sidebarLayout(
sidebarPanel(

uiOutput("groups")

),


mainPanel(

DT::dataTableOutput("summary")
)
)
)


server <- function(input, output) {
mydata <- reactive({structure(list(School = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 1L, 1L, 2L, 2L), .Label = c("School1", "School2"), class = "factor"),
Town = structure(c(1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 1L,
2L, 1L), .Label = c("Levin", "Wellington"), class = "factor"),
Income = c(6314L, 3546L, 3541L, 846684L, 231123L, 564564L,
545L, 1325L, 484L, 51353L, 465546L, 564546L)), .Names = c("School",
"Town", "Income"), class = "data.frame", row.names = c(NA, -12L
))})



output$groups <- renderUI({
df <- mydata()
selectInput(inputId = "grouper", label = "Group variable", choices = names(df), multiple = TRUE)
})




summary_data <- reactive({
req(input$grouper)
mydata() %>%
dplyr::group_by(!!rlang::sym(input$grouper)) %>%
dplyr::summarise(mean_income = mean(Income), na.rm = TRUE)
})

output$summary <- DT::renderDataTable({
DT::datatable(summary_data())
})



}

shinyApp(ui, server)

最佳答案

正如 Renu 在评论中指出的,答案是用 !! 替换 !!! ,用 sym 替换 syms (这允许 group_by 接受变量列表,而不是单个变量。

library(shiny)
library(DT)
library(dplyr)

ui <- fluidPage(

titlePanel("app"),

sidebarLayout(
sidebarPanel(

uiOutput("groups")

),


mainPanel(

DT::dataTableOutput("summary")
)
)
)


server <- function(input, output) {
mydata <- reactive({structure(list(School = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 1L, 1L, 2L, 2L), .Label = c("School1", "School2"), class = "factor"),
Town = structure(c(1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 1L,
2L, 1L), .Label = c("Levin", "Wellington"), class = "factor"),
Income = c(6314L, 3546L, 3541L, 846684L, 231123L, 564564L,
545L, 1325L, 484L, 51353L, 465546L, 564546L)), .Names = c("School",
"Town", "Income"), class = "data.frame", row.names = c(NA, -12L
))})



output$groups <- renderUI({
df <- mydata()
selectInput(inputId = "grouper", label = "Group variable", choices = names(df), multiple = TRUE)
})




summary_data <- reactive({
req(input$grouper)
mydata() %>%
dplyr::group_by(!!!rlang::syms(input$grouper)) %>%
dplyr::summarise(mean_income = mean(Income), na.rm = TRUE)
})

output$summary <- DT::renderDataTable({
DT::datatable(summary_data())
})



}

shinyApp(ui, server)

关于r - Shiny 的应用程序中的多个 group_by,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50092344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com