I tried to add a filter to my data analysis. The filter (inputF2) is an item in a category (xInput) chosen by the user.
then I want filter out the data to do summarize analysis and plot out the mean. However, once I wrote the if statement, the program won't run.
library(datasets)
library(shiny)
library(dplyr)
library(ggplot2)
library(DT)
library(crosstalk)
data("iris")
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Analyze Iris table"),
# Sidebar with a dropdown menu selection input for key measurecomponent
sidebarLayout(
sidebarPanel(
selectInput("yInput", "Measuring element: ",
colnames(iris), selected = colnames(iris)[2]),
selectInput('xInput', 'Grouper: ',
colnames(iris), selected = colnames(iris)[5])
),
# Show a plot of the generated distribution
mainPanel(
uiOutput('filter'),
plotOutput("barPlot"),
DTOutput('table1')
)))
server <- function(input, output) {
output$filter = renderUI({
selectInput('inputF2', 'Filter Item: ',
c('Null', unique(iris %>% select(input$xInput))))
})
if(input$inputF2 != 'Null') {
iris_sub = reactive({
iris %>% filter_at(input$xInput == input$inputF2)
})
} else{ iris_sub = iris}
by_xInput <- reactive({
iris_sub %>%
group_by_at(input$xInput) %>%
summarize(n = n(), mean_y = mean(!! rlang::sym(input$yInput)))
})
output$barPlot <- renderPlot({
# as the input is a string, use `aes_string`
ggplot(data = by_xInput(), aes_string(x = input$xInput, y = "mean_y")) +
geom_bar(stat = 'identity')
})
output$table1 = renderDT(
datatable(by_xInput())
)
}
shinyApp(ui = ui, server = server)
This is the error message I got:
Error in .getReactiveEnvironment()$currentContext() : Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)