cjerzak commited on
Commit
2acecda
·
verified ·
1 Parent(s): e233d10

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +80 -103
app.R CHANGED
@@ -1,145 +1,122 @@
1
- # install.packages(c("shiny", "dplyr", "ggplot2", "DT"))
2
 
 
3
  library(shiny)
4
- library(dplyr)
5
- library(ggplot2)
6
- library(data.table)
 
7
 
 
8
  ui <- fluidPage(
9
- titlePanel("Country Representation Rankings Explorer"),
10
-
 
 
 
11
  sidebarLayout(
12
  sidebarPanel(
13
- h4("Controls"),
14
  selectInput(
15
  inputId = "metric",
16
- label = "Select a Representation Metric:",
17
- choices = c(
18
- "Overall",
19
- "Representation Gap",
20
- "Ethnicity",
21
- "Gender",
22
- "Religion",
23
- "Language"
24
- ),
25
  selected = "Overall"
26
  ),
 
 
 
 
 
 
 
 
 
 
 
 
27
  checkboxInput(
28
- inputId = "sort_desc",
29
- label = "Sort in descending order",
30
  value = TRUE
31
- ),
32
- hr(),
33
- sliderInput(
34
- inputId = "top_n",
35
- label = "Number of Countries to Display in Plot:",
36
- min = 5,
37
- max = 50,
38
- value = 10,
39
- step = 1
40
  )
41
  ),
42
-
 
43
  mainPanel(
44
- tabsetPanel(
45
- tabPanel(
46
- title = "Plot",
47
- plotOutput("bar_plot", height = "600px")
48
- ),
49
- tabPanel(
50
- title = "Data Table",
51
- DTOutput("data_table")
52
- ),
53
- tabPanel(
54
- title = "Summary",
55
- verbatimTextOutput("summary_text")
56
- )
57
  )
58
  )
59
  )
60
  )
61
 
 
62
  server <- function(input, output, session) {
63
-
64
- # Load the data (adjust the path as necessary)
65
- data_raw <- reactive({
66
- read.csv("CountryRepresentationRankings.csv", stringsAsFactors = FALSE)
 
67
  })
68
 
69
- # Reactively prepare the data for plotting and table display
70
- data_prepared <- reactive({
71
- req(data_raw())
72
- # Convert to tibble for convenience
73
- df <- tibble::as_tibble(data_raw())
74
-
75
- # Ensure the selected metric is numeric for plotting
76
- # (This is typically already numeric, but we can do a safe check.)
77
- # Also handle potential issues with missing values.
78
- df <- df %>%
79
- mutate(
80
- across(all_of(input$metric), as.numeric)
81
- ) %>%
82
- filter(!is.na(.data[[input$metric]]))
83
-
84
- # Sort ascending or descending
85
- if (input$sort_desc) {
86
- df <- df %>% arrange(desc(.data[[input$metric]]))
87
- } else {
88
- df <- df %>% arrange(.data[[input$metric]])
89
- }
90
 
91
- # Keep only the top N rows for plotting
92
- df <- df %>% slice_head(n = input$top_n)
93
 
94
- df
 
 
 
 
 
 
95
  })
96
-
97
- # Render bar plot of the selected metric for top N countries
98
- output$bar_plot <- renderPlot({
99
- df <- data_prepared()
100
 
101
- # Convert Country to factor for a nice ordered plot
102
- df <- df %>%
103
- mutate(Country = factor(Country, levels = Country))
 
104
 
105
- ggplot(df, aes(x = Country, y = .data[[input$metric]])) +
 
 
 
 
106
  geom_col(fill = "steelblue") +
107
- coord_flip() +
108
  labs(
109
  x = "Country",
110
- y = paste0(input$metric, " Index"),
111
- title = paste("Top", input$top_n, "Countries by", input$metric)
112
  ) +
113
  theme_minimal(base_size = 14)
114
  })
115
 
116
- # Render data table of the entire dataset
117
- output$data_table <- renderDT({
118
- req(data_raw())
119
  datatable(
120
- data_raw(),
121
  options = list(pageLength = 10, autoWidth = TRUE),
122
- filter = "top",
123
  rownames = FALSE
124
  )
125
  })
126
-
127
- # Render summary statistics text for the selected metric
128
- output$summary_text <- renderPrint({
129
- df <- data_raw()
130
- req(df)
131
- # Convert the chosen metric to numeric if needed
132
- df[[input$metric]] <- suppressWarnings(as.numeric(df[[input$metric]]))
133
-
134
- valid_metric <- df[[input$metric]][!is.na(df[[input$metric]])]
135
- if (length(valid_metric) == 0) {
136
- cat("No valid numeric data for the selected metric.")
137
- } else {
138
- summary_stats <- summary(valid_metric)
139
- cat("Summary of", input$metric, "across all countries:\n")
140
- print(summary_stats)
141
- }
142
- })
143
  }
