]> nmode's Git Repositories - Rnaught/blob - inst/app/scripts/data.R
Update Shiny app
[Rnaught] / inst / app / scripts / data.R
1 # Main logic block for data-related interactions.
2 data_logic <- function(input, output, react_values) {
3 # Initialize a data frame to hold the datasets.
4 react_values$data_table <- data.frame(
5 Name = character(0),
6 `Time units` = character(0),
7 `Case counts` = character(0),
8 check.names = FALSE
9 )
10
11 manual_entry(input, output, react_values)
12 upload_data(input, output, react_values)
13 load_samples(input, output, react_values)
14 render_data_table(output, react_values)
15 render_plot(input, output, react_values, "Days")
16 render_plot(input, output, react_values, "Weeks")
17 delete_data(input, react_values)
18 export_data(output, react_values)
19 }
20
21 # Convert the input case counts string to an integer vector.
22 tokenize_counts <- function(counts_str) {
23 suppressWarnings(as.integer(unlist(strsplit(trimws(counts_str), ","))))
24 }
25
26 # Render the plots for daily and weekly data when the data table is updated.
27 render_plot <- function(input, output, react_values, time_units) {
28 observe({
29 datasets <- react_values$data_table[
30 which(react_values$data_table[["Time units"]] == time_units),
31 ]
32
33 data_plot <- plotly::plot_ly(type = "scatter", mode = "lines")
34 if (nrow(datasets) > 0) {
35 for (i in seq_len(nrow(datasets))) {
36 counts <- tokenize_counts(datasets[i, 3])
37 data_plot <- plotly::add_trace(data_plot,
38 x = seq_along(counts) - 1, y = counts, name = datasets[i, 1]
39 )
40 }
41 }
42
43 plot_title <- paste(
44 if (time_units == "Days") "Daily" else "Weekly", "case counts"
45 )
46
47 data_plot <- plotly::layout(data_plot, title = plot_title,
48 xaxis = list(title = time_units), yaxis = list(title = "Cases")
49 )
50
51 data_plot <- plotly::config(data_plot, displaylogo = FALSE,
52 toImageButtonOptions = list(
53 filename = paste0("Rnaught_data_", tolower(time_units), "_plot")
54 )
55 )
56
57 output[[paste0("data_plot_", tolower(time_units))]] <-
58 plotly::renderPlotly(data_plot)
59 })
60 }
61
62 # Validate and add manually-entered datasets.
63 manual_entry <- function(input, output, react_values) {
64 observeEvent(input$data_bulk, {
65 validate_data(input, output, react_values, "data_area")
66 })
67 }
68
69 # Validate and add datasets from a CSV file.
70 upload_data <- function(input, output, react_values) {
71 observeEvent(input$data_upload, {
72 validate_data(input, output, react_values, "data_upload")
73 })
74 }
75
76 # Validate datasets and update the data table.
77 validate_data <- function(input, output, react_values, data_source) {
78 tryCatch(
79 {
80 if (data_source == "data_area") {
81 datasets <- read.csv(text = input$data_area, header = FALSE, sep = ",")
82 } else if (data_source == "data_upload") {
83 datasets <- read.csv(
84 file = input$data_upload$datapath, header = FALSE, sep = ","
85 )
86 }
87
88 names <- trimws(datasets[, 1])
89 units <- trimws(datasets[, 2])
90 counts <- apply(data.frame(datasets[, 3:ncol(datasets)]), 1,
91 function(row) {
92 row <- suppressWarnings(as.integer(row))
93 toString(row[!is.na(row) & row >= 0])
94 }
95 )
96
97 warning_text <- ""
98
99 # Ensure the dataset names are neither blank nor duplicates.
100 if (anyNA(names) || any(names == "")) {
101 warning_text <- paste0(warning_text,
102 "Each row must begin with a non-blank dataset name.<br>"
103 )
104 } else {
105 if (length(unique(names)) != length(names)) {
106 warning_text <- paste0(warning_text,
107 "The rows contain duplicate dataset names.<br>"
108 )
109 }
110 if (any(names %in% react_values$data_table[, 1])) {
111 warning_text <- paste0(warning_text,
112 "The rows contain dataset names which already exist.<br>"
113 )
114 }
115 }
116
117 # Ensure the second entry in each row is a time unit equal to
118 # "Days" or "Weeks".
119 if (!all(units %in% c("Days", "Weeks"))) {
120 warning_text <- paste0(warning_text,
121 "The second entry in each row must be either 'Days' or 'Weeks'.<br>"
122 )
123 }
124
125 # Ensure the counts in each row have at least one non-negative integer.
126 if (any(counts == "")) {
127 warning_text <- paste0(warning_text,
128 "Each row must contain at least one non-negative integer.<br>"
129 )
130 }
131
132 output[[paste0(data_source, "_warn")]] <- renderUI(HTML(warning_text))
133
134 if (warning_text == "") {
135 # Add the new datasets to the data table.
136 new_rows <- data.frame(names, units, counts)
137 colnames(new_rows) <- c("Name", "Time units", "Case counts")
138 react_values$data_table <- rbind(react_values$data_table, new_rows)
139
140 # Evaluate all existing estimators on the new datasets and update the
141 # corresponding columns in the estimates table.
142 update_estimates_cols(new_rows, react_values)
143
144 showNotification("Datasets added successfully.",
145 duration = 3, id = "notify-success"
146 )
147 }
148 },
149 error = function(e) {
150 output[[paste0(data_source, "_warn")]] <- renderText(
151 "The input does not match the required format."
152 )
153 }
154 )
155 }
156
157 # Load sample datasets.
158 load_samples <- function(input, output, react_values) {
159 observeEvent(input$data_samples, {
160 names <- c()
161 units <- c()
162 counts <- c()
163
164 # COVID-19 Canada, March 2020 (weekly).
165 if (input$covid_canada) {
166 names <- c(names, "COVID-19 Canada 2020/03/03 - 2020/03/31")
167 units <- c(units, "Weeks")
168 counts <- c(counts, toString(Rnaught::COVIDCanada[seq(41, 69, 7), 2]))
169 }
170 # COVID-19 Ontario, March 2020 (weekly).
171 if (input$covid_ontario) {
172 names <- c(names, "COVID-19 Ontario 2020/03/03 - 2020/03/31")
173 units <- c(units, "Weeks")
174 counts <- c(counts,
175 toString(Rnaught::COVIDCanadaPT[seq(10176, 10204, 7), 3])
176 )
177 }
178
179 if (length(names) == 0) {
180 output$data_samples_warn <- renderText(
181 "At least one sample dataset must be selected."
182 )
183 } else if (any(names %in% react_values$data_table[, 1])) {
184 output$data_samples_warn <- renderText(
185 "At least one of the selected dataset names already exist."
186 )
187 } else {
188 output$data_samples_warn <- renderText("")
189
190 new_rows <- data.frame(names, units, counts)
191 colnames(new_rows) <- c("Name", "Time units", "Case counts")
192 react_values$data_table <- rbind(react_values$data_table, new_rows)
193
194 # Evaluate all existing estimators on the sample datasets and update the
195 # corresponding columns in the estimates table.
196 update_estimates_cols(new_rows, react_values)
197
198 showNotification("Datasets added successfully.",
199 duration = 3, id = "notify-success"
200 )
201 }
202 })
203 }
204
205 # Render the data table when new datasets are added.
206 render_data_table <- function(output, react_values) {
207 observe({
208 output$data_table <- DT::renderDataTable(
209 react_values$data_table, rownames = FALSE
210 )
211 })
212 }
213
214 # Delete rows in the data table and the corresponding columns in the estimates
215 # table.
216 delete_data <- function(input, react_values) {
217 observeEvent(input$data_delete, {
218 rows_selected <- input$data_table_rows_selected
219 react_values$data_table <- react_values$data_table[-rows_selected, ]
220 react_values$estimates_table <-
221 react_values$estimates_table[, -(rows_selected + 2)]
222 })
223 }
224
225 # Export data table as a CSV file.
226 export_data <- function(output, react_values) {
227 output$data_export <- downloadHandler(
228 filename = function() {
229 paste0("Rnaught_data_", format(Sys.time(), "%y-%m-%d_%H-%M-%S"), ".csv")
230 },
231 content = function(file) {
232 write.csv(react_values$data_table, file, row.names = FALSE)
233 }
234 )
235 }
236
237 # When new datasets are added, evaluate all existing estimators on them and
238 # add new columns to the estimates table.
239 update_estimates_cols <- function(datasets, react_values) {
240 new_cols <- data.frame(
241 matrix(nrow = nrow(react_values$estimates_table), ncol = nrow(datasets))
242 )
243 colnames(new_cols) <- datasets[, 1]
244
245 if (nrow(new_cols) > 0) {
246 for (row in seq_len(nrow(new_cols))) {
247 estimator <- react_values$estimators[[row]]
248 for (col in seq_len(ncol(new_cols))) {
249 new_cols[row, col] <- eval_estimator(estimator, datasets[col, ])
250 }
251 }
252 }
253
254 react_values$estimates_table <- cbind(
255 react_values$estimates_table, new_cols
256 )
257 }