我已经浏览了有关plyr和dplyr问题的其他答案但没有成功。
我想在dplyr中使用两个输入变量" group_by _"和"总结"命令。我似乎无法找到正确的语法来输入我的变量进行汇总以获得分组的平均值。将其转回数据框并不起作用。
new_frame <- frame()
new_frame[[input$ycol]]
sapply给出结果,但它忽略了分组级别并给出了整个列的平均值。
mean = sapply(frame()[input$ycol],mean)
我不确定还有其他选择。
MWE,错误如下。
library(shiny)
ui <- fluidPage(
titlePanel("MWE using faithful data"),
sidebarLayout(
sidebarPanel(
selectInput('xcol', 'X Variable', "",choices = "colour"),
selectInput('ycol', 'Y Variable', "",choices = c("waiting", "eruptions"))),
mainPanel(
tableOutput("distPlot"))))
server <- function(input, output) {
frame <- reactive({
faithful <- faithful %>% mutate(colour = rep(c("red","white"),136))
return(faithful)
})
output$distPlot <- renderTable({
frame() %>% group_by_(input$xcol) %>%
summarise(mean = mean(input$ycol))
})
}
shinyApp(ui = ui, server = server)
如果我对该行进行硬编码
summarise(mean = mean(input$ycol))
到
summarise(mean = mean(eruptions))
使用summarise_也不行。
它给了我想要的东西,但这不是我实际代码中的一个选项。任何帮助将不胜感激。
由于
答案 0 :(得分:2)
主要问题是我们如何评估input$xcol
和input$ycol
。这些是字符串元素。一种选择是将其转换为带有rlang::sym
的符号,并使用!!
library(shiny)
library(dplyr)
ui <- fluidPage(
titlePanel("MWE using faithful data"),
sidebarLayout(
sidebarPanel(
selectInput('xcol', 'X Variable', "",choices = "colour"),
selectInput('ycol', 'Y Variable', "",choices = c("waiting", "eruptions"))),
mainPanel(
tableOutput("distPlot"))))
server <- function(input, output) {
frame <- reactive({
faithful %>%
mutate(colour = rep(c("red","white"),136))
})
output$distPlot <- renderTable({
frame() %>%
group_by(!! rlang::sym(input$xcol)) %>%
summarise(mean = mean(!! rlang::sym(input$ycol)))
})
}
shinyApp(ui = ui, server = server)
-output