144
 
145
- shinyApp(ui = ui, server = server)
 
 
1
+ # app.R
2
 
3
+ # Load necessary libraries
4
  library(shiny)
5
+ library(readr) # for reading CSVs
6
+ library(dplyr) # for data manipulation
7
+ library(ggplot2) # for plotting
8
+ library(DT) # for rendering data tables interactively
9
 
10
+ # Define UI
11
  ui <- fluidPage(
12
+
13
+ # Title of the application
14
+ titlePanel("Country Representation Explorer"),
15
+
16
+ # Sidebar layout
17
  sidebarLayout(
18
  sidebarPanel(
19
+ # Input: Select which representation metric to visualize
20
  selectInput(
21
  inputId = "metric",
22
+ label = "Choose representation metric:",
23
+ choices = c("Overall", "Representation Gap", "Ethnicity",
24
+ "Gender", "Religion", "Language"),
 
 
 
 
 
 
25
  selected = "Overall"
26
  ),
27
+
28
+ # Input: Numeric slider to filter based on the chosen metric
29
+ sliderInput(
30
+ inputId = "metricRange",
31
+ label = "Filter countries by metric range:",
32
+ min = -10, # set a plausible minimum range
33
+ max = 10, # set a plausible maximum range
34
+ value = c(-10, 10),
35
+ step = 0.1
36
+ ),
37
+
38
+ # Checkbox to toggle data table
39
  checkboxInput(
40
+ inputId = "showDataTable",
41
+ label = "Show data table of filtered results",
42
  value = TRUE
 
 
 
 
 
 
 
 
 
43
  )
44
  ),
45
+
46
+ # Main panel to display outputs
47
  mainPanel(
48
+ # Output: Bar plot
49
+ plotOutput("repPlot", height = "600px"),
50
+
51
+ # Output: Data table (shown only when checkbox is TRUE)
52
+ conditionalPanel(
53
+ condition = "input.showDataTable == true",
54
+ DTOutput("tableOut")
 
 
 
 
 
 
55
  )
56
  )
57
  )
58
  )
59
 
60
+ # Define server logic
61
  server <- function(input, output, session) {
62
+
63
+ # Read in the CSV
64
+ # Make sure your 'CountryRepresentationRankings.csv' file is in the same folder as this script
65
+ full_data <- reactive({
66
+ read_csv("CountryRepresentationRankings.csv", show_col_types = FALSE)
67
  })
68
 
69
+ # Reactive subset of the data based on the metric range selected
70
+ filtered_data <- reactive({
71
+ req(input$metricRange)
72
+ req(input$metric)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
+ # Ensure data is loaded
75
+ data <- full_data()
76
 
77
+ # Filter based on user-selected metric range
78
+ data %>%
79
+ filter(
80
+ # get() dynamically selects the column name based on input$metric
81
+ get(input$metric) >= input$metricRange[1] &
82
+ get(input$metric) <= input$metricRange[2]
83
+ )
84
  })
85
+
86
+ # Render the bar plot
87
+ output$repPlot <- renderPlot({
88
+ data_for_plot <- filtered_data()
89
 
90
+ # Proceed only if there's data to plot
91
+ validate(
92
+ need(nrow(data_for_plot) > 0, "No data available within this range.")
93
+ )
94
 
95
+ # Order countries by the chosen metric
96
+ ggplot(data_for_plot, aes(
97
+ x = reorder(Country, get(input$metric)),
98
+ y = get(input$metric)
99
+ )) +
100
  geom_col(fill = "steelblue") +
101
+ coord_flip() + # Flip coordinates for easier reading of country names
102
  labs(
103
  x = "Country",
104
+ y = paste(input$metric, "Index"),
105
+ title = paste("Countries by", input$metric, "Representation")
106
  ) +
107
  theme_minimal(base_size = 14)
108
  })
109
 
110
+ # Render the data table (only if checkbox is selected)
111
+ output$tableOut <- renderDT({
112
+ data_for_table <- filtered_data()
113
  datatable(
114
+ data_for_table,
115
  options = list(pageLength = 10, autoWidth = TRUE),
 
116
  rownames = FALSE
117
  )
118
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  }
120
 
121
+ # Create Shiny app
122
+ shinyApp(ui, server)