首页 > 解决方案 > dplyr 链中函数内的闪亮输入反应性

问题描述

我写了一个自定义函数,我想用它mutate来向我的数据框添加一列并找到每个组中的最大值。最终我会用数据框做一个图。我的函数的参数之一将是用户提供的值。

我包括一个不会产生有趣数字的代表,但展示了我正在尝试做的事情。使用我的原始数据,我得到一个不同的错误:

UseMethod(“group_by_”)中的错误:没有适用于“group_by_”的适用方法应用于类“c('reactiveExpr','reactive')”的对象

有了这个代表,我得到

警告:错误:数据必须是数据框,或其他可被 fortify() 强制转换的对象,而不是具有 reactiveExpr/reactive 类的 S3 对象

无论哪种方式,我只是不太了解如何做到这一点。我哪里错了?

ui <- fluidPage(
titlePanel("Max Dollar per Mile"),
sidebarLayout(
position = "right",
mainPanel(plotOutput("plot2")),

sidebarPanel(
  sliderInput(
    inputId = "gasprice",
    label = "Select a dollar/gallon",
    min = 1,
    max = 4,
    step = .25, 
    value = 1
     )
   )
 )
)

server <- function(input,output){

    cost <-function(dpg, mpg) {
      ans = dpg/mpg

      ans
    }


  cars <- reactive({

  gas<-input$gasprice  

  mtcars %>%
    mutate(costpermile = cost(gas, mpg)) %>%
    group_by(cyl)%>%
    filter(costpermile == max(costpermile))
  })

  output$plot2<-renderPlot({
     ggplot(cars, aes(x=cyl, y=costpermile))+
     geom_bar(stat="identity")
   })
}


shinyApp(ui, server)

标签: rshiny

解决方案


推荐阅读