【问题标题】:Trouble using inputted variable with dplyr in Shiny with a reactive dataset在带有反应性数据集的 Shiny 中使用带有 dplyr 的输入变量时遇到问题
【发布时间】:2018-06-17 06:19:48
【问题描述】:

我浏览了有关 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_ 也不好。

它给了我想要的东西,但这不是我实际代码中的选项。任何帮助将不胜感激。

谢谢

【问题讨论】:

    标签: r shiny dplyr reactive


    【解决方案1】:

    主要问题是我们如何评估input$xcolinput$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)
    

    -输出

    【讨论】:

    • 感谢您的回答。您提到的其他选项是什么?
    猜你喜欢
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    相关资源
    最近更新 更多