Display multiple summary statistics depending on user selection - r

I'm creating a shiny app where a user can select a state parent_location and a county name from two drop downs. They can also select a variable of interest layer which will then produce a summary statistics table. I've got my code working up to this point.
What I need to do is select other similar counties (contained in the cluster column) and then display summary statistics for this county as well. I can't seem to figure out how to A) display multiple summary statistics tables and B) dynamically create a list of similar counties.
Code that works
library(shiny)
library(tidyverse)
library(lubridate)
eviction_county_2010 <- read.csv("./eviction_county_2010.csv")
ui <- fluidPage(
sliderInput(inputId = "year",
label = "Select a Year:",
min = 2010,
max = 2016,
value = 2010,
step = 1),
radioButtons(inputId = "layer",
label = "Select a Dataset to View:",
choices = c("Eviction Filing Rate"="eviction_filing_rate", "Percent Rent Burden"="rent_burden",
"Percent Renter Occupied"="pct_renter_occupied", "Poverty Rate"="poverty_rate")),
selectInput(inputId = "state",
label = "Select a State:",
eviction_county_2010$parent_location),
selectInput(inputId = "county",
label = "Select a County:",
choices = NULL),
mainPanel(
h2("Summary of the variable"),
verbatimTextOutput("sum")
)
)
server <- function(input, output, session) {
observe({
x <- filter(eviction_county_2010,parent_location == input$state) %>%
select(name)
updateSelectInput(session,"county","Select a County:",choices = unique(x))}
)
output$sum <- renderPrint({
ec <- eviction_county_2010 %>%
filter(parent_location == input$state) %>%
filter(name == input$county)
summary(ec[,input$layer])
})
}
# Run the application
shinyApp(ui = ui, server = server)
Code I've attempted for displaying for similar counties. It returns 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.) I'm not sure which part needs to be placed inside a reactive expression.
ui <- fluidPage(
sliderInput(inputId = "year",
label = "Select a Year:",
min = 2010,
max = 2016,
value = 2010,
step = 1),
radioButtons(inputId = "layer",
label = "Select a Dataset to View:",
choices = c("Eviction Filing Rate"="eviction_filing_rate", "Percent Rent Burden"="rent_burden",
"Percent Renter Occupied"="pct_renter_occupied", "Poverty Rate"="poverty_rate")),
selectInput(inputId = "state",
label = "Select a State:",
eviction_county_2010$parent_location),
selectInput(inputId = "county",
label = "Select a County:",
choices = NULL),
mainPanel(
h2("Summary of the variable"),
verbatimTextOutput("sum")
)
)
server <- function(input, output, session) {
ec <- eviction_county_2010 %>%
filter(parent_location == input$state) %>%
filter(name == input$county)
sel_clust <- unique(ec$cluster)
sim_cty <- eviction_county_2010[ sample(which(eviction_county_2010$cluster == sel_clust), 4),]
sim_cty <- unique(sim_cty$GEOID)
sim_cty <- append(sim_cty, unique(ec$GEOID))
observe({
x <- filter(eviction_county_2010,parent_location == input$state) %>%
select(name)
updateSelectInput(session,"county","Select a County:",choices = unique(x))}
)
output$sum <- renderPrint({
df1 <- eviction_county_2010 %>%
filter(GEOID == sim_cty[1])
df2 <- eviction_county_2010 %>%
filter(GEOID == sim_cty[2])
df3 <- eviction_county_2010 %>%
filter(GEOID == sim_cty[3])
df4 <- eviction_county_2010 %>%
filter(GEOID == sim_cty[4])
df5 <- eviction_county_2010 %>%
filter(GEOID == sim_cty[5])
summary(df1[,input$layer])
summary(df2[,input$layer])
summary(df3[,input$layer])
summary(df4[,input$layer])
summary(df5[,input$layer])
})
}
# Run the application
shinyApp(ui = ui, server = server)
Is this even possible? What am I doing wrong here?

