我浏览了有关 plyr 和 dplyr 问题的其他答案,但没有成功。
我想在 dplyr“group_by_”和“summarise”命令中使用两个输入变量。我似乎找不到正确的语法将我的变量输入汇总以获得分组的平均值。将其转回数据框是行不通的。
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_ 也不好。
它给了我我想要的东西,但这在我的实际代码中不是一个选项。任何帮助将不胜感激。
谢谢
最佳答案
主要问题是我们如何评估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)
-输出
关于r - 在 Shiny 中使用带有反应式数据集的 dplyr 输入变量时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48147447/