r - 在 Shiny 中使用带有反应式数据集的 dplyr 输入变量时出现问题

标签 r shiny dplyr reactive

我浏览了有关 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$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)

-输出

enter image description here

关于r - 在 Shiny 中使用带有反应式数据集的 dplyr 输入变量时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48147447/

相关文章:

r - 无法从 Dropbox 下载 .csv

R plotly : How to connect lines on polar/radar chart?

R Shiny 动态框高度

R:根据组和不同条件对数据框进行子集化

r - <U+00A0> 读取csv文件时的特殊字符

r - 如何删除plot.xts中的网格线

r - 如何更改/指定超出渐变条限制的填充颜色?

r - 在模块中使用 shiny.i18n 翻译 Shiny 的应用程序?

r - GoogleVis 和 Shiny

r - 使用 dplyr 计算 group_by 中的子组