问题
I am trying to figure out as I select input in UI to immediately reflect the results on page. My search results led me to look into reactive expression and reactive values. But as I am trying to filter the value on data, I think it is causing some complication yet I have no clue what I am supposed to do with this.
It seems like the filter function doesn't seem to work though.
This is the error message:
Warning: Error in UseMethod: no applicable method for 'filter_' applied to an object of class "c('reactiveExpr', 'reactive')"
Stack trace (innermost first):
51: filter_
50: filter.default
49: filter
48: function_list[[i]]
47: freduce
46: _fseq
45: eval
44: eval
43: withVisible
42: %>%
41: eval
40: makeFunction
39: exprToFunction
38: observe
37: server
1: runApp
Error in UseMethod("filter_") :
no applicable method for 'filter_' applied to an object of class "c('reactiveExpr', 'reactive')"
回答1:
I found two problems,
first reactive statements are functions - you need to add brackets ()
after them.
second, you need to work on the naming of your variables, especially naming an variable data
is never a good thing in R and you are naming two objects the same first the data set itself and second the reactive statement returning the dataset - it seemed like this confused shiny quite a lot. I renamed the reactive statement to dta
and that solved it for me. Here is the complete server code
server <- function(input, output, session) {
dta <- reactive({
data
})
output$p1 <- renderText({
paste0("You currently live in ", input$Location, " and are contemplating a job offer in ", input$reLocation, ".")
})
values <- reactiveValues()
observe({
# req(input$Location,input$reLocation)
# browser()
values$LocationCost <- dta() %>% filter(UrbanArea == input$Location) %>% select(CostOfLivingIndex)
values$reLocationCost <- dta() %>% filter(UrbanArea == input$reLocation) %>% select(CostOfLivingIndex)
})
# observeEvent(input$Location, {
# values$LocationCost <- data %>%
# filter(UrbanArea == input$Location) %>%
# select(CostOfLivingIndex)
# })
#
# observeEvent(input$reLocation, {
# values$reLocationCost <- data %>%
# filter(UrbanArea == input$reLocation) %>%
# select(CostOfLivingIndex)
# })
output$p2 <- renderText({
if (values$LocationCost < values$reLocationCost) {
calc <- round(100* ((values$reLocationCost-values$LocationCost)/values$LocationCost), 2)
print(paste0("You need ", calc, "% increase in your after-taxes income in order to maintain your present lifestyle."))
} else {
calc <- round(100 * ((values$LocationCost-values$reLocationCost)/values$reLocationCost), 2)
print(paste0("You can sustain upto ", calc, "% reduction in after taxes income without reducing your present lifestyle."))
}
})
}
Hope this helps!!
来源:https://stackoverflow.com/questions/53588091/r-shiny-reactive-values-dplyr-filter-error