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)