Move this section:
ec <- eviction_county_2010 %>%
filter(parent_location == input$state) %>%
filter(name == input$county)
sel_clust <- unique(ec$cluster)
sim_cty <- eviction_county_2010[ sample(which(eviction_county_2010$cluster == sel_clust), 4),]
sim_cty <- unique(sim_cty$GEOID)
sim_cty <- append(sim_cty, unique(ec$GEOID))
To a reactive({}) statement. I think that's where your error is.
For example:
ec <- reactive({
eviction_county_2010 %>%
filter(parent_location == input$state) %>%
filter(name == input$county)
sel_clust <- unique(ec$cluster)
sim_cty <- eviction_county_2010[ sample(which(eviction_county_2010$cluster == sel_clust), 4),]
sim_cty <- unique(sim_cty$GEOID)
sim_cty <- append(sim_cty, unique(ec$GEOID))
})
Then later in your sever code use:
ec() %>%
...stuff...

Related

Trying to get a checkboxGroupInput derived from column values to filter a bar graph, but keep getting various errors?

I keep getting errors like Error in : object of type 'closure' is not subsettable or
'..1'. x Input '..1' must be of size 28 or 1, not size 0. I am trying to change the bar graph based on what options are selected or not in the checkbox.
I changed the column names for ease of use from where I got the data.
library(shiny)
library(dplyr)
library(plotly)
#dataset link: https://www.kaggle.com/mahirahmzh/starbucks-customer-retention-malaysia-survey?select=Starbucks+satisfactory+survey.csv
#c("Timestamp","Gender","age","currently","income","visit_freq","Enjoy","Time","Nearby","membership","freq_purchase","avg_spend","Ratevsother","rateprice","salesandpromotion","ambiance","wifi","service","meetup","heardaboutpromotions","continuepatronage")
data <-read.csv("Starbucks satisfactory survey.csv", header=TRUE)
Categorical.Variables <- c("visit_freq", "age", "income")
ui <- fluidPage(
sidebarPanel(
selectInput('category', choices = Categorical.Variables, label = 'Select filter options:'),
conditionalPanel(condition = "input.category != '-'",
uiOutput("select_category"))
)
)
server <- function(input, output) {
output$select_category <- renderUI({
choices <- as.list(unique(data[[input$category]]))
checkboxGroupInput('categorycheck', label = 'Select filter:',
choices = choices,selected = choices)
data2 <- reactive({
data %>%
group_by(gender,data[[input$category]], currently,membership) %>%
summarize(n = n(), .groups="drop") %>%
filter(data[[input$category]] %in% input$categorycheck) %>%
filter(membership == "Yes")})
renderPlotly({
data2 <- data2()
colnames(data2) <- c("gender","filtercategory","currently","membership","n")
plot_ly(data2, x = ~currently, y = ~n, type = "bar", color=~gender, colors="Dark2") %>%
layout(barmode = 'group')
})
})
}
shinyApp(ui, server)
You have several issues. You should close your renderUI prior to using input$categorycheck in the reactive object data2. In addition, columns names in the csv file are long. Once you define the column names of data the way you are analyzing, it will work. Try this
mydata <-read.csv("Starbucks satisfactory survey.csv", header=TRUE)
names(mydata)[1:10] <- c("Timestamp", "gender", "Age", "currently", "Income", "visit_freq","drink_freq","time_spent", "nearby","membership")
Categorical.Variables <- c("Age", "Income", "visit_freq")
ui <- fluidPage(
sidebarPanel(
selectInput('category', choices = Categorical.Variables, label = 'Select filter options:'),
#conditionalPanel(condition = "input.category != '-'",
uiOutput("select_category")
# )
),
mainPanel(plotlyOutput("myplot"),
DTOutput("t1")
)
)
server <- function(input, output) {
output$select_category <- renderUI({
req(input$category)
choices <- as.list(unique(mydata[[input$category]]))
checkboxGroupInput('categorycheck', label = 'Select filter:',
choices = choices,selected = choices)
})
data2 <- reactive({
req(input$category,input$categorycheck)
mydata %>%
group_by(gender,.data[[input$category]], currently,membership) %>%
dplyr::summarize(n = n(), .groups="drop") %>%
filter(.data[[input$category]] %in% input$categorycheck) %>%
filter(membership == "Yes")})
output$t1 <- renderDT(data2())
output$myplot <- renderPlotly({
req(data2())
data2 <- data2()
colnames(data2) <- c("gender","filtercategory","currently","membership","n")
plot_ly(data2, x = ~currently, y = ~n, type = "bar", color=~gender, colors="Dark2") %>%
layout(barmode = 'group')
})
}
shinyApp(ui, server)

