cjerzak's picture
Update app.R
2acecda verified
raw
history blame
3.35 kB
# app.R
# Load necessary libraries
library(shiny)
library(readr) # for reading CSVs
library(dplyr) # for data manipulation
library(ggplot2) # for plotting
library(DT) # for rendering data tables interactively
# Define UI
ui <- fluidPage(
# Title of the application
titlePanel("Country Representation Explorer"),
# Sidebar layout
sidebarLayout(
sidebarPanel(
# Input: Select which representation metric to visualize
selectInput(
inputId = "metric",
label = "Choose representation metric:",
choices = c("Overall", "Representation Gap", "Ethnicity",
"Gender", "Religion", "Language"),
selected = "Overall"
),
# Input: Numeric slider to filter based on the chosen metric
sliderInput(
inputId = "metricRange",
label = "Filter countries by metric range:",
min = -10, # set a plausible minimum range
max = 10, # set a plausible maximum range
value = c(-10, 10),
step = 0.1
),
# Checkbox to toggle data table
checkboxInput(
inputId = "showDataTable",
label = "Show data table of filtered results",
value = TRUE
)
),
# Main panel to display outputs
mainPanel(
# Output: Bar plot
plotOutput("repPlot", height = "600px"),
# Output: Data table (shown only when checkbox is TRUE)
conditionalPanel(
condition = "input.showDataTable == true",
DTOutput("tableOut")
)
)
)
)
# Define server logic
server <- function(input, output, session) {
# Read in the CSV
# Make sure your 'CountryRepresentationRankings.csv' file is in the same folder as this script
full_data <- reactive({
read_csv("CountryRepresentationRankings.csv", show_col_types = FALSE)
})
# Reactive subset of the data based on the metric range selected
filtered_data <- reactive({
req(input$metricRange)
req(input$metric)
# Ensure data is loaded
data <- full_data()
# Filter based on user-selected metric range
data %>%
filter(
# get() dynamically selects the column name based on input$metric
get(input$metric) >= input$metricRange[1] &
get(input$metric) <= input$metricRange[2]
)
})
# Render the bar plot
output$repPlot <- renderPlot({
data_for_plot <- filtered_data()
# Proceed only if there's data to plot
validate(
need(nrow(data_for_plot) > 0, "No data available within this range.")
)
# Order countries by the chosen metric
ggplot(data_for_plot, aes(
x = reorder(Country, get(input$metric)),
y = get(input$metric)
)) +
geom_col(fill = "steelblue") +
coord_flip() + # Flip coordinates for easier reading of country names
labs(
x = "Country",
y = paste(input$metric, "Index"),
title = paste("Countries by", input$metric, "Representation")
) +
theme_minimal(base_size = 14)
})
# Render the data table (only if checkbox is selected)
output$tableOut <- renderDT({
data_for_table <- filtered_data()
datatable(
data_for_table,
options = list(pageLength = 10, autoWidth = TRUE),
rownames = FALSE
)
})
}
# Create Shiny app
shinyApp(ui, server)