0

I wrote a custom function and I want to use it with mutate to add a column to my dataframe and find the maximum value within each group. Ultimately I will make a figure with the dataframe. One of the arguments of my function will be a value provided by the user.

I'm including a reprex that does not result in a interesting figure, but demonstrates what I am trying to do. With my original data I get a different error:

Error in UseMethod("group_by_") : no applicable method for 'group_by_' applied to an object of class "c('reactiveExpr', 'reactive')"

With this reprex, I get

Warning: Error in : data must be a data frame, or other object coercible by fortify(), not an S3 object with class reactiveExpr/reactive

Either way, I am just not quite understanding how to do this. Where am I going wrong?

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)
Nazer
  • 3,654
  • 8
  • 33
  • 47
  • 1
    Since `cars` is reactive. you need to use `cars()` – MrFlick Jul 02 '20 at 21:21
  • Yeah! Well, the reprex works. Still have no idea what to do about my original error since it appears `group_by` gives me no troubles here. – Nazer Jul 02 '20 at 21:24
  • Well, the `group_by` error also sounds like you are trying to use a reactive value like a regular data.frame. Make sure you always use `()` when trying to get the value of a reactive object. – MrFlick Jul 02 '20 at 21:34

0 Answers0