Get "ALL" value in selectinput to plot with multi-filters (shiny)

I would like to get a reactive plot with multiple filters and an initial minimal plot with the number of ALL diagnostics by month.
The aim requires 4 filters AND a scale of period (display data by week,month ..).
I tried but not it's not working on the step to sum data (ALL).
If you have a suggestion I am open .
Thank you :)
library(shiny)
library(ggplot2)
library(dplyr)
#data
data.hosp <- data.frame(stringsAsFactors=FALSE,
id= c(1,2,3,4,5),
Annee = c(2018, 2018, 2018, 2018, 2018),
Mois = c("2018-01","2018-01","2018-02","2018-03","2018-03"),
Semaine = c("2018-001","2018-003","2018-008","2018-011","2018-013"),
uf= c("A3352","Z6687", "A3352", "A3352", "Z6687"),
um= c(3350,6687, 3352, 3350, 6687),
ghm= c("AAAAA","DFFDF","DDFDA","AZEEA","DDFDA"),
diag= c("A","A","C","Z","R"),
nb=c(1,3,1,1,10))
ui <- fluidPage(
titlePanel("Plot with filters"),
fluidRow(
column(2,
selectInput(inputId = "sel_uf",
label = "UF",
choices = as.character(unique(data.hosp$uf)),
multiple=TRUE,
width = validateCssUnit(200))),
column(2,
selectInput(inputId = "sel_um",
label = "UM",
choices = as.character(unique(data.hosp$um)),
multiple=TRUE,
width = validateCssUnit(200))),
column(3,
selectInput(inputId = "sel_ghm",
label = "GHM",
choices =as.character(unique(data.hosp$ghm)),
multiple=TRUE,
width = validateCssUnit(200))),
column(3,
selectInput(inputId = "sel_diag",
label = "Diagnostic",
choices =c('Tous', as.character(unique(data.hosp$diag))),
multiple=TRUE,
width = validateCssUnit(250))),
column(4, selectInput("periodec",
label="Affichage par :",
choices = c("Semaine"= "Semaine",
"Mois" = "Mois",
"Année" = "Annee"),
selected = "Mois" ) ),
plotOutput("graph1", height=300 )
))
server <- function(input, output) {
#Period filter (display by :)
periode <- reactive({
ifelse(input$periodec=="Semaine", "Semaine",
ifelse(input$periodec=="Mois", "Mois",
ifelse(input$periodec=="Année", "Annee"))) })
# Data filters
df_dat <- reactive({
df_dat <- data.hosp
#code to get "ALL" in selectsizeInput
if ('Tous' %in% input$sel_diag) { sel_diag <- unique(data.hosp$diag)
} else {
data.hosp <- data.hosp %>% filter(nb == input$sel_diag)
nb <- unique(data.hosp$nb) }
if (!is.null(input$sel_um)) {
df_dat <- df_dat %>% filter(um == input$sel_um) %>% group_by_(periode()) %>% summarise(sum_active = sum(nb))}
if (!is.null(input$sel_uf)) {
df_dat <- df_dat %>% filter(uf == input$sel_uf) %>% group_by_(periode()) %>% summarise(sum_active = sum(nb))}
if (!is.null(input$sel_ghm)) {
df_dat <- df_dat %>% filter(ghm == input$sel_ghm) %>% group_by_(periode()) %>% summarise(sum_active = sum(nb)) }
if (!is.null(input$sel_diag)) {
df_dat <- df_dat %>% filter(diag == input$sel_diag) %>% group_by_(periode()) %>% summarise(sum_active = sum(nb)) }
return(df_dat)
})
# Ensures that our filter works properly
observe(print(str(df_dat())))
# graph
output$graph1 <- renderPlot({
req(df_dat())
ggplot(df_dat(), aes_string(x =periode(), y = "sum_active", group = factor(periode() ))) +
geom_bar(aes_string(periode(), "sum_active"), stat = "identity", fill="steelblue")
})
}
shinyApp(ui,server)
Maybe this is what you are looking for. In my opinion the main issue is that your approach was overly complicated. (;
My approach sets all filters first. If NULL (and/or 'Tous') the "selection" is set to all categories of a variable, otherwise only the chosen ones are included.
Doing so you only need one pipe to filter and summarise the data
There is no need for the observe statement which I dropped
I fixed the req in the renderPlot to check wether the filtered data contains any rows. Otherwise ggplot will raise an error.
server <- function(input, output) {
#Period filter (display by :)
# While a nested ifelse works in the present case a better choice is using `if
periode <- reactive({
if (input$periodec == "Semaine") {
"Semaine"
} else if (input$periodec == "Mois") {
"Mois"
} else {
"Annee"
}
})
df_dat <- reactive({
# First: Setup the filters. If NULL: all categories else: chosen ctaegories
# In case of diag additionally check for "Tous"
sel_diag <- if (is.null(input$sel_diag) | 'Tous' %in% input$sel_diag) unique(data.hosp$diag) else input$sel_diag
sel_um <- if (is.null(input$sel_um)) unique(data.hosp$um) else input$sel_um
sel_uf <- if (is.null(input$sel_uf)) unique(data.hosp$uf) else input$sel_uf
sel_ghm <- if (is.null(input$sel_ghm)) unique(data.hosp$ghm) else input$sel_ghm
# Filter the data and summarise
data.hosp %>%
filter(diag %in% sel_diag, um %in% sel_um, uf %in% sel_uf, ghm %in% sel_ghm) %>%
group_by_(periode()) %>%
summarise(sum_active = sum(nb), .groups = "drop")
})
# graph
output$graph1 <- renderPlot({
# Plot only if any data
req(nrow(df_dat()) > 0)
ggplot(df_dat(), aes_string(x = periode(), y = "sum_active", group = factor(periode() ))) +
geom_bar(aes_string(periode(), "sum_active"), stat = "identity", fill="steelblue")
})
}

Filter values in pipe based on condition of separate filter

I have a shiny app and within that app, I have a table that I render based on input from the user. Within that pipe on eviction_county_2010 I am attempting to return the table with only a sample of counties in the same cluster as input$county. I figured out how to do this with multiple lines of code and reassignments, but shiny throws an error whenever I do this as it clearly isn't allowed. How can I tweak my code to return this within one pipe?
Code with multiple assignments. When I attempted this, 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.)
server <- function(input, output, session) {
ec <- eviction_county_2010 %>%
filter(parent_location == input$state) %>%
filter(name == input$county)
sel_clust <- c(unique(ec$cluster))
sel_geoid <- c(unique(ec$GEOID))
sim_cty <- eviction_county_2010 %>% filter(cluster == sel_clust | GEOID != sel_geoid)
sim_cty <- unique(sim_cty$GEOID)
sim_cty <- sample(sim_cty, 5)
sim_cty <- append(sel_geoid, sim_cty)
...
output$table <- renderTable({eviction_county_2010 %>% filter(GEOID %in% sim_cty)})
I attempted the above code in a reactive, and got Error: 'match' requires vector arguments.
sim_cty <- reactive({ec <- eviction_county_2010 %>%
filter(parent_location == input$state) %>%
filter(name == input$county)
sel_clust <- c(unique(ec$cluster))
sel_geoid <- c(unique(ec$GEOID))
sim_cty <- eviction_county_2010 %>% filter(cluster == sel_clust | GEOID != sel_geoid)
sim_cty <- unique(sim_cty$GEOID)
sim_cty <- sample(sim_cty, 5)
sim_cty <- append(sel_geoid, sim_cty)})
output$table <- renderTable(
eviction_county_2010 %>%
filter(GEOID %in% sim_cty)
Current code
library(shiny)
library(tidyverse)
library(datasets)
library(lubridate)
library(stringr)
eviction_county_2010 <- read.csv("./eviction_county_2010.csv")
ui <- fluidPage(
sliderInput(inputId = "year",
label = "Select a Year:",
min = 2010,
max = 2016,
value = 2010,
step = 1),
radioButtons(inputId = "layer",
label = "Select a Dataset to View:",
choices = c("Eviction Filing Rate"="eviction_filing_rate", "Percent Rent Burden"="rent_burden",
"Percent Renter Occupied"="pct_renter_occupied", "Poverty Rate"="poverty_rate")),
selectInput(inputId = "state",
label = "Select a State:",
eviction_county_2010$parent_location),
selectInput(inputId = "county",
label = "Select a County:",
choices = NULL),
mainPanel(
h2("Comparisons Across Similar Counties"),
tableOutput('table')
)
)
server <- function(input, output, session) {
observe({
x <- filter(eviction_county_2010,parent_location == input$state) %>%
select(name)
updateSelectInput(session,"county","Select a County:",choices = unique(x))}
)
output$table <- renderTable(
eviction_county_2010 %>%
group_by(County) %>%
summarise_at(c("GEOID", "population", "cluster", "poverty_rate", "unemployment_rate", "pct_renter_occupied",
"Percent_Rural", "median_gross_rent", "median_household_income",
"median_property_value", "rent_burden", "pct_white", "pct_nonwhite",
"pct_af_am", "pct_hispanic", "pct_am_ind", "pct_asian",
"pct_nh_pi", "pct_multiple", "pct_other"), mean, na.rm = TRUE) %>%
rename(Population = population, `Poverty Rate` = poverty_rate,
`Unemployment Rate` = unemployment_rate, `% Renter Occupied` = pct_renter_occupied,
`% Rural` = Percent_Rural, `Median Gross Rent` = median_gross_rent, `Median Household Income` = median_household_income,
`Median Property Value` = median_property_value, `Rent Burden` = rent_burden,
`% White` = pct_white, `% Non White` = pct_nonwhite,
`% African American` = pct_af_am, `% Hispanic` = pct_hispanic, `% American Indian` = pct_am_ind,
`% Asian` = pct_asian,
`% Native Hawaiian/Pacific Islander` = pct_nh_pi, `% Multiple` = pct_multiple, `% Other` = pct_other) # %>%
# filter(County == str_c(input$county, input$state, sep = ", "))
)
}
# Run the application
shinyApp(ui = ui, server = server)
I can't test it without an example/toy data (see here to learn how to create one).
But, per your code, when you convert sim_cty to reactive, you need to call it as a function sim_cty():
output$table <- renderTable(
eviction_county_2010 %>%
filter(GEOID %in% sim_cty())
See here to learn more about reactives in shiny.

DT output takes me to 1st page when i edit a reactive DT

I have a toy version of my code below. I have one of the columns (column 7) in my shiny DT output as editable. When i edit the a cell of the column it takes me back to the first row of of the column. I checked the data table object in environment, the edited cell does get update. So, that is good. But i want to stay on the same page after editing the cell. This is because a user may have applied a few filters to reach a certain page and then when he edits a cell he would like to continue from there rather than going back to start.
I am new to R so any help would be greatly appreciated.
I am using DT 0.7
My data frame has 7 columns: Continent, State, Country, Date, Rate (Pollution), Vehicles, Remark (editable column)
A user can filter the table output by select input, range and slider input. I want to make that output editable.
Thanks in advance!
library(shiny)
library(DT)
ui <- navbarPage("Hello",
tabPanel("Tab1",
sidebarLayout(
sidebarPanel( width = 4,
selectInput("continent", "Select:",
choices = ""),
selectInput("country" , "Select:",
choices = ""),
selectInput("state" , "Select:",
choices = ""),
dateRangeInput("date", "Select:",
startview = "month",
minview = "months",
maxview = "decades",
start = as.Date('1999-01-01'),
end = as.Date(today()),
separator = "-"),
sliderInput("rate", "Select:",
min = 1, max = 5, value = c(1,5),
dragRange = TRUE)),
mainPanel(
tabsetPanel(
tabPanel("Analysis",
dataTableOutput("Table1")
)))))
#server
server <- function(input, output, session)
{
observe({
updateSelectInput(session, "continent",
choices = c("All", unique(Df$Continent)))
})
observe({
updateSelectInput(session, "country",
choices = c("All", Df %>%
filter(`Continent` == input$continent) %>%
select(Country)))
})
observe({
updateSelectInput(session, "state",
choices = c("All", Df %>%
filter(`Continent` == input$continent &
`Country` == input$country) %>%
select(State)))
})
#create reactive table
RecTable <- reactive({
Df
if(input$continent != "All") {
Df <- Df[Df$Continent == input$continent,]
}
if(input$country != "All") {
Df <- Df[Df$Country == input$country,]
}
if(input$state != "All") {
Df <- Df[Df$State == input$state,]
}
Df <- Df %>%
filter(Date >= input$date[1] & Date <= input$date[2]) %>%
filter(Rate >= input$rate[1] & Rate <= input$rate[2])
Df})
output$Table1 <- DT::renderDT({
DT::datatable(RecTable(),
rownames = FALSE ,
editable = list(target = 'cell', disable = list(columns = c(0:6))))
})
proxy1 <- dataTableProxy('Table1')
observeEvent(input$Table1_cell_edit, {
Df <<- editData(Df, input$Table1_cell_edit, 'Table1', rownames = FALSE, resetPaging = FALSE)
})}
#run
shinyApp(ui = ui, server = server)

Shiny with reactive inputs and "Go" button

I have a shiny App, I wanted to be reactive for the inputs choice and show the datatable when I press the "Go" button.
For inputs I want to have the choice between "All value" of my variable and each value.
I have some problem to fix my app.
First try
library(shiny)
library(dplyr)
library(DT)
# my data
bdd <- tibble(BA = rep(LETTERS, 2), MA = as.character(1:52),
YES = paste(BA, MA, sep = ""))
ui <- fluidPage(
titlePanel("BA"),
column(4,
uiOutput("filter1"),
uiOutput("filter2"),
uiOutput("filter3"),
actionButton("button", "GO")),
column(8,
DT::dataTableOutput("my_table"))
)
server <- function(input, output, session) {
All_BA <- reactive({
bdd %>% distinct(BA)
})
# my reactives inputs for filter 1
output$filter1 <- renderUI({
selectInput("filter1", "Filtre numéro 1",
choices = c("All_BA", bdd %>% select(BA)))
})
All_MA <- reactive({
bdd %>% filter(BA %in% input$filter1) %>%
distinct(MA)
})
# my reactives inputs for filter 2
output$filter2 <- renderUI({
selectInput("filter2", "Filtre numéro 2",
choices = c("All_MA", bdd %>% filter(BA %in% input$filter1) %>% select(MA)),
selected = "All_MA")
})
All_Y <- reactive({
bdd %>% filter(BA %in% input$filter1 |
MA %in% input$filter2) %>% distinct(YES)
})
# my reactives inputs for filter 3
output$filter3 <- renderUI({
selectInput("filter3", "Filtre numéro 3",
choices = c("All_Y", bdd %>% filter(BA %in% input$filter1,
MA %in% input$filter2) %>% select(YES)),
selected = "All_Y")
})
df <- eventReactive(input$button, {
bdd %>% filter(BA %in% input$filter1,
MA %in% input$filter2,
YES %in% input$filter3)
})
output$my_table <- DT::renderDataTable({
df()
})
}
# Run the application
shinyApp(ui = ui, server = server)
second try (didn't work cause of rectivity problem and the code doesnt seem to be optimized)
library(shiny)
library(dplyr)
library(DT)
# my data
bdd <- tibble(BA = rep(LETTERS, 2), MA = as.character(1:52),
YES = paste(BA, MA, sep = ""))
ui <- fluidPage(
titlePanel("BA"),
column(4,
uiOutput("filter1"),
uiOutput("filter2"),
uiOutput("filter3"),
actionButton("button", "GO")),
column(8,
DT::dataTableOutput("my_table"))
)
server <- function(input, output, session) {
All_BA <- reactive({
bdd %>% distinct(BA)
})
# my reactives inputs for filter 1
if(input$filter1 == "All_BA"){
bdd <- reactive({
bdd %>%
filter(BA %in% All_BA())
})
}else{
bdd <- reactive({
bdd %>%
filter(BA %in% input$filter1)
})
}
output$filter1 <- renderUI({
selectInput("filter1", "Filtre numéro 1",
choices = c("All_BA", bdd() %>% select(BA)))
})
All_MA <- reactive({
bdd() %>% filter(BA %in% input$filter1) %>%
distinct(MA)
})
# my reactives inputs for filter 2
if(input$filter2 == "All_MA"){
bdd2 <- reactive({
bdd() %>%
filter(MA %in% All_MA())
})
}else{
bdd2 <- reactive({
bdd() %>%
filter(MA %in% input$filter2)
})
}
output$filter2 <- renderUI({
selectInput("filter2", "Filtre numéro 2",
choices = c("All_MA", bdd2() %>% select(MA)),
selected = "All_MA")
})
All_Y <- reactive({
bdd2 %>% filter(BA %in% input$filter1 |
MA %in% input$filter2) %>% distinct(YES)
})
# my reactives inputs for filter 3
if(input$filter3 == "All_Y"){
bdd3 <- reactive({
bdd2() %>%
filter(YES %in% All_Y())
})
}else{
bdd3 <- reactive({
bdd2() %>%
filter(YES %in% input$filter3)
})
}
output$filter3 <- renderUI({
selectInput("filter3", "Filtre numéro 3",
choices = c("All_Y", bdd3() %>% select(YES)),
selected = "All_Y")
})
df <- eventReactive(input$button, {
bdd %>% filter(BA %in% input$filter1,
MA %in% input$filter2,
YES %in% input$filter3)
})
output$my_table <- DT::renderDataTable({
df()
})
}
# Run the application
shinyApp(ui = ui, server = server)
The problem lies in the filtering of the table.
If nothing is selected input$filter1 has value 'All_BA', and the filter return no value, and similarly for the other inputs.
In fact the filter works if all 3 input values are selected.
Change it to:
df <- eventReactive(input$button, {
res <- bdd
if(input$filter1 != "All_BA")
res <- res %>% filter(BA %in% input$filter1)
if(input$filter2 != "All_MA")
res <- res %>% filter(MA %in% input$filter2)
if(input$filter3 != "All_Y")
res <- res %>% filter(MA %in% input$filter3)
res
})
(I worked on the first example).
Hope this helps

Resources