1 |
#' `teal` module: Principal component analysis |
|
2 |
#' |
|
3 |
#' Module conducts principal component analysis (PCA) on a given dataset and offers different |
|
4 |
#' ways of visualizing the outcomes, including elbow plot, circle plot, biplot, and eigenvector plot. |
|
5 |
#' Additionally, it enables dynamic customization of plot aesthetics, such as opacity, size, and |
|
6 |
#' font size, through UI inputs. |
|
7 |
#' |
|
8 |
#' @inheritParams teal::module |
|
9 |
#' @inheritParams shared_params |
|
10 |
#' @param dat (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
11 |
#' specifying columns used to compute PCA. |
|
12 |
#' @param font_size (`numeric`) optional, specifies font size. |
|
13 |
#' It controls the font size for plot titles, axis labels, and legends. |
|
14 |
#' - If vector of `length == 1` then the font sizes will have a fixed size. |
|
15 |
#' - while vector of `value`, `min`, and `max` allows dynamic adjustment. |
|
16 |
#' @param ggplot2_args `r roxygen_ggplot2_args_param("Elbow plot", "Circle plot", "Biplot", "Eigenvector plot")` |
|
17 |
#' |
|
18 |
#' @inherit shared_params return |
|
19 |
#' |
|
20 |
#' @section Decorating Module: |
|
21 |
#' |
|
22 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
23 |
#' - `elbow_plot` (`ggplot`) |
|
24 |
#' - `circle_plot` (`ggplot`) |
|
25 |
#' - `biplot` (`ggplot`) |
|
26 |
#' - `eigenvector_plot` (`ggplot`) |
|
27 |
#' |
|
28 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
29 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
30 |
#' See code snippet below: |
|
31 |
#' |
|
32 |
#' ``` |
|
33 |
#' tm_a_pca( |
|
34 |
#' ..., # arguments for module |
|
35 |
#' decorators = list( |
|
36 |
#' elbow_plot = teal_transform_module(...), # applied to the `elbow_plot` output |
|
37 |
#' circle_plot = teal_transform_module(...), # applied to the `circle_plot` output |
|
38 |
#' biplot = teal_transform_module(...), # applied to the `biplot` output |
|
39 |
#' eigenvector_plot = teal_transform_module(...) # applied to the `eigenvector_plot` output |
|
40 |
#' ) |
|
41 |
#' ) |
|
42 |
#' ``` |
|
43 |
#' |
|
44 |
#' For additional details and examples of decorators, refer to the vignette |
|
45 |
#' `vignette("decorate-module-output", package = "teal.modules.general")`. |
|
46 |
#' |
|
47 |
#' To learn more please refer to the vignette |
|
48 |
#' `vignette("transform-module-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
49 |
#' |
|
50 |
#' @inheritSection teal::example_module Reporting |
|
51 |
#' |
|
52 |
#' @examplesShinylive |
|
53 |
#' library(teal.modules.general) |
|
54 |
#' interactive <- function() TRUE |
|
55 |
#' {{ next_example }} |
|
56 |
#' @examples |
|
57 |
#' |
|
58 |
#' # general data example |
|
59 |
#' data <- teal_data() |
|
60 |
#' data <- within(data, { |
|
61 |
#' require(nestcolor) |
|
62 |
#' USArrests <- USArrests |
|
63 |
#' }) |
|
64 |
#' |
|
65 |
#' app <- init( |
|
66 |
#' data = data, |
|
67 |
#' modules = modules( |
|
68 |
#' tm_a_pca( |
|
69 |
#' "PCA", |
|
70 |
#' dat = data_extract_spec( |
|
71 |
#' dataname = "USArrests", |
|
72 |
#' select = select_spec( |
|
73 |
#' choices = variable_choices( |
|
74 |
#' data = data[["USArrests"]], c("Murder", "Assault", "UrbanPop", "Rape") |
|
75 |
#' ), |
|
76 |
#' selected = c("Murder", "Assault"), |
|
77 |
#' multiple = TRUE |
|
78 |
#' ), |
|
79 |
#' filter = NULL |
|
80 |
#' ) |
|
81 |
#' ) |
|
82 |
#' ) |
|
83 |
#' ) |
|
84 |
#' if (interactive()) { |
|
85 |
#' shinyApp(app$ui, app$server) |
|
86 |
#' } |
|
87 |
#' |
|
88 |
#' @examplesShinylive |
|
89 |
#' library(teal.modules.general) |
|
90 |
#' interactive <- function() TRUE |
|
91 |
#' {{ next_example }} |
|
92 |
#' @examples |
|
93 |
#' |
|
94 |
#' # CDISC data example |
|
95 |
#' data <- teal_data() |
|
96 |
#' data <- within(data, { |
|
97 |
#' require(nestcolor) |
|
98 |
#' ADSL <- teal.data::rADSL |
|
99 |
#' }) |
|
100 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
101 |
#' |
|
102 |
#' app <- init( |
|
103 |
#' data = data, |
|
104 |
#' modules = modules( |
|
105 |
#' tm_a_pca( |
|
106 |
#' "PCA", |
|
107 |
#' dat = data_extract_spec( |
|
108 |
#' dataname = "ADSL", |
|
109 |
#' select = select_spec( |
|
110 |
#' choices = variable_choices( |
|
111 |
#' data = data[["ADSL"]], c("BMRKR1", "AGE", "EOSDY") |
|
112 |
#' ), |
|
113 |
#' selected = c("BMRKR1", "AGE"), |
|
114 |
#' multiple = TRUE |
|
115 |
#' ), |
|
116 |
#' filter = NULL |
|
117 |
#' ) |
|
118 |
#' ) |
|
119 |
#' ) |
|
120 |
#' ) |
|
121 |
#' if (interactive()) { |
|
122 |
#' shinyApp(app$ui, app$server) |
|
123 |
#' } |
|
124 |
#' |
|
125 |
#' @export |
|
126 |
#' |
|
127 |
tm_a_pca <- function(label = "Principal Component Analysis", |
|
128 |
dat, |
|
129 |
plot_height = c(600, 200, 2000), |
|
130 |
plot_width = NULL, |
|
131 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
132 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
133 |
rotate_xaxis_labels = FALSE, |
|
134 |
font_size = c(12, 8, 20), |
|
135 |
alpha = c(1, 0, 1), |
|
136 |
size = c(2, 1, 8), |
|
137 |
pre_output = NULL, |
|
138 |
post_output = NULL, |
|
139 |
transformators = list(), |
|
140 |
decorators = list()) { |
|
141 | ! |
message("Initializing tm_a_pca") |
142 | ||
143 |
# Normalize the parameters |
|
144 | ! |
if (inherits(dat, "data_extract_spec")) dat <- list(dat) |
145 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
146 | ||
147 |
# Start of assertions |
|
148 | ! |
checkmate::assert_string(label) |
149 | ! |
checkmate::assert_list(dat, types = "data_extract_spec") |
150 | ||
151 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
152 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
153 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
154 | ! |
checkmate::assert_numeric( |
155 | ! |
plot_width[1], |
156 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
157 |
) |
|
158 | ||
159 | ! |
ggtheme <- match.arg(ggtheme) |
160 | ||
161 | ! |
plot_choices <- c("Elbow plot", "Circle plot", "Biplot", "Eigenvector plot") |
162 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
163 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
164 | ||
165 | ! |
checkmate::assert_flag(rotate_xaxis_labels) |
166 | ||
167 | ! |
if (length(font_size) == 1) { |
168 | ! |
checkmate::assert_numeric(font_size, any.missing = FALSE, finite = TRUE, lower = 8, upper = 20) |
169 |
} else { |
|
170 | ! |
checkmate::assert_numeric(font_size, len = 3, any.missing = FALSE, finite = TRUE, lower = 8, upper = 20) |
171 | ! |
checkmate::assert_numeric(font_size[1], lower = font_size[2], upper = font_size[3], .var.name = "font_size") |
172 |
} |
|
173 | ||
174 | ! |
if (length(alpha) == 1) { |
175 | ! |
checkmate::assert_numeric(alpha, any.missing = FALSE, finite = TRUE, lower = 0, upper = 1) |
176 |
} else { |
|
177 | ! |
checkmate::assert_numeric(alpha, len = 3, any.missing = FALSE, finite = TRUE, lower = 0, upper = 1) |
178 | ! |
checkmate::assert_numeric(alpha[1], lower = alpha[2], upper = alpha[3], .var.name = "alpha") |
179 |
} |
|
180 | ||
181 | ! |
if (length(size) == 1) { |
182 | ! |
checkmate::assert_numeric(size, any.missing = FALSE, finite = TRUE, lower = 1, upper = 8) |
183 |
} else { |
|
184 | ! |
checkmate::assert_numeric(size, len = 3, any.missing = FALSE, finite = TRUE, lower = 1, upper = 8) |
185 | ! |
checkmate::assert_numeric(size[1], lower = size[2], upper = size[3], .var.name = "size") |
186 |
} |
|
187 | ||
188 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
189 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
190 | ||
191 | ! |
available_decorators <- c("elbow_plot", "circle_plot", "biplot", "eigenvector_plot") |
192 | ! |
assert_decorators(decorators, available_decorators) |
193 | ||
194 |
# Make UI args |
|
195 | ! |
args <- as.list(environment()) |
196 | ||
197 | ! |
data_extract_list <- list(dat = dat) |
198 | ||
199 | ! |
ans <- module( |
200 | ! |
label = label, |
201 | ! |
server = srv_a_pca, |
202 | ! |
ui = ui_a_pca, |
203 | ! |
ui_args = args, |
204 | ! |
server_args = c( |
205 | ! |
data_extract_list, |
206 | ! |
list( |
207 | ! |
plot_height = plot_height, |
208 | ! |
plot_width = plot_width, |
209 | ! |
ggplot2_args = ggplot2_args, |
210 | ! |
decorators = decorators |
211 |
) |
|
212 |
), |
|
213 | ! |
transformators = transformators, |
214 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
215 |
) |
|
216 | ! |
attr(ans, "teal_bookmarkable") <- FALSE |
217 | ! |
ans |
218 |
} |
|
219 | ||
220 |
# UI function for the PCA module |
|
221 |
ui_a_pca <- function(id, ...) { |
|
222 | ! |
ns <- NS(id) |
223 | ! |
args <- list(...) |
224 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$dat) |
225 | ||
226 | ! |
color_selector <- args$dat |
227 | ! |
for (i in seq_along(color_selector)) { |
228 | ! |
color_selector[[i]]$select$multiple <- FALSE |
229 | ! |
color_selector[[i]]$select$always_selected <- NULL |
230 | ! |
color_selector[[i]]$select$selected <- NULL |
231 |
} |
|
232 | ||
233 | ! |
tagList( |
234 | ! |
teal.widgets::standard_layout( |
235 | ! |
output = teal.widgets::white_small_well( |
236 | ! |
uiOutput(ns("all_plots")) |
237 |
), |
|
238 | ! |
encoding = tags$div( |
239 | ! |
tags$label("Encodings", class = "text-primary"), |
240 | ! |
teal.transform::datanames_input(args["dat"]), |
241 | ! |
teal.transform::data_extract_ui( |
242 | ! |
id = ns("dat"), |
243 | ! |
label = "Data selection", |
244 | ! |
data_extract_spec = args$dat, |
245 | ! |
is_single_dataset = is_single_dataset_value |
246 |
), |
|
247 | ! |
bslib::accordion( |
248 | ! |
open = TRUE, |
249 | ! |
bslib::accordion_panel( |
250 | ! |
title = "Display", |
251 | ! |
checkboxGroupInput( |
252 | ! |
ns("tables_display"), |
253 | ! |
"Tables display", |
254 | ! |
choices = c("PC importance" = "importance", "Eigenvectors" = "eigenvector"), |
255 | ! |
selected = c("importance", "eigenvector") |
256 |
), |
|
257 | ! |
radioButtons( |
258 | ! |
ns("plot_type"), |
259 | ! |
label = "Plot type", |
260 | ! |
choices = args$plot_choices, |
261 | ! |
selected = args$plot_choices[1] |
262 |
), |
|
263 | ! |
conditionalPanel( |
264 | ! |
condition = sprintf("input['%s'] == 'Elbow plot'", ns("plot_type")), |
265 | ! |
ui_decorate_teal_data( |
266 | ! |
ns("d_elbow_plot"), |
267 | ! |
decorators = select_decorators(args$decorators, "elbow_plot") |
268 |
) |
|
269 |
), |
|
270 | ! |
conditionalPanel( |
271 | ! |
condition = sprintf("input['%s'] == 'Circle plot'", ns("plot_type")), |
272 | ! |
ui_decorate_teal_data( |
273 | ! |
ns("d_circle_plot"), |
274 | ! |
decorators = select_decorators(args$decorators, "circle_plot") |
275 |
) |
|
276 |
), |
|
277 | ! |
conditionalPanel( |
278 | ! |
condition = sprintf("input['%s'] == 'Biplot'", ns("plot_type")), |
279 | ! |
ui_decorate_teal_data( |
280 | ! |
ns("d_biplot"), |
281 | ! |
decorators = select_decorators(args$decorators, "biplot") |
282 |
) |
|
283 |
), |
|
284 | ! |
conditionalPanel( |
285 | ! |
condition = sprintf("input['%s'] == 'Eigenvector plot'", ns("plot_type")), |
286 | ! |
ui_decorate_teal_data( |
287 | ! |
ns("d_eigenvector_plot"), |
288 | ! |
decorators = select_decorators(args$decorators, "eigenvector_plot") |
289 |
) |
|
290 |
) |
|
291 |
), |
|
292 | ! |
bslib::accordion_panel( |
293 | ! |
title = "Pre-processing", |
294 | ! |
radioButtons( |
295 | ! |
ns("standardization"), "Standardization", |
296 | ! |
choices = c("None" = "none", "Center" = "center", "Center & Scale" = "center_scale"), |
297 | ! |
selected = "center_scale" |
298 |
), |
|
299 | ! |
radioButtons( |
300 | ! |
ns("na_action"), "NA action", |
301 | ! |
choices = c("None" = "none", "Drop" = "drop"), |
302 | ! |
selected = "none" |
303 |
) |
|
304 |
), |
|
305 | ! |
bslib::accordion_panel( |
306 | ! |
title = "Selected plot specific settings", |
307 | ! |
uiOutput(ns("plot_settings")), |
308 | ! |
conditionalPanel( |
309 | ! |
condition = sprintf("input['%s'] == 'Biplot'", ns("plot_type")), |
310 | ! |
list( |
311 | ! |
teal.transform::data_extract_ui( |
312 | ! |
id = ns("response"), |
313 | ! |
label = "Color by", |
314 | ! |
data_extract_spec = color_selector, |
315 | ! |
is_single_dataset = is_single_dataset_value |
316 |
), |
|
317 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("alpha"), "Opacity:", args$alpha, ticks = FALSE), |
318 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("size"), "Points size:", args$size, ticks = FALSE) |
319 |
) |
|
320 |
) |
|
321 |
), |
|
322 | ! |
bslib::accordion_panel( |
323 | ! |
title = "Plot settings", |
324 | ! |
collapsed = TRUE, |
325 | ! |
conditionalPanel( |
326 | ! |
condition = sprintf( |
327 | ! |
"input['%s'] == 'Elbow plot' || input['%s'] == 'Eigenvector plot'", |
328 | ! |
ns("plot_type"), |
329 | ! |
ns("plot_type") |
330 |
), |
|
331 | ! |
list(checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = args$rotate_xaxis_labels)) |
332 |
), |
|
333 | ! |
selectInput( |
334 | ! |
inputId = ns("ggtheme"), |
335 | ! |
label = "Theme (by ggplot):", |
336 | ! |
choices = ggplot_themes, |
337 | ! |
selected = args$ggtheme, |
338 | ! |
multiple = FALSE |
339 |
), |
|
340 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("font_size"), "Font Size", args$font_size, ticks = FALSE) |
341 |
) |
|
342 |
) |
|
343 |
), |
|
344 | ! |
forms = tagList( |
345 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
346 |
), |
|
347 | ! |
pre_output = args$pre_output, |
348 | ! |
post_output = args$post_output |
349 |
) |
|
350 |
) |
|
351 |
} |
|
352 | ||
353 |
# Server function for the PCA module |
|
354 |
srv_a_pca <- function(id, data, dat, plot_height, plot_width, ggplot2_args, decorators) { |
|
355 | ! |
checkmate::assert_class(data, "reactive") |
356 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
357 | ! |
moduleServer(id, function(input, output, session) { |
358 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
359 | ||
360 | ! |
response <- dat |
361 | ||
362 | ! |
for (i in seq_along(response)) { |
363 | ! |
response[[i]]$select$multiple <- FALSE |
364 | ! |
response[[i]]$select$always_selected <- NULL |
365 | ! |
response[[i]]$select$selected <- NULL |
366 | ! |
all_cols <- teal.data::col_labels(isolate(data())[[response[[i]]$dataname]]) |
367 | ! |
ignore_cols <- unlist(teal.data::join_keys(isolate(data()))[[response[[i]]$dataname]]) |
368 | ! |
color_cols <- all_cols[!names(all_cols) %in% ignore_cols] |
369 | ! |
response[[i]]$select$choices <- teal.transform::choices_labeled(names(color_cols), color_cols) |
370 |
} |
|
371 | ||
372 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
373 | ! |
data_extract = list(dat = dat, response = response), |
374 | ! |
datasets = data, |
375 | ! |
select_validation_rule = list( |
376 | ! |
dat = ~ if (length(.) < 2L) "Please select more than 1 variable to perform PCA.", |
377 | ! |
response = shinyvalidate::compose_rules( |
378 | ! |
shinyvalidate::sv_optional(), |
379 | ! |
~ if (isTRUE(is.element(., selector_list()$dat()$select))) { |
380 | ! |
"Response must not have been used for PCA." |
381 |
} |
|
382 |
) |
|
383 |
) |
|
384 |
) |
|
385 | ||
386 | ! |
iv_r <- reactive({ |
387 | ! |
iv <- shinyvalidate::InputValidator$new() |
388 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
389 |
}) |
|
390 | ||
391 | ! |
iv_extra <- shinyvalidate::InputValidator$new() |
392 | ! |
iv_extra$add_rule("x_axis", function(value) { |
393 | ! |
if (isTRUE(input$plot_type %in% c("Circle plot", "Biplot"))) { |
394 | ! |
if (!shinyvalidate::input_provided(value)) { |
395 | ! |
"Need X axis" |
396 |
} |
|
397 |
} |
|
398 |
}) |
|
399 | ! |
iv_extra$add_rule("y_axis", function(value) { |
400 | ! |
if (isTRUE(input$plot_type %in% c("Circle plot", "Biplot"))) { |
401 | ! |
if (!shinyvalidate::input_provided(value)) { |
402 | ! |
"Need Y axis" |
403 |
} |
|
404 |
} |
|
405 |
}) |
|
406 | ! |
rule_dupl <- function(...) { |
407 | ! |
if (isTRUE(input$plot_type %in% c("Circle plot", "Biplot"))) { |
408 | ! |
if (isTRUE(input$x_axis == input$y_axis)) { |
409 | ! |
"Please choose different X and Y axes." |
410 |
} |
|
411 |
} |
|
412 |
} |
|
413 | ! |
iv_extra$add_rule("x_axis", rule_dupl) |
414 | ! |
iv_extra$add_rule("y_axis", rule_dupl) |
415 | ! |
iv_extra$add_rule("variables", function(value) { |
416 | ! |
if (identical(input$plot_type, "Circle plot")) { |
417 | ! |
if (!shinyvalidate::input_provided(value)) { |
418 | ! |
"Need Original Coordinates" |
419 |
} |
|
420 |
} |
|
421 |
}) |
|
422 | ! |
iv_extra$add_rule("pc", function(value) { |
423 | ! |
if (identical(input$plot_type, "Eigenvector plot")) { |
424 | ! |
if (!shinyvalidate::input_provided(value)) { |
425 | ! |
"Need PC" |
426 |
} |
|
427 |
} |
|
428 |
}) |
|
429 | ! |
iv_extra$enable() |
430 | ||
431 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
432 | ! |
selector_list = selector_list, |
433 | ! |
datasets = data |
434 |
) |
|
435 | ! |
qenv <- reactive({ |
436 | ! |
obj <- data() |
437 | ! |
teal.reporter::teal_card(obj) <- |
438 | ! |
c( |
439 | ! |
teal.reporter::teal_card("# Principal Component Analysis"), |
440 | ! |
teal.reporter::teal_card(obj), |
441 | ! |
teal.reporter::teal_card("## Module's code") |
442 |
) |
|
443 | ! |
teal.code::eval_code(obj, 'library("ggplot2");library("dplyr");library("tidyr")') # nolint: quotes |
444 |
}) |
|
445 | ! |
anl_merged_q <- reactive({ |
446 | ! |
req(anl_merged_input()) |
447 | ! |
qenv() %>% |
448 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
449 |
}) |
|
450 | ||
451 | ! |
merged <- list( |
452 | ! |
anl_input_r = anl_merged_input, |
453 | ! |
anl_q_r = anl_merged_q |
454 |
) |
|
455 | ||
456 | ! |
validation <- reactive({ |
457 | ! |
req(merged$anl_q_r()) |
458 |
# inputs |
|
459 | ! |
keep_cols <- as.character(merged$anl_input_r()$columns_source$dat) |
460 | ! |
na_action <- input$na_action |
461 | ! |
standardization <- input$standardization |
462 | ! |
center <- standardization %in% c("center", "center_scale") |
463 | ! |
scale <- standardization == "center_scale" |
464 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
465 | ||
466 | ! |
teal::validate_has_data(ANL, 10) |
467 | ! |
validate(need( |
468 | ! |
na_action != "none" | !anyNA(ANL[keep_cols]), |
469 | ! |
paste( |
470 | ! |
"There are NAs in the dataset. Please deal with them in preprocessing", |
471 | ! |
"or select \"Drop\" in the NA actions inside the encodings panel (left)." |
472 |
) |
|
473 |
)) |
|
474 | ! |
if (scale) { |
475 | ! |
not_single <- vapply(ANL[keep_cols], function(column) length(unique(column)) != 1, FUN.VALUE = logical(1)) |
476 | ||
477 | ! |
msg <- paste0( |
478 | ! |
"You have selected `Center & Scale` under `Standardization` in the `Pre-processing` panel, ", |
479 | ! |
"but one or more of your columns has/have a variance value of zero, indicating all values are identical" |
480 |
) |
|
481 | ! |
validate(need(all(not_single), msg)) |
482 |
} |
|
483 |
}) |
|
484 | ||
485 |
# computation ---- |
|
486 | ! |
computation <- reactive({ |
487 | ! |
validation() |
488 | ||
489 |
# inputs |
|
490 | ! |
keep_cols <- as.character(merged$anl_input_r()$columns_source$dat) |
491 | ! |
na_action <- input$na_action |
492 | ! |
standardization <- input$standardization |
493 | ! |
center <- standardization %in% c("center", "center_scale") |
494 | ! |
scale <- standardization == "center_scale" |
495 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
496 | ||
497 | ! |
qenv <- teal.code::eval_code( |
498 | ! |
merged$anl_q_r(), |
499 | ! |
substitute( |
500 | ! |
expr = keep_columns <- keep_cols, |
501 | ! |
env = list(keep_cols = keep_cols) |
502 |
) |
|
503 |
) |
|
504 | ||
505 | ! |
if (na_action == "drop") { |
506 | ! |
qenv <- teal.code::eval_code( |
507 | ! |
qenv, |
508 | ! |
quote(ANL <- tidyr::drop_na(ANL, keep_columns)) |
509 |
) |
|
510 |
} |
|
511 | ||
512 | ! |
qenv <- teal.code::eval_code( |
513 | ! |
qenv, |
514 | ! |
substitute( |
515 | ! |
expr = pca <- summary(stats::prcomp(ANL[keep_columns], center = center, scale. = scale, retx = TRUE)), |
516 | ! |
env = list(center = center, scale = scale) |
517 |
) |
|
518 |
) |
|
519 | ||
520 | ! |
teal.reporter::teal_card(qenv) <- c(teal.reporter::teal_card(qenv), "## Principal Components Table") |
521 | ||
522 | ! |
qenv <- teal.code::eval_code( |
523 | ! |
qenv, |
524 | ! |
quote({ |
525 | ! |
tbl_importance <- dplyr::as_tibble(pca$importance, rownames = "Metric") |
526 | ! |
tbl_importance |
527 |
}) |
|
528 |
) |
|
529 | ||
530 | ! |
teal.reporter::teal_card(qenv) <- c(teal.reporter::teal_card(qenv), "## Eigenvectors Table") |
531 | ||
532 | ! |
teal.code::eval_code( |
533 | ! |
qenv, |
534 | ! |
quote({ |
535 | ! |
tbl_eigenvector <- dplyr::as_tibble(pca$rotation, rownames = "Variable") |
536 | ! |
tbl_eigenvector |
537 |
}) |
|
538 |
) |
|
539 |
}) |
|
540 | ||
541 |
# plot args ---- |
|
542 | ! |
output$plot_settings <- renderUI({ |
543 |
# reactivity triggers |
|
544 | ! |
req(iv_r()$is_valid()) |
545 | ! |
req(computation()) |
546 | ! |
qenv <- computation() |
547 | ||
548 | ! |
ns <- session$ns |
549 | ||
550 | ! |
pca <- qenv[["pca"]] |
551 | ! |
chcs_pcs <- colnames(pca$rotation) |
552 | ! |
chcs_vars <- qenv[["keep_columns"]] |
553 | ||
554 | ! |
tagList( |
555 | ! |
conditionalPanel( |
556 | ! |
condition = sprintf( |
557 | ! |
"input['%s'] == 'Biplot' || input['%s'] == 'Circle plot'", |
558 | ! |
ns("plot_type"), ns("plot_type") |
559 |
), |
|
560 | ! |
list( |
561 | ! |
teal.widgets::optionalSelectInput(ns("x_axis"), "X axis", choices = chcs_pcs, selected = chcs_pcs[1]), |
562 | ! |
teal.widgets::optionalSelectInput(ns("y_axis"), "Y axis", choices = chcs_pcs, selected = chcs_pcs[2]), |
563 | ! |
teal.widgets::optionalSelectInput( |
564 | ! |
ns("variables"), "Original coordinates", |
565 | ! |
choices = chcs_vars, selected = chcs_vars, |
566 | ! |
multiple = TRUE |
567 |
) |
|
568 |
) |
|
569 |
), |
|
570 | ! |
conditionalPanel( |
571 | ! |
condition = sprintf("input['%s'] == 'Elbow plot'", ns("plot_type")), |
572 | ! |
helpText("No plot specific settings available.") |
573 |
), |
|
574 | ! |
conditionalPanel( |
575 | ! |
condition = paste0("input['", ns("plot_type"), "'] == 'Eigenvector plot'"), |
576 | ! |
teal.widgets::optionalSelectInput(ns("pc"), "PC", choices = chcs_pcs, selected = chcs_pcs[1]) |
577 |
) |
|
578 |
) |
|
579 |
}) |
|
580 | ||
581 |
# plot elbow ---- |
|
582 | ! |
plot_elbow <- function(base_q) { |
583 | ! |
ggtheme <- input$ggtheme |
584 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
585 | ! |
font_size <- input$font_size |
586 | ||
587 | ! |
angle_value <- ifelse(isTRUE(rotate_xaxis_labels), 45, 0) |
588 | ! |
hjust_value <- ifelse(isTRUE(rotate_xaxis_labels), 1, 0.5) |
589 | ||
590 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
591 | ! |
labs = list(x = "Principal component", y = "Proportion of variance explained", color = "", fill = "Legend"), |
592 | ! |
theme = list( |
593 | ! |
legend.position = "right", |
594 | ! |
legend.spacing.y = quote(grid::unit(-5, "pt")), |
595 | ! |
legend.title = quote(ggplot2::element_text(vjust = 25)), |
596 | ! |
axis.text.x = substitute( |
597 | ! |
ggplot2::element_text(angle = angle_value, hjust = hjust_value), |
598 | ! |
list(angle_value = angle_value, hjust_value = hjust_value) |
599 |
), |
|
600 | ! |
text = substitute(ggplot2::element_text(size = font_size), list(font_size = font_size)) |
601 |
) |
|
602 |
) |
|
603 | ||
604 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
605 | ! |
teal.widgets::resolve_ggplot2_args( |
606 | ! |
user_plot = ggplot2_args[["Elbow plot"]], |
607 | ! |
user_default = ggplot2_args$default, |
608 | ! |
module_plot = dev_ggplot2_args |
609 |
), |
|
610 | ! |
ggtheme = ggtheme |
611 |
) |
|
612 | ! |
teal.reporter::teal_card(base_q) <- c(teal.reporter::teal_card(base_q), "## Elbow plot") |
613 | ! |
teal.code::eval_code( |
614 | ! |
base_q, |
615 | ! |
substitute( |
616 | ! |
expr = { |
617 | ! |
elb_dat <- pca$importance[c("Proportion of Variance", "Cumulative Proportion"), ] %>% |
618 | ! |
dplyr::as_tibble(rownames = "metric") %>% |
619 | ! |
tidyr::gather("component", "value", -metric) %>% |
620 | ! |
dplyr::mutate( |
621 | ! |
component = factor(component, levels = unique(stringr::str_sort(component, numeric = TRUE))) |
622 |
) |
|
623 | ||
624 | ! |
cols <- c(getOption("ggplot2.discrete.colour"), c("lightblue", "darkred", "black"))[1:3] |
625 | ! |
elbow_plot <- ggplot2::ggplot(mapping = ggplot2::aes_string(x = "component", y = "value")) + |
626 | ! |
ggplot2::geom_bar( |
627 | ! |
ggplot2::aes(fill = "Single variance"), |
628 | ! |
data = dplyr::filter(elb_dat, metric == "Proportion of Variance"), |
629 | ! |
color = "black", |
630 | ! |
stat = "identity" |
631 |
) + |
|
632 | ! |
ggplot2::geom_point( |
633 | ! |
ggplot2::aes(color = "Cumulative variance"), |
634 | ! |
data = dplyr::filter(elb_dat, metric == "Cumulative Proportion") |
635 |
) + |
|
636 | ! |
ggplot2::geom_line( |
637 | ! |
ggplot2::aes(group = 1, color = "Cumulative variance"), |
638 | ! |
data = dplyr::filter(elb_dat, metric == "Cumulative Proportion") |
639 |
) + |
|
640 | ! |
labs + |
641 | ! |
ggplot2::scale_color_manual(values = c("Cumulative variance" = cols[2], "Single variance" = cols[3])) + |
642 | ! |
ggplot2::scale_fill_manual(values = c("Cumulative variance" = cols[2], "Single variance" = cols[1])) + |
643 | ! |
ggthemes + |
644 | ! |
themes |
645 |
}, |
|
646 | ! |
env = list( |
647 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
648 | ! |
labs = parsed_ggplot2_args$labs, |
649 | ! |
themes = parsed_ggplot2_args$theme |
650 |
) |
|
651 |
) |
|
652 |
) |
|
653 |
} |
|
654 | ||
655 |
# plot circle ---- |
|
656 | ! |
plot_circle <- function(base_q) { |
657 | ! |
x_axis <- input$x_axis |
658 | ! |
y_axis <- input$y_axis |
659 | ! |
variables <- input$variables |
660 | ! |
ggtheme <- input$ggtheme |
661 | ||
662 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
663 | ! |
font_size <- input$font_size |
664 | ||
665 | ! |
angle <- ifelse(isTRUE(rotate_xaxis_labels), 45, 0) |
666 | ! |
hjust <- ifelse(isTRUE(rotate_xaxis_labels), 1, 0.5) |
667 | ||
668 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
669 | ! |
theme = list( |
670 | ! |
text = substitute(ggplot2::element_text(size = font_size), list(font_size = font_size)), |
671 | ! |
axis.text.x = substitute( |
672 | ! |
ggplot2::element_text(angle = angle_val, hjust = hjust_val), |
673 | ! |
list(angle_val = angle, hjust_val = hjust) |
674 |
) |
|
675 |
) |
|
676 |
) |
|
677 | ||
678 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
679 | ! |
user_plot = ggplot2_args[["Circle plot"]], |
680 | ! |
user_default = ggplot2_args$default, |
681 | ! |
module_plot = dev_ggplot2_args |
682 |
) |
|
683 | ||
684 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
685 | ! |
all_ggplot2_args, |
686 | ! |
ggtheme = ggtheme |
687 |
) |
|
688 | ||
689 | ! |
teal.reporter::teal_card(base_q) <- c(teal.reporter::teal_card(base_q), "## Circle plot") |
690 | ! |
teal.code::eval_code( |
691 | ! |
base_q, |
692 | ! |
substitute( |
693 | ! |
expr = { |
694 | ! |
pca_rot <- pca$rotation[, c(x_axis, y_axis)] %>% |
695 | ! |
dplyr::as_tibble(rownames = "label") %>% |
696 | ! |
dplyr::filter(label %in% variables) |
697 | ||
698 | ! |
circle_data <- data.frame( |
699 | ! |
x = cos(seq(0, 2 * pi, length.out = 100)), |
700 | ! |
y = sin(seq(0, 2 * pi, length.out = 100)) |
701 |
) |
|
702 | ||
703 | ! |
circle_plot <- ggplot2::ggplot(pca_rot) + |
704 | ! |
ggplot2::geom_point(ggplot2::aes_string(x = x_axis, y = y_axis)) + |
705 | ! |
ggplot2::geom_label( |
706 | ! |
ggplot2::aes_string(x = x_axis, y = y_axis, label = "label"), |
707 | ! |
nudge_x = 0.1, nudge_y = 0.05, |
708 | ! |
fontface = "bold" |
709 |
) + |
|
710 | ! |
ggplot2::geom_path(ggplot2::aes(x, y, group = 1), data = circle_data) + |
711 | ! |
ggplot2::geom_point(ggplot2::aes(x = x, y = y), data = data.frame(x = 0, y = 0), shape = "x", size = 5) + |
712 | ! |
labs + |
713 | ! |
ggthemes + |
714 | ! |
themes |
715 |
}, |
|
716 | ! |
env = list( |
717 | ! |
x_axis = x_axis, |
718 | ! |
y_axis = y_axis, |
719 | ! |
variables = variables, |
720 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
721 | ! |
labs = `if`(is.null(parsed_ggplot2_args$labs), quote(labs()), parsed_ggplot2_args$labs), |
722 | ! |
themes = parsed_ggplot2_args$theme |
723 |
) |
|
724 |
) |
|
725 |
) |
|
726 |
} |
|
727 | ||
728 |
# plot biplot ---- |
|
729 | ! |
plot_biplot <- function(base_q) { |
730 | ! |
qenv <- base_q |
731 | ||
732 | ! |
ANL <- qenv[["ANL"]] |
733 | ||
734 | ! |
resp_col <- as.character(merged$anl_input_r()$columns_source$response) |
735 | ! |
dat_cols <- as.character(merged$anl_input_r()$columns_source$dat) |
736 | ! |
x_axis <- input$x_axis |
737 | ! |
y_axis <- input$y_axis |
738 | ! |
variables <- input$variables |
739 | ! |
pca <- qenv[["pca"]] |
740 | ||
741 | ! |
ggtheme <- input$ggtheme |
742 | ||
743 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
744 | ! |
alpha <- input$alpha |
745 | ! |
size <- input$size |
746 | ! |
font_size <- input$font_size |
747 | ||
748 | ! |
teal.reporter::teal_card(base_q) <- c(teal.reporter::teal_card(base_q), "## Biplot") |
749 | ! |
qenv <- teal.code::eval_code( |
750 | ! |
qenv, |
751 | ! |
substitute( |
752 | ! |
expr = pca_rot <- dplyr::as_tibble(pca$x[, c(x_axis, y_axis)]), |
753 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
754 |
) |
|
755 |
) |
|
756 | ||
757 |
# rot_vars = data frame that displays arrows in the plot, need to be scaled to data |
|
758 | ! |
if (!is.null(input$variables)) { |
759 | ! |
qenv <- teal.code::eval_code( |
760 | ! |
qenv, |
761 | ! |
substitute( |
762 | ! |
expr = { |
763 | ! |
r <- sqrt(qchisq(0.69, df = 2)) * prod(colMeans(pca_rot ^ 2)) ^ (1 / 4) # styler: off |
764 | ! |
v_scale <- rowSums(pca$rotation ^ 2) # styler: off |
765 | ||
766 | ! |
rot_vars <- pca$rotation[, c(x_axis, y_axis)] %>% |
767 | ! |
dplyr::as_tibble(rownames = "label") %>% |
768 | ! |
dplyr::mutate_at(vars(c(x_axis, y_axis)), function(x) r * x / sqrt(max(v_scale))) |
769 |
}, |
|
770 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
771 |
) |
|
772 |
) %>% |
|
773 | ! |
teal.code::eval_code( |
774 | ! |
if (is.logical(pca$center) && !pca$center) { |
775 | ! |
substitute( |
776 | ! |
expr = { |
777 | ! |
rot_vars <- rot_vars %>% |
778 | ! |
tibble::column_to_rownames("label") %>% |
779 | ! |
sweep(1, apply(ANL[keep_columns], 2, mean, na.rm = TRUE)) %>% |
780 | ! |
tibble::rownames_to_column("label") %>% |
781 | ! |
dplyr::mutate( |
782 | ! |
xstart = mean(pca$x[, x_axis], na.rm = TRUE), |
783 | ! |
ystart = mean(pca$x[, y_axis], na.rm = TRUE) |
784 |
) |
|
785 |
}, |
|
786 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
787 |
) |
|
788 |
} else { |
|
789 | ! |
quote(rot_vars <- rot_vars %>% dplyr::mutate(xstart = 0, ystart = 0)) |
790 |
} |
|
791 |
) %>% |
|
792 | ! |
teal.code::eval_code( |
793 | ! |
substitute( |
794 | ! |
expr = rot_vars <- rot_vars %>% dplyr::filter(label %in% variables), |
795 | ! |
env = list(variables = variables) |
796 |
) |
|
797 |
) |
|
798 |
} |
|
799 | ||
800 | ! |
pca_plot_biplot_expr <- list(quote(ggplot())) |
801 | ||
802 | ! |
if (length(resp_col) == 0) { |
803 | ! |
pca_plot_biplot_expr <- c( |
804 | ! |
pca_plot_biplot_expr, |
805 | ! |
substitute( |
806 | ! |
ggplot2::geom_point(ggplot2::aes_string(x = x_axis, y = y_axis), |
807 | ! |
data = pca_rot, alpha = alpha, size = size |
808 |
), |
|
809 | ! |
list(x_axis = input$x_axis, y_axis = input$y_axis, alpha = input$alpha, size = input$size) |
810 |
) |
|
811 |
) |
|
812 | ! |
dev_labs <- list() |
813 |
} else { |
|
814 | ! |
rp_keys <- setdiff(colnames(ANL), as.character(unlist(merged$anl_input_r()$columns_source))) |
815 | ||
816 | ! |
response <- ANL[[resp_col]] |
817 | ||
818 | ! |
aes_biplot <- substitute( |
819 | ! |
ggplot2::aes_string(x = x_axis, y = y_axis, color = "response"), |
820 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
821 |
) |
|
822 | ||
823 | ! |
qenv <- teal.code::eval_code( |
824 | ! |
qenv, |
825 | ! |
substitute(response <- ANL[[resp_col]], env = list(resp_col = resp_col)) |
826 |
) |
|
827 | ||
828 | ! |
dev_labs <- list(color = varname_w_label(resp_col, ANL)) |
829 | ||
830 | ! |
scales_biplot <- |
831 | ! |
if ( |
832 | ! |
is.character(response) || |
833 | ! |
is.factor(response) || |
834 | ! |
(is.numeric(response) && length(unique(response)) <= 6) |
835 |
) { |
|
836 | ! |
qenv <- teal.code::eval_code( |
837 | ! |
qenv, |
838 | ! |
quote(pca_rot$response <- as.factor(response)) |
839 |
) |
|
840 | ! |
quote(ggplot2::scale_color_brewer(palette = "Dark2")) |
841 | ! |
} else if (inherits(response, "Date")) { |
842 | ! |
qenv <- teal.code::eval_code( |
843 | ! |
qenv, |
844 | ! |
quote(pca_rot$response <- numeric(response)) |
845 |
) |
|
846 | ||
847 | ! |
quote( |
848 | ! |
ggplot2::scale_color_gradient( |
849 | ! |
low = c(getOption("ggplot2.discrete.colour")[2], "darkred")[1], |
850 | ! |
high = c(getOption("ggplot2.discrete.colour"), "lightblue")[1], |
851 | ! |
labels = function(x) as.Date(x, origin = "1970-01-01") |
852 |
) |
|
853 |
) |
|
854 |
} else { |
|
855 | ! |
qenv <- teal.code::eval_code( |
856 | ! |
qenv, |
857 | ! |
quote(pca_rot$response <- response) |
858 |
) |
|
859 | ! |
quote(ggplot2::scale_color_gradient( |
860 | ! |
low = c(getOption("ggplot2.discrete.colour")[2], "darkred")[1], |
861 | ! |
high = c(getOption("ggplot2.discrete.colour"), "lightblue")[1] |
862 |
)) |
|
863 |
} |
|
864 | ||
865 | ! |
pca_plot_biplot_expr <- c( |
866 | ! |
pca_plot_biplot_expr, |
867 | ! |
substitute( |
868 | ! |
ggplot2::geom_point(aes_biplot, data = pca_rot, alpha = alpha, size = size), |
869 | ! |
env = list(aes_biplot = aes_biplot, alpha = alpha, size = size) |
870 |
), |
|
871 | ! |
scales_biplot |
872 |
) |
|
873 |
} |
|
874 | ||
875 | ! |
if (!is.null(input$variables)) { |
876 | ! |
pca_plot_biplot_expr <- c( |
877 | ! |
pca_plot_biplot_expr, |
878 | ! |
substitute( |
879 | ! |
ggplot2::geom_segment( |
880 | ! |
ggplot2::aes_string(x = "xstart", y = "ystart", xend = x_axis, yend = y_axis), |
881 | ! |
data = rot_vars, |
882 | ! |
lineend = "round", linejoin = "round", |
883 | ! |
arrow = grid::arrow(length = grid::unit(0.5, "cm")) |
884 |
), |
|
885 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
886 |
), |
|
887 | ! |
substitute( |
888 | ! |
ggplot2::geom_label( |
889 | ! |
ggplot2::aes_string( |
890 | ! |
x = x_axis, |
891 | ! |
y = y_axis, |
892 | ! |
label = "label" |
893 |
), |
|
894 | ! |
data = rot_vars, |
895 | ! |
nudge_y = 0.1, |
896 | ! |
fontface = "bold" |
897 |
), |
|
898 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
899 |
), |
|
900 | ! |
quote(ggplot2::geom_point(ggplot2::aes(x = xstart, y = ystart), data = rot_vars, shape = "x", size = 5)) |
901 |
) |
|
902 |
} |
|
903 | ||
904 | ! |
angle <- ifelse(isTRUE(rotate_xaxis_labels), 45, 0) |
905 | ! |
hjust <- ifelse(isTRUE(rotate_xaxis_labels), 1, 0.5) |
906 | ||
907 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
908 | ! |
labs = dev_labs, |
909 | ! |
theme = list( |
910 | ! |
text = substitute(ggplot2::element_text(size = font_size), list(font_size = font_size)), |
911 | ! |
axis.text.x = substitute( |
912 | ! |
ggplot2::element_text(angle = angle_val, hjust = hjust_val), |
913 | ! |
list(angle_val = angle, hjust_val = hjust) |
914 |
) |
|
915 |
) |
|
916 |
) |
|
917 | ||
918 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
919 | ! |
user_plot = ggplot2_args[["Biplot"]], |
920 | ! |
user_default = ggplot2_args$default, |
921 | ! |
module_plot = dev_ggplot2_args |
922 |
) |
|
923 | ||
924 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
925 | ! |
all_ggplot2_args, |
926 | ! |
ggtheme = ggtheme |
927 |
) |
|
928 | ||
929 | ! |
pca_plot_biplot_expr <- c( |
930 | ! |
pca_plot_biplot_expr, |
931 | ! |
parsed_ggplot2_args |
932 |
) |
|
933 | ||
934 | ! |
teal.code::eval_code( |
935 | ! |
qenv, |
936 | ! |
substitute( |
937 | ! |
expr = { |
938 | ! |
biplot <- plot_call |
939 |
}, |
|
940 | ! |
env = list( |
941 | ! |
plot_call = Reduce(function(x, y) call("+", x, y), pca_plot_biplot_expr) |
942 |
) |
|
943 |
) |
|
944 |
) |
|
945 |
} |
|
946 | ||
947 |
# plot eigenvector_plot ---- |
|
948 | ! |
plot_eigenvector <- function(base_q) { |
949 | ! |
req(input$pc) |
950 | ! |
pc <- input$pc |
951 | ! |
ggtheme <- input$ggtheme |
952 | ||
953 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
954 | ! |
font_size <- input$font_size |
955 | ||
956 | ! |
angle <- ifelse(rotate_xaxis_labels, 45, 0) |
957 | ! |
hjust <- ifelse(rotate_xaxis_labels, 1, 0.5) |
958 | ||
959 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
960 | ! |
theme = list( |
961 | ! |
text = substitute(ggplot2::element_text(size = font_size), list(font_size = font_size)), |
962 | ! |
axis.text.x = substitute( |
963 | ! |
ggplot2::element_text(angle = angle_val, hjust = hjust_val), |
964 | ! |
list(angle_val = angle, hjust_val = hjust) |
965 |
) |
|
966 |
) |
|
967 |
) |
|
968 | ||
969 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
970 | ! |
user_plot = ggplot2_args[["Eigenvector plot"]], |
971 | ! |
user_default = ggplot2_args$default, |
972 | ! |
module_plot = dev_ggplot2_args |
973 |
) |
|
974 | ||
975 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
976 | ! |
all_ggplot2_args, |
977 | ! |
ggtheme = ggtheme |
978 |
) |
|
979 | ||
980 | ! |
ggplot_exprs <- c( |
981 | ! |
list( |
982 | ! |
quote(ggplot(pca_rot)), |
983 | ! |
substitute( |
984 | ! |
ggplot2::geom_bar( |
985 | ! |
ggplot2::aes_string(x = "Variable", y = pc), |
986 | ! |
stat = "identity", |
987 | ! |
color = "black", |
988 | ! |
fill = c(getOption("ggplot2.discrete.colour"), "lightblue")[1] |
989 |
), |
|
990 | ! |
env = list(pc = pc) |
991 |
), |
|
992 | ! |
substitute( |
993 | ! |
ggplot2::geom_text( |
994 | ! |
ggplot2::aes( |
995 | ! |
x = Variable, |
996 | ! |
y = pc_name, |
997 | ! |
label = round(pc_name, 3), |
998 | ! |
vjust = ifelse(pc_name > 0, -0.5, 1.3) |
999 |
) |
|
1000 |
), |
|
1001 | ! |
env = list(pc_name = as.name(pc)) |
1002 |
) |
|
1003 |
), |
|
1004 | ! |
parsed_ggplot2_args$labs, |
1005 | ! |
parsed_ggplot2_args$ggtheme, |
1006 | ! |
parsed_ggplot2_args$theme |
1007 |
) |
|
1008 | ||
1009 | ! |
teal.reporter::teal_card(base_q) <- c(teal.reporter::teal_card(base_q), "## Eigenvector plot") |
1010 | ! |
teal.code::eval_code( |
1011 | ! |
base_q, |
1012 | ! |
substitute( |
1013 | ! |
expr = { |
1014 | ! |
pca_rot <- pca$rotation[, pc, drop = FALSE] %>% |
1015 | ! |
dplyr::as_tibble(rownames = "Variable") |
1016 | ! |
eigenvector_plot <- plot_call |
1017 |
}, |
|
1018 | ! |
env = list( |
1019 | ! |
pc = pc, |
1020 | ! |
plot_call = Reduce(function(x, y) call("+", x, y), ggplot_exprs) |
1021 |
) |
|
1022 |
) |
|
1023 |
) |
|
1024 |
} |
|
1025 | ||
1026 |
# qenvs --- |
|
1027 | ! |
output_q <- lapply( |
1028 | ! |
list( |
1029 | ! |
elbow_plot = plot_elbow, |
1030 | ! |
circle_plot = plot_circle, |
1031 | ! |
biplot = plot_biplot, |
1032 | ! |
eigenvector_plot = plot_eigenvector |
1033 |
), |
|
1034 | ! |
function(fun) { |
1035 | ! |
reactive({ |
1036 | ! |
req(computation()) |
1037 | ! |
teal::validate_inputs(iv_r()) |
1038 | ! |
teal::validate_inputs(iv_extra, header = "Plot settings are required") |
1039 | ! |
fun(computation()) |
1040 |
}) |
|
1041 |
} |
|
1042 |
) |
|
1043 | ||
1044 | ! |
decorated_q <- mapply( |
1045 | ! |
function(obj_name, q) { |
1046 | ! |
srv_decorate_teal_data( |
1047 | ! |
id = sprintf("d_%s", obj_name), |
1048 | ! |
data = q, |
1049 | ! |
decorators = select_decorators(decorators, obj_name), |
1050 | ! |
expr = reactive({ |
1051 | ! |
substitute(.plot, env = list(.plot = as.name(obj_name))) |
1052 |
}) |
|
1053 |
) |
|
1054 |
}, |
|
1055 | ! |
names(output_q), |
1056 | ! |
output_q |
1057 |
) |
|
1058 | ||
1059 |
# plot final ---- |
|
1060 | ! |
decorated_output_q <- reactive({ |
1061 | ! |
switch(req(input$plot_type), |
1062 | ! |
"Elbow plot" = decorated_q$elbow_plot(), |
1063 | ! |
"Circle plot" = decorated_q$circle_plot(), |
1064 | ! |
"Biplot" = decorated_q$biplot(), |
1065 | ! |
"Eigenvector plot" = decorated_q$eigenvector_plot(), |
1066 | ! |
stop("Unknown plot") |
1067 |
) |
|
1068 |
}) |
|
1069 | ||
1070 | ! |
plot_r <- reactive({ |
1071 | ! |
plot_name <- gsub(" ", "_", tolower(req(input$plot_type))) |
1072 | ! |
req(decorated_output_q())[[plot_name]] |
1073 |
}) |
|
1074 | ||
1075 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
1076 | ! |
id = "pca_plot", |
1077 | ! |
plot_r = plot_r, |
1078 | ! |
height = plot_height, |
1079 | ! |
width = plot_width, |
1080 | ! |
graph_align = "center" |
1081 |
) |
|
1082 | ||
1083 | ! |
decorated_output_dims_q <- set_chunk_dims(pws, decorated_output_q) |
1084 | ||
1085 |
# tables ---- |
|
1086 | ! |
output$tbl_importance <- renderTable( |
1087 | ! |
expr = { |
1088 | ! |
req("importance" %in% input$tables_display, computation()) |
1089 | ! |
computation()[["tbl_importance"]] |
1090 |
}, |
|
1091 | ! |
bordered = TRUE, |
1092 | ! |
align = "c", |
1093 | ! |
digits = 3 |
1094 |
) |
|
1095 | ||
1096 | ! |
output$tbl_importance_ui <- renderUI({ |
1097 | ! |
req("importance" %in% input$tables_display) |
1098 | ! |
tags$div( |
1099 | ! |
align = "center", |
1100 | ! |
tags$h4("Principal components importance"), |
1101 | ! |
tableOutput(session$ns("tbl_importance")), |
1102 | ! |
tags$hr() |
1103 |
) |
|
1104 |
}) |
|
1105 | ||
1106 | ! |
output$tbl_eigenvector <- renderTable( |
1107 | ! |
expr = { |
1108 | ! |
req("eigenvector" %in% input$tables_display, req(computation())) |
1109 | ! |
computation()[["tbl_eigenvector"]] |
1110 |
}, |
|
1111 | ! |
bordered = TRUE, |
1112 | ! |
align = "c", |
1113 | ! |
digits = 3 |
1114 |
) |
|
1115 | ||
1116 | ! |
output$tbl_eigenvector_ui <- renderUI({ |
1117 | ! |
req("eigenvector" %in% input$tables_display) |
1118 | ! |
tags$div( |
1119 | ! |
align = "center", |
1120 | ! |
tags$h4("Eigenvectors"), |
1121 | ! |
tableOutput(session$ns("tbl_eigenvector")), |
1122 | ! |
tags$hr() |
1123 |
) |
|
1124 |
}) |
|
1125 | ||
1126 | ! |
output$all_plots <- renderUI({ |
1127 | ! |
teal::validate_inputs(iv_r()) |
1128 | ! |
teal::validate_inputs(iv_extra, header = "Plot settings are required") |
1129 | ||
1130 | ! |
validation() |
1131 | ! |
tags$div( |
1132 | ! |
uiOutput(session$ns("tbl_importance_ui")), |
1133 | ! |
uiOutput(session$ns("tbl_eigenvector_ui")), |
1134 | ! |
teal.widgets::plot_with_settings_ui(id = session$ns("pca_plot")) |
1135 |
) |
|
1136 |
}) |
|
1137 | ||
1138 |
# Render R code. |
|
1139 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_output_q()))) |
1140 | ||
1141 | ! |
teal.widgets::verbatim_popup_srv( |
1142 | ! |
id = "rcode", |
1143 | ! |
verbatim_content = source_code_r, |
1144 | ! |
title = "R Code for PCA" |
1145 |
) |
|
1146 | ! |
decorated_output_dims_q |
1147 |
}) |
|
1148 |
} |
1 |
#' `teal` module: Distribution analysis |
|
2 |
#' |
|
3 |
#' Module is designed to explore the distribution of a single variable within a given dataset. |
|
4 |
#' It offers several tools, such as histograms, Q-Q plots, and various statistical tests to |
|
5 |
#' visually and statistically analyze the variable's distribution. |
|
6 |
#' |
|
7 |
#' @inheritParams teal::module |
|
8 |
#' @inheritParams teal.widgets::standard_layout |
|
9 |
#' @inheritParams shared_params |
|
10 |
#' |
|
11 |
#' @param dist_var (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
12 |
#' Variable(s) for which the distribution will be analyzed. |
|
13 |
#' @param strata_var (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
14 |
#' Categorical variable used to split the distribution analysis. |
|
15 |
#' @param group_var (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
16 |
#' Variable used for faceting plot into multiple panels. |
|
17 |
#' @param freq (`logical`) optional, whether to display frequency (`TRUE`) or density (`FALSE`). |
|
18 |
#' Defaults to density (`FALSE`). |
|
19 |
#' @param bins (`integer(1)` or `integer(3)`) optional, specifies the number of bins for the histogram. |
|
20 |
#' - When the length of `bins` is one: The histogram bins will have a fixed size based on the `bins` provided. |
|
21 |
#' - When the length of `bins` is three: The histogram bins are dynamically adjusted based on vector of `value`, `min`, |
|
22 |
#' and `max`. |
|
23 |
#' Defaults to `c(30L, 1L, 100L)`. |
|
24 |
#' |
|
25 |
#' @param ggplot2_args `r roxygen_ggplot2_args_param("Histogram", "QQplot")` |
|
26 |
#' |
|
27 |
#' @inherit shared_params return |
|
28 |
#' |
|
29 |
#' @section Decorating Module: |
|
30 |
#' |
|
31 |
#' This module generates the following objects, which can be modified in place using decorators:: |
|
32 |
#' - `histogram_plot` (`ggplot`) |
|
33 |
#' - `qq_plot` (`ggplot`) |
|
34 |
#' |
|
35 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
36 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
37 |
#' See code snippet below: |
|
38 |
#' |
|
39 |
#' ``` |
|
40 |
#' tm_g_distribution( |
|
41 |
#' ..., # arguments for module |
|
42 |
#' decorators = list( |
|
43 |
#' histogram_plot = teal_transform_module(...), # applied only to `histogram_plot` output |
|
44 |
#' qq_plot = teal_transform_module(...) # applied only to `qq_plot` output |
|
45 |
#' ) |
|
46 |
#' ) |
|
47 |
#' ``` |
|
48 |
#' |
|
49 |
#' For additional details and examples of decorators, refer to the vignette |
|
50 |
#' `vignette("decorate-module-output", package = "teal.modules.general")`. |
|
51 |
#' |
|
52 |
#' To learn more please refer to the vignette |
|
53 |
#' `vignette("transform-module-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
54 |
#' |
|
55 |
#' @inheritSection teal::example_module Reporting |
|
56 |
#' |
|
57 |
#' @examplesShinylive |
|
58 |
#' library(teal.modules.general) |
|
59 |
#' interactive <- function() TRUE |
|
60 |
#' {{ next_example }} |
|
61 |
# nolint start: line_length_linter. |
|
62 |
#' @examples |
|
63 |
# nolint end: line_length_linter. |
|
64 |
#' # general data example |
|
65 |
#' data <- teal_data() |
|
66 |
#' data <- within(data, { |
|
67 |
#' iris <- iris |
|
68 |
#' }) |
|
69 |
#' |
|
70 |
#' app <- init( |
|
71 |
#' data = data, |
|
72 |
#' modules = list( |
|
73 |
#' tm_g_distribution( |
|
74 |
#' dist_var = data_extract_spec( |
|
75 |
#' dataname = "iris", |
|
76 |
#' select = select_spec(variable_choices("iris"), "Petal.Length") |
|
77 |
#' ) |
|
78 |
#' ) |
|
79 |
#' ) |
|
80 |
#' ) |
|
81 |
#' if (interactive()) { |
|
82 |
#' shinyApp(app$ui, app$server) |
|
83 |
#' } |
|
84 |
#' |
|
85 |
#' @examplesShinylive |
|
86 |
#' library(teal.modules.general) |
|
87 |
#' interactive <- function() TRUE |
|
88 |
#' {{ next_example }} |
|
89 |
# nolint start: line_length_linter. |
|
90 |
#' @examples |
|
91 |
# nolint end: line_length_linter. |
|
92 |
#' # CDISC data example |
|
93 |
#' data <- teal_data() |
|
94 |
#' data <- within(data, { |
|
95 |
#' ADSL <- teal.data::rADSL |
|
96 |
#' }) |
|
97 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
98 |
#' |
|
99 |
#' vars1 <- choices_selected( |
|
100 |
#' variable_choices(data[["ADSL"]], c("ARM", "COUNTRY", "SEX")), |
|
101 |
#' selected = NULL |
|
102 |
#' ) |
|
103 |
#' |
|
104 |
#' app <- init( |
|
105 |
#' data = data, |
|
106 |
#' modules = modules( |
|
107 |
#' tm_g_distribution( |
|
108 |
#' dist_var = data_extract_spec( |
|
109 |
#' dataname = "ADSL", |
|
110 |
#' select = select_spec( |
|
111 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1")), |
|
112 |
#' selected = "BMRKR1", |
|
113 |
#' multiple = FALSE, |
|
114 |
#' fixed = FALSE |
|
115 |
#' ) |
|
116 |
#' ), |
|
117 |
#' strata_var = data_extract_spec( |
|
118 |
#' dataname = "ADSL", |
|
119 |
#' filter = filter_spec( |
|
120 |
#' vars = vars1, |
|
121 |
#' multiple = TRUE |
|
122 |
#' ) |
|
123 |
#' ), |
|
124 |
#' group_var = data_extract_spec( |
|
125 |
#' dataname = "ADSL", |
|
126 |
#' filter = filter_spec( |
|
127 |
#' vars = vars1, |
|
128 |
#' multiple = TRUE |
|
129 |
#' ) |
|
130 |
#' ) |
|
131 |
#' ) |
|
132 |
#' ) |
|
133 |
#' ) |
|
134 |
#' if (interactive()) { |
|
135 |
#' shinyApp(app$ui, app$server) |
|
136 |
#' } |
|
137 |
#' |
|
138 |
#' @export |
|
139 |
#' |
|
140 |
tm_g_distribution <- function(label = "Distribution Module", |
|
141 |
dist_var, |
|
142 |
strata_var = NULL, |
|
143 |
group_var = NULL, |
|
144 |
freq = FALSE, |
|
145 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
146 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
147 |
bins = c(30L, 1L, 100L), |
|
148 |
plot_height = c(600, 200, 2000), |
|
149 |
plot_width = NULL, |
|
150 |
pre_output = NULL, |
|
151 |
post_output = NULL, |
|
152 |
transformators = list(), |
|
153 |
decorators = list()) { |
|
154 | ! |
message("Initializing tm_g_distribution") |
155 | ||
156 |
# Normalize the parameters |
|
157 | ! |
if (inherits(dist_var, "data_extract_spec")) dist_var <- list(dist_var) |
158 | ! |
if (inherits(strata_var, "data_extract_spec")) strata_var <- list(strata_var) |
159 | ! |
if (inherits(group_var, "data_extract_spec")) group_var <- list(group_var) |
160 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
161 | ||
162 |
# Start of assertions |
|
163 | ! |
checkmate::assert_string(label) |
164 | ||
165 | ! |
checkmate::assert_list(dist_var, "data_extract_spec") |
166 | ! |
checkmate::assert_false(dist_var[[1L]]$select$multiple) |
167 | ||
168 | ! |
checkmate::assert_list(strata_var, types = "data_extract_spec", null.ok = TRUE) |
169 | ! |
checkmate::assert_list(group_var, types = "data_extract_spec", null.ok = TRUE) |
170 | ! |
checkmate::assert_flag(freq) |
171 | ! |
ggtheme <- match.arg(ggtheme) |
172 | ||
173 | ! |
plot_choices <- c("Histogram", "QQplot") |
174 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
175 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
176 | ||
177 | ! |
if (length(bins) == 1) { |
178 | ! |
checkmate::assert_numeric(bins, any.missing = FALSE, lower = 1) |
179 |
} else { |
|
180 | ! |
checkmate::assert_numeric(bins, len = 3, any.missing = FALSE, lower = 1) |
181 | ! |
checkmate::assert_numeric(bins[1], lower = bins[2], upper = bins[3], .var.name = "bins") |
182 |
} |
|
183 | ||
184 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
185 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
186 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
187 | ! |
checkmate::assert_numeric( |
188 | ! |
plot_width[1], |
189 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
190 |
) |
|
191 | ||
192 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
193 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
194 | ||
195 | ! |
assert_decorators(decorators, names = c("histogram_plot", "qq_plot")) |
196 | ||
197 |
# End of assertions |
|
198 | ||
199 |
# Make UI args |
|
200 | ! |
args <- as.list(environment()) |
201 | ||
202 | ! |
data_extract_list <- list( |
203 | ! |
dist_var = dist_var, |
204 | ! |
strata_var = strata_var, |
205 | ! |
group_var = group_var |
206 |
) |
|
207 | ||
208 | ! |
ans <- module( |
209 | ! |
label = label, |
210 | ! |
server = srv_distribution, |
211 | ! |
server_args = c( |
212 | ! |
data_extract_list, |
213 | ! |
list( |
214 | ! |
plot_height = plot_height, |
215 | ! |
plot_width = plot_width, |
216 | ! |
ggplot2_args = ggplot2_args, |
217 | ! |
decorators = decorators |
218 |
) |
|
219 |
), |
|
220 | ! |
ui = ui_distribution, |
221 | ! |
ui_args = args, |
222 | ! |
transformators = transformators, |
223 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
224 |
) |
|
225 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
226 | ! |
ans |
227 |
} |
|
228 | ||
229 |
# UI function for the distribution module |
|
230 |
ui_distribution <- function(id, ...) { |
|
231 | ! |
args <- list(...) |
232 | ! |
ns <- NS(id) |
233 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$dist_var, args$strata_var, args$group_var) |
234 | ||
235 | ! |
teal.widgets::standard_layout( |
236 | ! |
output = teal.widgets::white_small_well( |
237 | ! |
tabsetPanel( |
238 | ! |
id = ns("tabs"), |
239 | ! |
tabPanel("Histogram", teal.widgets::plot_with_settings_ui(id = ns("hist_plot"))), |
240 | ! |
tabPanel("QQplot", teal.widgets::plot_with_settings_ui(id = ns("qq_plot"))) |
241 |
), |
|
242 | ! |
tags$h3("Statistics Table"), |
243 | ! |
DT::dataTableOutput(ns("summary_table")), |
244 | ! |
tags$h3("Tests"), |
245 | ! |
conditionalPanel( |
246 | ! |
sprintf("input['%s'].length === 0", ns("dist_tests")), |
247 | ! |
div( |
248 | ! |
id = ns("please_select_a_test"), |
249 | ! |
"Please select a test" |
250 |
) |
|
251 |
), |
|
252 | ! |
conditionalPanel( |
253 | ! |
sprintf("input['%s'].length > 0", ns("dist_tests")), |
254 | ! |
DT::dataTableOutput(ns("t_stats")) |
255 |
) |
|
256 |
), |
|
257 | ! |
encoding = tags$div( |
258 | ! |
tags$label("Encodings", class = "text-primary"), |
259 | ! |
teal.transform::datanames_input(args[c("dist_var", "strata_var")]), |
260 | ! |
teal.transform::data_extract_ui( |
261 | ! |
id = ns("dist_i"), |
262 | ! |
label = "Variable", |
263 | ! |
data_extract_spec = args$dist_var, |
264 | ! |
is_single_dataset = is_single_dataset_value |
265 |
), |
|
266 | ! |
if (!is.null(args$group_var)) { |
267 | ! |
tagList( |
268 | ! |
teal.transform::data_extract_ui( |
269 | ! |
id = ns("group_i"), |
270 | ! |
label = "Group by", |
271 | ! |
data_extract_spec = args$group_var, |
272 | ! |
is_single_dataset = is_single_dataset_value |
273 |
), |
|
274 | ! |
uiOutput(ns("scales_types_ui")) |
275 |
) |
|
276 |
}, |
|
277 | ! |
if (!is.null(args$strata_var)) { |
278 | ! |
teal.transform::data_extract_ui( |
279 | ! |
id = ns("strata_i"), |
280 | ! |
label = "Stratify by", |
281 | ! |
data_extract_spec = args$strata_var, |
282 | ! |
is_single_dataset = is_single_dataset_value |
283 |
) |
|
284 |
}, |
|
285 | ! |
bslib::accordion( |
286 | ! |
conditionalPanel( |
287 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'Histogram'"), |
288 | ! |
bslib::accordion_panel( |
289 | ! |
"Histogram", |
290 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("bins"), "Bins", args$bins, ticks = FALSE, step = 1), |
291 | ! |
shinyWidgets::prettyRadioButtons( |
292 | ! |
ns("main_type"), |
293 | ! |
label = "Plot Type:", |
294 | ! |
choices = c("Density", "Frequency"), |
295 | ! |
selected = if (!args$freq) "Density" else "Frequency", |
296 | ! |
bigger = FALSE, |
297 | ! |
inline = TRUE |
298 |
), |
|
299 | ! |
checkboxInput(ns("add_dens"), label = "Overlay Density", value = TRUE), |
300 | ! |
ui_decorate_teal_data( |
301 | ! |
ns("d_density"), |
302 | ! |
decorators = select_decorators(args$decorators, "histogram_plot") |
303 |
) |
|
304 |
) |
|
305 |
), |
|
306 | ! |
conditionalPanel( |
307 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'QQplot'"), |
308 | ! |
bslib::accordion_panel( |
309 | ! |
"QQ Plot", |
310 | ! |
checkboxInput(ns("qq_line"), label = "Add diagonal line(s)", TRUE), |
311 | ! |
ui_decorate_teal_data( |
312 | ! |
ns("d_qq"), |
313 | ! |
decorators = select_decorators(args$decorators, "qq_plot") |
314 |
), |
|
315 | ! |
collapsed = FALSE |
316 |
) |
|
317 |
), |
|
318 | ! |
conditionalPanel( |
319 | ! |
condition = paste0("input['", ns("main_type"), "'] == 'Density'"), |
320 | ! |
bslib::accordion_panel( |
321 | ! |
"Theoretical Distribution", |
322 | ! |
teal.widgets::optionalSelectInput( |
323 | ! |
ns("t_dist"), |
324 | ! |
tags$div( |
325 | ! |
tagList( |
326 | ! |
"Distribution:", |
327 | ! |
bslib::tooltip( |
328 | ! |
icon("circle-info"), |
329 | ! |
tags$span( |
330 | ! |
"Default parameters are optimized with MASS::fitdistr function." |
331 |
) |
|
332 |
) |
|
333 |
) |
|
334 |
), |
|
335 | ! |
choices = c("normal", "lognormal", "gamma", "unif"), |
336 | ! |
selected = NULL, |
337 | ! |
multiple = FALSE |
338 |
), |
|
339 | ! |
numericInput(ns("dist_param1"), label = "param1", value = NULL), |
340 | ! |
numericInput(ns("dist_param2"), label = "param2", value = NULL), |
341 | ! |
tags$span(actionButton(ns("params_reset"), "Default params")), |
342 | ! |
collapsed = FALSE |
343 |
) |
|
344 |
), |
|
345 | ! |
bslib::accordion_panel( |
346 | ! |
title = "Tests", |
347 | ! |
teal.widgets::optionalSelectInput( |
348 | ! |
ns("dist_tests"), |
349 | ! |
"Tests:", |
350 | ! |
choices = c( |
351 | ! |
"Shapiro-Wilk", |
352 | ! |
if (!is.null(args$strata_var)) "t-test (two-samples, not paired)", |
353 | ! |
if (!is.null(args$strata_var)) "one-way ANOVA", |
354 | ! |
if (!is.null(args$strata_var)) "Fligner-Killeen", |
355 | ! |
if (!is.null(args$strata_var)) "F-test", |
356 | ! |
"Kolmogorov-Smirnov (one-sample)", |
357 | ! |
"Anderson-Darling (one-sample)", |
358 | ! |
"Cramer-von Mises (one-sample)", |
359 | ! |
if (!is.null(args$strata_var)) "Kolmogorov-Smirnov (two-samples)" |
360 |
), |
|
361 | ! |
selected = NULL |
362 |
) |
|
363 |
), |
|
364 | ! |
bslib::accordion_panel( |
365 | ! |
title = "Statistics Table", |
366 | ! |
sliderInput(ns("roundn"), "Round to n digits", min = 0, max = 10, value = 2) |
367 |
), |
|
368 | ! |
bslib::accordion_panel( |
369 | ! |
title = "Plot settings", |
370 | ! |
selectInput( |
371 | ! |
inputId = ns("ggtheme"), |
372 | ! |
label = "Theme (by ggplot):", |
373 | ! |
choices = ggplot_themes, |
374 | ! |
selected = args$ggtheme, |
375 | ! |
multiple = FALSE |
376 |
) |
|
377 |
) |
|
378 |
) |
|
379 |
), |
|
380 | ! |
forms = tagList( |
381 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
382 |
), |
|
383 | ! |
pre_output = args$pre_output, |
384 | ! |
post_output = args$post_output |
385 |
) |
|
386 |
} |
|
387 | ||
388 |
# Server function for the distribution module |
|
389 |
srv_distribution <- function(id, |
|
390 |
data, |
|
391 |
dist_var, |
|
392 |
strata_var, |
|
393 |
group_var, |
|
394 |
plot_height, |
|
395 |
plot_width, |
|
396 |
ggplot2_args, |
|
397 |
decorators) { |
|
398 | ! |
checkmate::assert_class(data, "reactive") |
399 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
400 | ! |
moduleServer(id, function(input, output, session) { |
401 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
402 | ||
403 | ! |
setBookmarkExclude("params_reset") |
404 | ||
405 | ! |
ns <- session$ns |
406 | ||
407 | ! |
rule_req <- function(value) { |
408 | ! |
if (isTRUE(input$dist_tests %in% c( |
409 | ! |
"Fligner-Killeen", |
410 | ! |
"t-test (two-samples, not paired)", |
411 | ! |
"F-test", |
412 | ! |
"Kolmogorov-Smirnov (two-samples)", |
413 | ! |
"one-way ANOVA" |
414 |
))) { |
|
415 | ! |
if (!shinyvalidate::input_provided(value)) { |
416 | ! |
"Please select stratify variable." |
417 |
} |
|
418 |
} |
|
419 |
} |
|
420 | ! |
rule_dupl <- function(...) { |
421 | ! |
if (identical(input$dist_tests, "Fligner-Killeen")) { |
422 | ! |
strata <- selector_list()$strata_i()$select |
423 | ! |
group <- selector_list()$group_i()$select |
424 | ! |
if (isTRUE(strata == group)) { |
425 | ! |
"Please select different variables for strata and group." |
426 |
} |
|
427 |
} |
|
428 |
} |
|
429 | ||
430 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
431 | ! |
data_extract = list( |
432 | ! |
dist_i = dist_var, |
433 | ! |
strata_i = strata_var, |
434 | ! |
group_i = group_var |
435 |
), |
|
436 | ! |
data, |
437 | ! |
select_validation_rule = list( |
438 | ! |
dist_i = shinyvalidate::sv_required("Please select a variable") |
439 |
), |
|
440 | ! |
filter_validation_rule = list( |
441 | ! |
strata_i = shinyvalidate::compose_rules( |
442 | ! |
rule_req, |
443 | ! |
rule_dupl |
444 |
), |
|
445 | ! |
group_i = rule_dupl |
446 |
) |
|
447 |
) |
|
448 | ||
449 | ! |
iv_r <- reactive({ |
450 | ! |
iv <- shinyvalidate::InputValidator$new() |
451 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list, validator_names = "dist_i") |
452 |
}) |
|
453 | ||
454 | ! |
iv_r_dist <- reactive({ |
455 | ! |
iv <- shinyvalidate::InputValidator$new() |
456 | ! |
teal.transform::compose_and_enable_validators( |
457 | ! |
iv, selector_list, |
458 | ! |
validator_names = c("strata_i", "group_i") |
459 |
) |
|
460 |
}) |
|
461 | ! |
rule_dist_1 <- function(value) { |
462 | ! |
if (!is.null(input$t_dist)) { |
463 | ! |
switch(input$t_dist, |
464 | ! |
"normal" = if (!shinyvalidate::input_provided(value)) "mean is required", |
465 | ! |
"lognormal" = if (!shinyvalidate::input_provided(value)) "meanlog is required", |
466 | ! |
"gamma" = { |
467 | ! |
if (!shinyvalidate::input_provided(value)) "shape is required" else if (value <= 0) "shape must be positive" |
468 |
}, |
|
469 | ! |
"unif" = NULL |
470 |
) |
|
471 |
} |
|
472 |
} |
|
473 | ! |
rule_dist_2 <- function(value) { |
474 | ! |
if (!is.null(input$t_dist)) { |
475 | ! |
switch(input$t_dist, |
476 | ! |
"normal" = { |
477 | ! |
if (!shinyvalidate::input_provided(value)) { |
478 | ! |
"sd is required" |
479 | ! |
} else if (value < 0) { |
480 | ! |
"sd must be non-negative" |
481 |
} |
|
482 |
}, |
|
483 | ! |
"lognormal" = { |
484 | ! |
if (!shinyvalidate::input_provided(value)) { |
485 | ! |
"sdlog is required" |
486 | ! |
} else if (value < 0) { |
487 | ! |
"sdlog must be non-negative" |
488 |
} |
|
489 |
}, |
|
490 | ! |
"gamma" = { |
491 | ! |
if (!shinyvalidate::input_provided(value)) { |
492 | ! |
"rate is required" |
493 | ! |
} else if (value <= 0) { |
494 | ! |
"rate must be positive" |
495 |
} |
|
496 |
}, |
|
497 | ! |
"unif" = NULL |
498 |
) |
|
499 |
} |
|
500 |
} |
|
501 | ||
502 | ! |
rule_dist <- function(value) { |
503 | ! |
if (isTRUE(input$tabs == "QQplot") || |
504 | ! |
isTRUE(input$dist_tests %in% c( |
505 | ! |
"Kolmogorov-Smirnov (one-sample)", |
506 | ! |
"Anderson-Darling (one-sample)", |
507 | ! |
"Cramer-von Mises (one-sample)" |
508 |
))) { |
|
509 | ! |
if (!shinyvalidate::input_provided(value)) { |
510 | ! |
"Please select the theoretical distribution." |
511 |
} |
|
512 |
} |
|
513 |
} |
|
514 | ||
515 | ! |
iv_dist <- shinyvalidate::InputValidator$new() |
516 | ! |
iv_dist$add_rule("t_dist", rule_dist) |
517 | ! |
iv_dist$add_rule("dist_param1", rule_dist_1) |
518 | ! |
iv_dist$add_rule("dist_param2", rule_dist_2) |
519 | ! |
iv_dist$enable() |
520 | ||
521 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
522 | ! |
selector_list = selector_list, |
523 | ! |
datasets = data |
524 |
) |
|
525 | ||
526 | ! |
qenv <- reactive( |
527 | ! |
teal.code::eval_code(data(), 'library("ggplot2");library("dplyr")') # nolint quotes |
528 |
) |
|
529 | ||
530 | ! |
anl_merged_q <- reactive({ |
531 | ! |
req(anl_merged_input()) |
532 | ! |
qenv() %>% |
533 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
534 |
}) |
|
535 | ||
536 | ! |
merged <- list( |
537 | ! |
anl_input_r = anl_merged_input, |
538 | ! |
anl_q_r = anl_merged_q |
539 |
) |
|
540 | ||
541 | ! |
output$scales_types_ui <- renderUI({ |
542 | ! |
if ("group_i" %in% names(selector_list()) && length(selector_list()$group_i()$filters[[1]]$selected) > 0) { |
543 | ! |
shinyWidgets::prettyRadioButtons( |
544 | ! |
ns("scales_type"), |
545 | ! |
label = "Scales:", |
546 | ! |
choices = c("Fixed", "Free"), |
547 | ! |
selected = "Fixed", |
548 | ! |
bigger = FALSE, |
549 | ! |
inline = TRUE |
550 |
) |
|
551 |
} |
|
552 |
}) |
|
553 | ||
554 | ! |
observeEvent( |
555 | ! |
eventExpr = list( |
556 | ! |
input$t_dist, |
557 | ! |
input$params_reset, |
558 | ! |
selector_list()$dist_i()$select |
559 |
), |
|
560 | ! |
handlerExpr = { |
561 | ! |
params <- |
562 | ! |
if (length(input$t_dist) != 0) { |
563 | ! |
get_dist_params <- function(x, dist) { |
564 | ! |
if (dist == "unif") { |
565 | ! |
return(stats::setNames(range(x, na.rm = TRUE), c("min", "max"))) |
566 |
} |
|
567 | ! |
tryCatch( |
568 | ! |
MASS::fitdistr(x, densfun = dist)$estimate, |
569 | ! |
error = function(e) c(param1 = NA_real_, param2 = NA_real_) |
570 |
) |
|
571 |
} |
|
572 | ||
573 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
574 | ! |
round(get_dist_params(as.numeric(stats::na.omit(ANL[[merge_vars()$dist_var]])), input$t_dist), 2) |
575 |
} else { |
|
576 | ! |
c("param1" = NA_real_, "param2" = NA_real_) |
577 |
} |
|
578 | ||
579 | ! |
params_vals <- unname(params) |
580 | ! |
map_distr_nams <- list( |
581 | ! |
normal = c("mean", "sd"), |
582 | ! |
lognormal = c("meanlog", "sdlog"), |
583 | ! |
gamma = c("shape", "rate"), |
584 | ! |
unif = c("min", "max") |
585 |
) |
|
586 | ||
587 | ! |
if (!is.null(input$t_dist) && input$t_dist %in% names(map_distr_nams)) { |
588 | ! |
params_names <- map_distr_nams[[input$t_dist]] |
589 |
} else { |
|
590 | ! |
params_names <- names(params) |
591 |
} |
|
592 | ||
593 | ! |
updateNumericInput( |
594 | ! |
inputId = "dist_param1", |
595 | ! |
label = params_names[1], |
596 | ! |
value = restoreInput(ns("dist_param1"), params_vals[1]) |
597 |
) |
|
598 | ! |
updateNumericInput( |
599 | ! |
inputId = "dist_param2", |
600 | ! |
label = params_names[2], |
601 | ! |
value = restoreInput(ns("dist_param1"), params_vals[2]) |
602 |
) |
|
603 |
}, |
|
604 | ! |
ignoreInit = TRUE |
605 |
) |
|
606 | ||
607 | ! |
observeEvent(input$params_reset, { |
608 | ! |
updateActionButton(inputId = "params_reset", label = "Reset params") |
609 |
}) |
|
610 | ||
611 | ! |
merge_vars <- reactive({ |
612 | ! |
teal::validate_inputs(iv_r()) |
613 | ||
614 | ! |
dist_var <- as.vector(merged$anl_input_r()$columns_source$dist_i) |
615 | ! |
s_var <- as.vector(merged$anl_input_r()$columns_source$strata_i) |
616 | ! |
g_var <- as.vector(merged$anl_input_r()$columns_source$group_i) |
617 | ||
618 | ! |
dist_var_name <- if (length(dist_var)) as.name(dist_var) else NULL |
619 | ! |
s_var_name <- if (length(s_var)) as.name(s_var) else NULL |
620 | ! |
g_var_name <- if (length(g_var)) as.name(g_var) else NULL |
621 | ||
622 | ! |
list( |
623 | ! |
dist_var = dist_var, |
624 | ! |
s_var = s_var, |
625 | ! |
g_var = g_var, |
626 | ! |
dist_var_name = dist_var_name, |
627 | ! |
s_var_name = s_var_name, |
628 | ! |
g_var_name = g_var_name |
629 |
) |
|
630 |
}) |
|
631 | ||
632 |
# common qenv |
|
633 | ! |
common_q <- reactive({ |
634 |
# Create a private stack for this function only. |
|
635 | ||
636 | ! |
obj <- merged$anl_q_r() |
637 | ! |
teal.reporter::teal_card(obj) <- |
638 | ! |
c( |
639 | ! |
teal.reporter::teal_card("# Distribution Plot"), |
640 | ! |
teal.reporter::teal_card(obj), |
641 | ! |
teal.reporter::teal_card("## Module's code") |
642 |
) |
|
643 | ||
644 | ! |
ANL <- obj[["ANL"]] |
645 | ! |
dist_var <- merge_vars()$dist_var |
646 | ! |
s_var <- merge_vars()$s_var |
647 | ! |
g_var <- merge_vars()$g_var |
648 | ||
649 | ! |
dist_var_name <- merge_vars()$dist_var_name |
650 | ! |
s_var_name <- merge_vars()$s_var_name |
651 | ! |
g_var_name <- merge_vars()$g_var_name |
652 | ||
653 | ! |
roundn <- input$roundn |
654 | ! |
dist_param1 <- input$dist_param1 |
655 | ! |
dist_param2 <- input$dist_param2 |
656 |
# isolated as dist_param1/dist_param2 already triggered the reactivity |
|
657 | ! |
t_dist <- isolate(input$t_dist) |
658 | ||
659 | ! |
qenv <- obj |
660 | ||
661 | ! |
if (length(g_var) > 0) { |
662 | ! |
validate( |
663 | ! |
need( |
664 | ! |
inherits(ANL[[g_var]], c("integer", "factor", "character")), |
665 | ! |
"Group by variable must be `factor`, `character`, or `integer`" |
666 |
) |
|
667 |
) |
|
668 | ! |
qenv <- teal.code::eval_code(qenv, 'library("forcats")') # nolint quotes |
669 | ! |
qenv <- teal.code::eval_code( |
670 | ! |
qenv, |
671 | ! |
substitute( |
672 | ! |
expr = ANL[[g_var]] <- forcats::fct_na_value_to_level(as.factor(ANL[[g_var]]), "NA"), |
673 | ! |
env = list(g_var = g_var) |
674 |
) |
|
675 |
) |
|
676 |
} |
|
677 | ||
678 | ! |
if (length(s_var) > 0) { |
679 | ! |
validate( |
680 | ! |
need( |
681 | ! |
inherits(ANL[[s_var]], c("integer", "factor", "character")), |
682 | ! |
"Stratify by variable must be `factor`, `character`, or `integer`" |
683 |
) |
|
684 |
) |
|
685 | ||
686 | ! |
qenv <- teal.code::eval_code(qenv, 'library("forcats")') # nolint quotes |
687 | ! |
qenv <- teal.code::eval_code( |
688 | ! |
qenv, |
689 | ! |
substitute( |
690 | ! |
expr = ANL[[s_var]] <- forcats::fct_na_value_to_level(as.factor(ANL[[s_var]]), "NA"), |
691 | ! |
env = list(s_var = s_var) |
692 |
) |
|
693 |
) |
|
694 |
} |
|
695 | ||
696 | ! |
validate(need(is.numeric(ANL[[dist_var]]), "Please select a numeric variable.")) |
697 | ! |
teal::validate_has_data(ANL, 1, complete = TRUE) |
698 | ||
699 | ! |
if (length(t_dist) != 0) { |
700 | ! |
map_distr_nams <- list( |
701 | ! |
normal = c("mean", "sd"), |
702 | ! |
lognormal = c("meanlog", "sdlog"), |
703 | ! |
gamma = c("shape", "rate"), |
704 | ! |
unif = c("min", "max") |
705 |
) |
|
706 | ! |
params_names_raw <- map_distr_nams[[t_dist]] |
707 | ||
708 | ! |
qenv <- teal.code::eval_code( |
709 | ! |
qenv, |
710 | ! |
substitute( |
711 | ! |
expr = { |
712 | ! |
params <- as.list(c(dist_param1, dist_param2)) |
713 | ! |
names(params) <- params_names_raw |
714 |
}, |
|
715 | ! |
env = list( |
716 | ! |
dist_param1 = dist_param1, |
717 | ! |
dist_param2 = dist_param2, |
718 | ! |
params_names_raw = params_names_raw |
719 |
) |
|
720 |
) |
|
721 |
) |
|
722 |
} |
|
723 | ||
724 | ! |
if (length(s_var) == 0 && length(g_var) == 0) { |
725 | ! |
teal.code::eval_code( |
726 | ! |
qenv, |
727 | ! |
substitute( |
728 | ! |
expr = { |
729 | ! |
summary_table_data <- ANL %>% |
730 | ! |
dplyr::summarise( |
731 | ! |
min = round(min(dist_var_name, na.rm = TRUE), roundn), |
732 | ! |
median = round(stats::median(dist_var_name, na.rm = TRUE), roundn), |
733 | ! |
mean = round(mean(dist_var_name, na.rm = TRUE), roundn), |
734 | ! |
max = round(max(dist_var_name, na.rm = TRUE), roundn), |
735 | ! |
sd = round(stats::sd(dist_var_name, na.rm = TRUE), roundn), |
736 | ! |
count = dplyr::n() |
737 |
) |
|
738 |
}, |
|
739 | ! |
env = list( |
740 | ! |
dist_var_name = as.name(dist_var), |
741 | ! |
roundn = roundn |
742 |
) |
|
743 |
) |
|
744 |
) |
|
745 |
} else { |
|
746 | ! |
teal.code::eval_code( |
747 | ! |
qenv, |
748 | ! |
substitute( |
749 | ! |
expr = { |
750 | ! |
strata_vars <- strata_vars_raw |
751 | ! |
summary_table_data <- ANL %>% |
752 | ! |
dplyr::group_by_at(dplyr::vars(dplyr::any_of(strata_vars))) %>% |
753 | ! |
dplyr::summarise( |
754 | ! |
min = round(min(dist_var_name, na.rm = TRUE), roundn), |
755 | ! |
median = round(stats::median(dist_var_name, na.rm = TRUE), roundn), |
756 | ! |
mean = round(mean(dist_var_name, na.rm = TRUE), roundn), |
757 | ! |
max = round(max(dist_var_name, na.rm = TRUE), roundn), |
758 | ! |
sd = round(stats::sd(dist_var_name, na.rm = TRUE), roundn), |
759 | ! |
count = dplyr::n() |
760 |
) |
|
761 |
}, |
|
762 | ! |
env = list( |
763 | ! |
dist_var_name = dist_var_name, |
764 | ! |
strata_vars_raw = c(g_var, s_var), |
765 | ! |
roundn = roundn |
766 |
) |
|
767 |
) |
|
768 |
) |
|
769 |
} |
|
770 |
}) |
|
771 | ||
772 |
# distplot qenv ---- |
|
773 | ! |
dist_q <- eventReactive( |
774 | ! |
eventExpr = { |
775 | ! |
common_q() |
776 | ! |
input$scales_type |
777 | ! |
input$main_type |
778 | ! |
input$bins |
779 | ! |
input$add_dens |
780 | ! |
is.null(input$ggtheme) |
781 |
}, |
|
782 | ! |
valueExpr = { |
783 | ! |
dist_var <- merge_vars()$dist_var |
784 | ! |
s_var <- merge_vars()$s_var |
785 | ! |
g_var <- merge_vars()$g_var |
786 | ! |
dist_var_name <- merge_vars()$dist_var_name |
787 | ! |
s_var_name <- merge_vars()$s_var_name |
788 | ! |
g_var_name <- merge_vars()$g_var_name |
789 | ! |
t_dist <- input$t_dist |
790 | ! |
dist_param1 <- input$dist_param1 |
791 | ! |
dist_param2 <- input$dist_param2 |
792 | ||
793 | ! |
scales_type <- input$scales_type |
794 | ||
795 | ! |
ndensity <- 512 |
796 | ! |
main_type_var <- input$main_type |
797 | ! |
bins_var <- input$bins |
798 | ! |
add_dens_var <- input$add_dens |
799 | ! |
ggtheme <- input$ggtheme |
800 | ||
801 | ! |
teal::validate_inputs(iv_dist) |
802 | ||
803 | ! |
qenv <- common_q() |
804 | ||
805 | ! |
m_type <- if (main_type_var == "Density") "density" else "count" |
806 | ||
807 | ! |
plot_call <- if (length(s_var) == 0 && length(g_var) == 0) { |
808 | ! |
substitute( |
809 | ! |
expr = ggplot2::ggplot(ANL, ggplot2::aes(dist_var_name)) + |
810 | ! |
ggplot2::geom_histogram( |
811 | ! |
position = "identity", ggplot2::aes(y = ggplot2::after_stat(m_type)), bins = bins_var, alpha = 0.3 |
812 |
), |
|
813 | ! |
env = list( |
814 | ! |
m_type = as.name(m_type), bins_var = bins_var, dist_var_name = as.name(dist_var) |
815 |
) |
|
816 |
) |
|
817 | ! |
} else if (length(s_var) != 0 && length(g_var) == 0) { |
818 | ! |
substitute( |
819 | ! |
expr = ggplot2::ggplot(ANL, ggplot2::aes(dist_var_name, col = s_var_name)) + |
820 | ! |
ggplot2::geom_histogram( |
821 | ! |
position = "identity", ggplot2::aes(y = ggplot2::after_stat(m_type), fill = s_var), |
822 | ! |
bins = bins_var, alpha = 0.3 |
823 |
), |
|
824 | ! |
env = list( |
825 | ! |
m_type = as.name(m_type), |
826 | ! |
bins_var = bins_var, |
827 | ! |
dist_var_name = dist_var_name, |
828 | ! |
s_var = as.name(s_var), |
829 | ! |
s_var_name = s_var_name |
830 |
) |
|
831 |
) |
|
832 | ! |
} else if (length(s_var) == 0 && length(g_var) != 0) { |
833 | ! |
req(scales_type) |
834 | ! |
substitute( |
835 | ! |
expr = ggplot2::ggplot(ANL[ANL[[g_var]] != "NA", ], ggplot2::aes(dist_var_name)) + |
836 | ! |
ggplot2::geom_histogram( |
837 | ! |
position = "identity", ggplot2::aes(y = ggplot2::after_stat(m_type)), bins = bins_var, alpha = 0.3 |
838 |
) + |
|
839 | ! |
ggplot2::facet_wrap(~g_var_name, ncol = 1, scales = scales_raw), |
840 | ! |
env = list( |
841 | ! |
m_type = as.name(m_type), |
842 | ! |
bins_var = bins_var, |
843 | ! |
dist_var_name = dist_var_name, |
844 | ! |
g_var = g_var, |
845 | ! |
g_var_name = g_var_name, |
846 | ! |
scales_raw = tolower(scales_type) |
847 |
) |
|
848 |
) |
|
849 |
} else { |
|
850 | ! |
req(scales_type) |
851 | ! |
substitute( |
852 | ! |
expr = ggplot2::ggplot(ANL[ANL[[g_var]] != "NA", ], ggplot2::aes(dist_var_name, col = s_var_name)) + |
853 | ! |
ggplot2::geom_histogram( |
854 | ! |
position = "identity", |
855 | ! |
ggplot2::aes(y = ggplot2::after_stat(m_type), fill = s_var), bins = bins_var, alpha = 0.3 |
856 |
) + |
|
857 | ! |
ggplot2::facet_wrap(~g_var_name, ncol = 1, scales = scales_raw), |
858 | ! |
env = list( |
859 | ! |
m_type = as.name(m_type), |
860 | ! |
bins_var = bins_var, |
861 | ! |
dist_var_name = dist_var_name, |
862 | ! |
g_var = g_var, |
863 | ! |
s_var = as.name(s_var), |
864 | ! |
g_var_name = g_var_name, |
865 | ! |
s_var_name = s_var_name, |
866 | ! |
scales_raw = tolower(scales_type) |
867 |
) |
|
868 |
) |
|
869 |
} |
|
870 | ||
871 | ! |
if (add_dens_var) { |
872 | ! |
plot_call <- substitute( |
873 | ! |
expr = plot_call + |
874 | ! |
ggplot2::stat_density( |
875 | ! |
ggplot2::aes(y = ggplot2::after_stat(const * m_type2)), |
876 | ! |
geom = "line", |
877 | ! |
position = "identity", |
878 | ! |
alpha = 0.5, |
879 | ! |
size = 2, |
880 | ! |
n = ndensity |
881 |
), |
|
882 | ! |
env = list( |
883 | ! |
plot_call = plot_call, |
884 | ! |
const = if (main_type_var == "Density") { |
885 | ! |
1 |
886 |
} else { |
|
887 | ! |
diff(range(qenv[["ANL"]][[dist_var]], na.rm = TRUE)) / bins_var |
888 |
}, |
|
889 | ! |
m_type2 = if (main_type_var == "Density") as.name("density") else as.name("count"), |
890 | ! |
ndensity = ndensity |
891 |
) |
|
892 |
) |
|
893 |
} |
|
894 | ||
895 | ! |
if (length(t_dist) != 0 && main_type_var == "Density" && length(g_var) == 0 && length(s_var) == 0) { |
896 | ! |
qenv <- teal.code::eval_code(qenv, 'library("ggpp")') # nolint quotes |
897 | ! |
qenv <- teal.code::eval_code( |
898 | ! |
qenv, |
899 | ! |
substitute( |
900 | ! |
df_params <- as.data.frame(append(params, list(name = t_dist))), |
901 | ! |
env = list(t_dist = t_dist) |
902 |
) |
|
903 |
) |
|
904 | ! |
datas <- quote(data.frame(x = 0.7, y = 1, tb = I(list(df_params = df_params)))) |
905 | ! |
label <- quote(tb) |
906 | ||
907 | ! |
plot_call <- substitute( |
908 | ! |
expr = plot_call + ggpp::geom_table_npc( |
909 | ! |
data = data, |
910 | ! |
ggplot2::aes(npcx = x, npcy = y, label = label), |
911 | ! |
hjust = 0, vjust = 1, size = 4 |
912 |
), |
|
913 | ! |
env = list(plot_call = plot_call, data = datas, label = label) |
914 |
) |
|
915 |
} |
|
916 | ||
917 | ! |
if ( |
918 | ! |
length(s_var) == 0 && |
919 | ! |
length(g_var) == 0 && |
920 | ! |
main_type_var == "Density" && |
921 | ! |
length(t_dist) != 0 && |
922 | ! |
main_type_var == "Density" |
923 |
) { |
|
924 | ! |
map_dist <- stats::setNames( |
925 | ! |
c("dnorm", "dlnorm", "dgamma", "dunif"), |
926 | ! |
c("normal", "lognormal", "gamma", "unif") |
927 |
) |
|
928 | ! |
plot_call <- substitute( |
929 | ! |
expr = plot_call + stat_function( |
930 | ! |
data = data.frame(x = range(ANL[[dist_var]]), color = mapped_dist), |
931 | ! |
ggplot2::aes(x, color = color), |
932 | ! |
fun = mapped_dist_name, |
933 | ! |
n = ndensity, |
934 | ! |
size = 2, |
935 | ! |
args = params |
936 |
) + |
|
937 | ! |
ggplot2::scale_color_manual(values = stats::setNames("blue", mapped_dist), aesthetics = "color"), |
938 | ! |
env = list( |
939 | ! |
plot_call = plot_call, |
940 | ! |
dist_var = dist_var, |
941 | ! |
ndensity = ndensity, |
942 | ! |
mapped_dist = unname(map_dist[t_dist]), |
943 | ! |
mapped_dist_name = as.name(unname(map_dist[t_dist])) |
944 |
) |
|
945 |
) |
|
946 |
} |
|
947 | ||
948 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
949 | ! |
user_plot = ggplot2_args[["Histogram"]], |
950 | ! |
user_default = ggplot2_args$default |
951 |
) |
|
952 | ||
953 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
954 | ! |
all_ggplot2_args, |
955 | ! |
ggtheme = ggtheme |
956 |
) |
|
957 | ||
958 | ! |
teal.reporter::teal_card(qenv) <- c(teal.reporter::teal_card(qenv), "## Histogram Plot") |
959 | ! |
teal.code::eval_code( |
960 | ! |
qenv, |
961 | ! |
substitute( |
962 | ! |
expr = histogram_plot <- plot_call, |
963 | ! |
env = list(plot_call = Reduce(function(x, y) call("+", x, y), c(plot_call, parsed_ggplot2_args))) |
964 |
) |
|
965 |
) |
|
966 |
} |
|
967 |
) |
|
968 | ||
969 |
# qqplot qenv ---- |
|
970 | ! |
qq_q <- eventReactive( |
971 | ! |
eventExpr = { |
972 | ! |
common_q() |
973 | ! |
input$scales_type |
974 | ! |
input$qq_line |
975 | ! |
is.null(input$ggtheme) |
976 | ! |
input$tabs |
977 |
}, |
|
978 | ! |
valueExpr = { |
979 | ! |
dist_var <- merge_vars()$dist_var |
980 | ! |
s_var <- merge_vars()$s_var |
981 | ! |
g_var <- merge_vars()$g_var |
982 | ! |
dist_var_name <- merge_vars()$dist_var_name |
983 | ! |
s_var_name <- merge_vars()$s_var_name |
984 | ! |
g_var_name <- merge_vars()$g_var_name |
985 | ! |
dist_param1 <- input$dist_param1 |
986 | ! |
dist_param2 <- input$dist_param2 |
987 | ||
988 | ! |
scales_type <- input$scales_type |
989 | ! |
ggtheme <- input$ggtheme |
990 | ||
991 | ! |
teal::validate_inputs(iv_r_dist(), iv_dist) |
992 | ! |
t_dist <- req(input$t_dist) # Not validated when tab is not selected |
993 | ! |
qenv <- common_q() |
994 | ||
995 | ! |
plot_call <- if (length(s_var) == 0 && length(g_var) == 0) { |
996 | ! |
substitute( |
997 | ! |
expr = ggplot2::ggplot(ANL, ggplot2::aes_string(sample = dist_var)), |
998 | ! |
env = list(dist_var = dist_var) |
999 |
) |
|
1000 | ! |
} else if (length(s_var) != 0 && length(g_var) == 0) { |
1001 | ! |
substitute( |
1002 | ! |
expr = ggplot2::ggplot(ANL, ggplot2::aes_string(sample = dist_var, color = s_var)), |
1003 | ! |
env = list(dist_var = dist_var, s_var = s_var) |
1004 |
) |
|
1005 | ! |
} else if (length(s_var) == 0 && length(g_var) != 0) { |
1006 | ! |
substitute( |
1007 | ! |
expr = ggplot2::ggplot(ANL[ANL[[g_var]] != "NA", ], ggplot2::aes_string(sample = dist_var)) + |
1008 | ! |
ggplot2::facet_wrap(~g_var_name, ncol = 1, scales = scales_raw), |
1009 | ! |
env = list( |
1010 | ! |
dist_var = dist_var, |
1011 | ! |
g_var = g_var, |
1012 | ! |
g_var_name = g_var_name, |
1013 | ! |
scales_raw = tolower(scales_type) |
1014 |
) |
|
1015 |
) |
|
1016 |
} else { |
|
1017 | ! |
substitute( |
1018 | ! |
expr = ggplot2::ggplot(ANL[ANL[[g_var]] != "NA", ], ggplot2::aes_string(sample = dist_var, color = s_var)) + |
1019 | ! |
ggplot2::facet_wrap(~g_var_name, ncol = 1, scales = scales_raw), |
1020 | ! |
env = list( |
1021 | ! |
dist_var = dist_var, |
1022 | ! |
g_var = g_var, |
1023 | ! |
s_var = s_var, |
1024 | ! |
g_var_name = g_var_name, |
1025 | ! |
scales_raw = tolower(scales_type) |
1026 |
) |
|
1027 |
) |
|
1028 |
} |
|
1029 | ||
1030 | ! |
map_dist <- stats::setNames( |
1031 | ! |
c("qnorm", "qlnorm", "qgamma", "qunif"), |
1032 | ! |
c("normal", "lognormal", "gamma", "unif") |
1033 |
) |
|
1034 | ||
1035 | ! |
plot_call <- substitute( |
1036 | ! |
expr = plot_call + |
1037 | ! |
ggplot2::stat_qq(distribution = mapped_dist, dparams = params), |
1038 | ! |
env = list(plot_call = plot_call, mapped_dist = as.name(unname(map_dist[t_dist]))) |
1039 |
) |
|
1040 | ||
1041 | ! |
if (length(t_dist) != 0 && length(g_var) == 0 && length(s_var) == 0) { |
1042 | ! |
qenv <- teal.code::eval_code(qenv, 'library("ggpp")') # nolint quotes |
1043 | ! |
qenv <- teal.code::eval_code( |
1044 | ! |
qenv, |
1045 | ! |
substitute( |
1046 | ! |
df_params <- as.data.frame(append(params, list(name = t_dist))), |
1047 | ! |
env = list(t_dist = t_dist) |
1048 |
) |
|
1049 |
) |
|
1050 | ! |
datas <- quote(data.frame(x = 0.7, y = 1, tb = I(list(df_params = df_params)))) |
1051 | ! |
label <- quote(tb) |
1052 | ||
1053 | ! |
plot_call <- substitute( |
1054 | ! |
expr = plot_call + |
1055 | ! |
ggpp::geom_table_npc( |
1056 | ! |
data = data, |
1057 | ! |
ggplot2::aes(npcx = x, npcy = y, label = label), |
1058 | ! |
hjust = 0, |
1059 | ! |
vjust = 1, |
1060 | ! |
size = 4 |
1061 |
), |
|
1062 | ! |
env = list( |
1063 | ! |
plot_call = plot_call, |
1064 | ! |
data = datas, |
1065 | ! |
label = label |
1066 |
) |
|
1067 |
) |
|
1068 |
} |
|
1069 | ||
1070 | ! |
if (isTRUE(input$qq_line)) { |
1071 | ! |
plot_call <- substitute( |
1072 | ! |
expr = plot_call + |
1073 | ! |
ggplot2::stat_qq_line(distribution = mapped_dist, dparams = params), |
1074 | ! |
env = list(plot_call = plot_call, mapped_dist = as.name(unname(map_dist[t_dist]))) |
1075 |
) |
|
1076 |
} |
|
1077 | ||
1078 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
1079 | ! |
user_plot = ggplot2_args[["QQplot"]], |
1080 | ! |
user_default = ggplot2_args$default, |
1081 | ! |
module_plot = teal.widgets::ggplot2_args(labs = list(x = "theoretical", y = "sample")) |
1082 |
) |
|
1083 | ||
1084 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
1085 | ! |
all_ggplot2_args, |
1086 | ! |
ggtheme = ggtheme |
1087 |
) |
|
1088 | ||
1089 | ! |
teal.reporter::teal_card(qenv) <- c(teal.reporter::teal_card(qenv), "## QQ Plot") |
1090 | ! |
teal.code::eval_code( |
1091 | ! |
qenv, |
1092 | ! |
substitute( |
1093 | ! |
expr = qq_plot <- plot_call, |
1094 | ! |
env = list(plot_call = Reduce(function(x, y) call("+", x, y), c(plot_call, parsed_ggplot2_args))) |
1095 |
) |
|
1096 |
) |
|
1097 |
} |
|
1098 |
) |
|
1099 | ||
1100 |
# test qenv ---- |
|
1101 | ! |
test_q <- eventReactive( |
1102 | ! |
ignoreNULL = FALSE, |
1103 | ! |
eventExpr = { |
1104 | ! |
common_q() |
1105 | ! |
input$dist_param1 |
1106 | ! |
input$dist_param2 |
1107 | ! |
input$dist_tests |
1108 |
}, |
|
1109 | ! |
valueExpr = { |
1110 |
# Create a private stack for this function only. |
|
1111 | ! |
ANL <- common_q()[["ANL"]] |
1112 | ||
1113 | ! |
dist_var <- merge_vars()$dist_var |
1114 | ! |
s_var <- merge_vars()$s_var |
1115 | ! |
g_var <- merge_vars()$g_var |
1116 | ||
1117 | ! |
dist_var_name <- merge_vars()$dist_var_name |
1118 | ! |
s_var_name <- merge_vars()$s_var_name |
1119 | ! |
g_var_name <- merge_vars()$g_var_name |
1120 | ||
1121 | ! |
dist_param1 <- input$dist_param1 |
1122 | ! |
dist_param2 <- input$dist_param2 |
1123 | ! |
dist_tests <- input$dist_tests |
1124 | ! |
t_dist <- input$t_dist |
1125 | ||
1126 | ! |
req(dist_tests) |
1127 | ||
1128 | ! |
teal::validate_inputs(iv_dist) |
1129 | ||
1130 | ! |
if (length(s_var) > 0 || length(g_var) > 0) { |
1131 | ! |
counts <- ANL %>% |
1132 | ! |
dplyr::group_by_at(dplyr::vars(dplyr::any_of(c(s_var, g_var)))) %>% |
1133 | ! |
dplyr::summarise(n = dplyr::n()) |
1134 | ||
1135 | ! |
validate(need(all(counts$n > 5), "Please select strata*group with at least 5 observation each.")) |
1136 |
} |
|
1137 | ||
1138 | ||
1139 | ! |
if (dist_tests %in% c( |
1140 | ! |
"t-test (two-samples, not paired)", |
1141 | ! |
"F-test", |
1142 | ! |
"Kolmogorov-Smirnov (two-samples)" |
1143 |
)) { |
|
1144 | ! |
if (length(g_var) == 0 && length(s_var) > 0) { |
1145 | ! |
validate(need( |
1146 | ! |
length(unique(ANL[[s_var]])) == 2, |
1147 | ! |
"Please select stratify variable with 2 levels." |
1148 |
)) |
|
1149 |
} |
|
1150 | ! |
if (length(g_var) > 0 && length(s_var) > 0) { |
1151 | ! |
validate(need( |
1152 | ! |
all(stats::na.omit(as.vector( |
1153 | ! |
tapply(ANL[[s_var]], list(ANL[[g_var]]), function(x) length(unique(x))) == 2 |
1154 |
))), |
|
1155 | ! |
"Please select stratify variable with 2 levels, per each group." |
1156 |
)) |
|
1157 |
} |
|
1158 |
} |
|
1159 | ||
1160 | ! |
map_dist <- stats::setNames( |
1161 | ! |
c("pnorm", "plnorm", "pgamma", "punif"), |
1162 | ! |
c("normal", "lognormal", "gamma", "unif") |
1163 |
) |
|
1164 | ! |
sks_args <- list( |
1165 | ! |
test = quote(stats::ks.test), |
1166 | ! |
args = bquote(append(list(.[[.(dist_var)]], .(map_dist[t_dist])), params)), |
1167 | ! |
groups = c(g_var, s_var) |
1168 |
) |
|
1169 | ! |
ssw_args <- list( |
1170 | ! |
test = quote(stats::shapiro.test), |
1171 | ! |
args = bquote(list(.[[.(dist_var)]])), |
1172 | ! |
groups = c(g_var, s_var) |
1173 |
) |
|
1174 | ! |
mfil_args <- list( |
1175 | ! |
test = quote(stats::fligner.test), |
1176 | ! |
args = bquote(list(.[[.(dist_var)]], .[[.(s_var)]])), |
1177 | ! |
groups = c(g_var) |
1178 |
) |
|
1179 | ! |
sad_args <- list( |
1180 | ! |
test = quote(goftest::ad.test), |
1181 | ! |
args = bquote(append(list(.[[.(dist_var)]], .(map_dist[t_dist])), params)), |
1182 | ! |
groups = c(g_var, s_var) |
1183 |
) |
|
1184 | ! |
scvm_args <- list( |
1185 | ! |
test = quote(goftest::cvm.test), |
1186 | ! |
args = bquote(append(list(.[[.(dist_var)]], .(map_dist[t_dist])), params)), |
1187 | ! |
groups = c(g_var, s_var) |
1188 |
) |
|
1189 | ! |
manov_args <- list( |
1190 | ! |
test = quote(stats::aov), |
1191 | ! |
args = bquote(list(stats::formula(.(dist_var_name) ~ .(s_var_name)), .)), |
1192 | ! |
groups = c(g_var) |
1193 |
) |
|
1194 | ! |
mt_args <- list( |
1195 | ! |
test = quote(stats::t.test), |
1196 | ! |
args = bquote(unname(split(.[[.(dist_var)]], .[[.(s_var)]], drop = TRUE))), |
1197 | ! |
groups = c(g_var) |
1198 |
) |
|
1199 | ! |
mv_args <- list( |
1200 | ! |
test = quote(stats::var.test), |
1201 | ! |
args = bquote(unname(split(.[[.(dist_var)]], .[[.(s_var)]], drop = TRUE))), |
1202 | ! |
groups = c(g_var) |
1203 |
) |
|
1204 | ! |
mks_args <- list( |
1205 | ! |
test = quote(stats::ks.test), |
1206 | ! |
args = bquote(unname(split(.[[.(dist_var)]], .[[.(s_var)]], drop = TRUE))), |
1207 | ! |
groups = c(g_var) |
1208 |
) |
|
1209 | ||
1210 | ! |
tests_base <- switch(dist_tests, |
1211 | ! |
"Kolmogorov-Smirnov (one-sample)" = sks_args, |
1212 | ! |
"Shapiro-Wilk" = ssw_args, |
1213 | ! |
"Fligner-Killeen" = mfil_args, |
1214 | ! |
"one-way ANOVA" = manov_args, |
1215 | ! |
"t-test (two-samples, not paired)" = mt_args, |
1216 | ! |
"F-test" = mv_args, |
1217 | ! |
"Kolmogorov-Smirnov (two-samples)" = mks_args, |
1218 | ! |
"Anderson-Darling (one-sample)" = sad_args, |
1219 | ! |
"Cramer-von Mises (one-sample)" = scvm_args |
1220 |
) |
|
1221 | ||
1222 | ! |
env <- list( |
1223 | ! |
t_test = t_dist, |
1224 | ! |
dist_var = dist_var, |
1225 | ! |
g_var = g_var, |
1226 | ! |
s_var = s_var, |
1227 | ! |
args = tests_base$args, |
1228 | ! |
groups = tests_base$groups, |
1229 | ! |
test = tests_base$test, |
1230 | ! |
dist_var_name = dist_var_name, |
1231 | ! |
g_var_name = g_var_name, |
1232 | ! |
s_var_name = s_var_name |
1233 |
) |
|
1234 | ||
1235 | ! |
qenv <- common_q() |
1236 | ||
1237 | ! |
if (length(s_var) == 0 && length(g_var) == 0) { |
1238 | ! |
qenv <- teal.code::eval_code(qenv, 'library("generics")') # nolint quotes |
1239 | ! |
qenv <- teal.code::eval_code( |
1240 | ! |
qenv, |
1241 | ! |
substitute( |
1242 | ! |
expr = { |
1243 | ! |
test_table_data <- ANL %>% |
1244 | ! |
dplyr::select(dist_var) %>% |
1245 | ! |
with(., generics::glance(do.call(test, args))) %>% |
1246 | ! |
dplyr::mutate_if(is.numeric, round, 3) |
1247 |
}, |
|
1248 | ! |
env = env |
1249 |
) |
|
1250 |
) |
|
1251 |
} else { |
|
1252 | ! |
qenv <- teal.code::eval_code(qenv, 'library("tidyr")') # nolint quotes |
1253 | ! |
qenv <- teal.code::eval_code( |
1254 | ! |
qenv, |
1255 | ! |
substitute( |
1256 | ! |
expr = { |
1257 | ! |
test_table_data <- ANL %>% |
1258 | ! |
dplyr::select(dist_var, s_var, g_var) %>% |
1259 | ! |
dplyr::group_by_at(dplyr::vars(dplyr::any_of(groups))) %>% |
1260 | ! |
dplyr::do(tests = generics::glance(do.call(test, args))) %>% |
1261 | ! |
tidyr::unnest(tests) %>% |
1262 | ! |
dplyr::mutate_if(is.numeric, round, 3) |
1263 |
}, |
|
1264 | ! |
env = env |
1265 |
) |
|
1266 |
) |
|
1267 |
} |
|
1268 |
} |
|
1269 |
) |
|
1270 | ||
1271 |
# outputs ---- |
|
1272 | ! |
output_dist_q <- reactive(c(common_q(), req(dist_q()))) |
1273 | ! |
output_qq_q <- reactive(c(common_q(), req(qq_q()))) |
1274 | ||
1275 |
# Summary table listing has to be created separately to allow for qenv join |
|
1276 | ! |
q_common <- common_q() |
1277 | ! |
teal.reporter::teal_card(q_common) <- c( |
1278 | ! |
teal.reporter::teal_card(q_common), |
1279 | ! |
"## Statistics table" |
1280 |
) |
|
1281 | ! |
output_summary_q <- reactive({ |
1282 | ! |
if (iv_r()$is_valid()) { |
1283 | ! |
within(q_common, { |
1284 | ! |
summary_table <- rtables::df_to_tt(summary_table_data) |
1285 |
}) |
|
1286 |
} else { |
|
1287 | ! |
within( |
1288 | ! |
q_common, |
1289 | ! |
summary_table <- rtables::rtable(header = rtables::rheader(colnames(summary_table_data))) |
1290 |
) |
|
1291 |
} |
|
1292 |
}) |
|
1293 | ||
1294 | ! |
output_test_q <- reactive({ |
1295 |
# wrapped in if since could lead into validate error - we do want to continue |
|
1296 | ! |
test_q_out <- try(test_q(), silent = TRUE) |
1297 | ! |
q_common <- common_q() |
1298 | ! |
teal.reporter::teal_card(q_common) <- c( |
1299 | ! |
teal.reporter::teal_card(q_common), |
1300 | ! |
"## Distribution Tests table" |
1301 |
) |
|
1302 | ! |
if (inherits(test_q_out, c("try-error", "error"))) { |
1303 | ! |
within( |
1304 | ! |
q_common, |
1305 | ! |
test_table <- rtables::rtable(header = rtables::rheader("No data available in table"), rtables::rrow()) |
1306 |
) |
|
1307 |
} else { |
|
1308 | ! |
within(c(q_common, test_q_out), { |
1309 | ! |
test_table <- rtables::df_to_tt(test_table_data) |
1310 |
}) |
|
1311 |
} |
|
1312 |
}) |
|
1313 | ||
1314 | ! |
decorated_output_dist_q <- srv_decorate_teal_data( |
1315 | ! |
"d_density", |
1316 | ! |
data = output_dist_q, |
1317 | ! |
decorators = select_decorators(decorators, "histogram_plot"), |
1318 | ! |
expr = quote(histogram_plot) |
1319 |
) |
|
1320 | ||
1321 | ! |
decorated_output_qq_q <- srv_decorate_teal_data( |
1322 | ! |
"d_qq", |
1323 | ! |
data = output_qq_q, |
1324 | ! |
decorators = select_decorators(decorators, "qq_plot"), |
1325 | ! |
expr = quote(qq_plot) |
1326 |
) |
|
1327 | ||
1328 | ! |
decorated_output_summary_q <- srv_decorate_teal_data( |
1329 | ! |
"d_summary", |
1330 | ! |
data = output_summary_q, |
1331 | ! |
decorators = select_decorators(decorators, "summary_table"), |
1332 | ! |
expr = quote(summary_table) |
1333 |
) |
|
1334 | ||
1335 | ! |
decorated_output_test_q <- srv_decorate_teal_data( |
1336 | ! |
"d_test", |
1337 | ! |
data = output_test_q, |
1338 | ! |
decorators = select_decorators(decorators, "test_table"), |
1339 | ! |
expr = quote(test_table) |
1340 |
) |
|
1341 | ||
1342 | ! |
dist_r <- reactive(req(decorated_output_dist_q())[["histogram_plot"]]) |
1343 | ! |
qq_r <- reactive(req(decorated_output_qq_q())[["qq_plot"]]) |
1344 | ||
1345 | ! |
summary_r <- reactive({ |
1346 | ! |
q <- req(output_summary_q()) |
1347 | ||
1348 | ! |
DT::datatable( |
1349 | ! |
q[["summary_table_data"]], |
1350 | ! |
options = list( |
1351 | ! |
autoWidth = TRUE, |
1352 | ! |
columnDefs = list(list(width = "200px", targets = "_all")) |
1353 |
), |
|
1354 | ! |
rownames = FALSE |
1355 |
) |
|
1356 |
}) |
|
1357 | ||
1358 | ! |
output$summary_table <- DT::renderDataTable(summary_r()) |
1359 | ||
1360 | ! |
tests_r <- reactive({ |
1361 | ! |
q <- req(output_test_q()) |
1362 | ! |
DT::datatable(q[["test_table_data"]]) |
1363 |
}) |
|
1364 | ||
1365 | ! |
pws1 <- teal.widgets::plot_with_settings_srv( |
1366 | ! |
id = "hist_plot", |
1367 | ! |
plot_r = dist_r, |
1368 | ! |
height = plot_height, |
1369 | ! |
width = plot_width, |
1370 | ! |
brushing = FALSE |
1371 |
) |
|
1372 | ||
1373 | ! |
pws2 <- teal.widgets::plot_with_settings_srv( |
1374 | ! |
id = "qq_plot", |
1375 | ! |
plot_r = qq_r, |
1376 | ! |
height = plot_height, |
1377 | ! |
width = plot_width, |
1378 | ! |
brushing = FALSE |
1379 |
) |
|
1380 | ||
1381 | ! |
decorated_output_dist_dims_q <- set_chunk_dims(pws1, decorated_output_dist_q) |
1382 | ||
1383 | ! |
decorated_output_qq_dims_q <- set_chunk_dims(pws2, decorated_output_qq_q) |
1384 | ||
1385 | ! |
decorated_output_q <- reactive({ |
1386 | ! |
tab <- req(input$tabs) # tab is NULL upon app launch, hence will crash without this statement |
1387 | ! |
test_q_out <- output_test_q() |
1388 | ||
1389 | ! |
out_q <- switch(tab, |
1390 | ! |
Histogram = decorated_output_dist_dims_q(), |
1391 | ! |
QQplot = decorated_output_qq_dims_q() |
1392 |
) |
|
1393 | ! |
withCallingHandlers( |
1394 | ! |
c(out_q, output_summary_q(), test_q_out), |
1395 | ! |
warning = function(w) { |
1396 | ! |
if (grepl("Restoring original content and adding only", conditionMessage(w))) { |
1397 | ! |
invokeRestart("muffleWarning") |
1398 |
} |
|
1399 |
} |
|
1400 |
) |
|
1401 |
}) |
|
1402 | ||
1403 | ! |
output$t_stats <- DT::renderDataTable(tests_r()) |
1404 | ||
1405 |
# Render R code. |
|
1406 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_output_q()))) |
1407 | ||
1408 | ! |
teal.widgets::verbatim_popup_srv( |
1409 | ! |
id = "rcode", |
1410 | ! |
verbatim_content = source_code_r, |
1411 | ! |
title = "R Code for distribution" |
1412 |
) |
|
1413 | ! |
decorated_output_q |
1414 |
}) |
|
1415 |
} |
1 |
#' `teal` module: Data table viewer |
|
2 |
#' |
|
3 |
#' Module provides a dynamic and interactive way to view `data.frame`s in a `teal` application. |
|
4 |
#' It uses the `DT` package to display data tables in a paginated, searchable, and sortable format, |
|
5 |
#' which helps to enhance data exploration and analysis. |
|
6 |
#' |
|
7 |
#' The `DT` package has an option `DT.TOJSON_ARGS` to show `Inf` and `NA` in data tables. |
|
8 |
#' Configure the `DT.TOJSON_ARGS` option via |
|
9 |
#' `options(DT.TOJSON_ARGS = list(na = "string"))` before running the module. |
|
10 |
#' Note though that sorting of numeric columns with `NA`/`Inf` will be lexicographic not numerical. |
|
11 |
#' |
|
12 |
#' @inheritParams teal::module |
|
13 |
#' @inheritParams shared_params |
|
14 |
#' @param variables_selected (`named list`) Character vectors of the variables (i.e. columns) |
|
15 |
#' which should be initially shown for each dataset. |
|
16 |
#' Names of list elements should correspond to the names of the datasets available in the app. |
|
17 |
#' If no entry is specified for a dataset, the first six variables from that |
|
18 |
#' dataset will initially be shown. |
|
19 |
#' @param datasets_selected (`character`) `r lifecycle::badge("deprecated")` A vector of datasets which should be |
|
20 |
#' shown and in what order. Use `datanames` instead. |
|
21 |
#' @param dt_args (`named list`) Additional arguments to be passed to [DT::datatable()] |
|
22 |
#' (must not include `data` or `options`). |
|
23 |
#' @param dt_options (`named list`) The `options` argument to `DT::datatable`. By default |
|
24 |
#' `list(searching = FALSE, pageLength = 30, lengthMenu = c(5, 15, 30, 100), scrollX = TRUE)` |
|
25 |
#' @param server_rendering (`logical`) should the data table be rendered server side |
|
26 |
#' (see `server` argument of [DT::renderDataTable()]) |
|
27 |
#' |
|
28 |
#' @inherit shared_params return |
|
29 |
#' |
|
30 |
#' @examplesShinylive |
|
31 |
#' library(teal.modules.general) |
|
32 |
#' interactive <- function() TRUE |
|
33 |
#' {{ next_example }} |
|
34 |
#' @examples |
|
35 |
#' # general data example |
|
36 |
#' data <- teal_data() |
|
37 |
#' data <- within(data, { |
|
38 |
#' require(nestcolor) |
|
39 |
#' iris <- iris |
|
40 |
#' }) |
|
41 |
#' |
|
42 |
#' app <- init( |
|
43 |
#' data = data, |
|
44 |
#' modules = modules( |
|
45 |
#' tm_data_table( |
|
46 |
#' variables_selected = list( |
|
47 |
#' iris = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species") |
|
48 |
#' ), |
|
49 |
#' dt_args = list(caption = "IRIS Table Caption") |
|
50 |
#' ) |
|
51 |
#' ) |
|
52 |
#' ) |
|
53 |
#' if (interactive()) { |
|
54 |
#' shinyApp(app$ui, app$server) |
|
55 |
#' } |
|
56 |
#' |
|
57 |
#' @examplesShinylive |
|
58 |
#' library(teal.modules.general) |
|
59 |
#' interactive <- function() TRUE |
|
60 |
#' {{ next_example }} |
|
61 |
#' @examples |
|
62 |
#' # CDISC data example |
|
63 |
#' data <- teal_data() |
|
64 |
#' data <- within(data, { |
|
65 |
#' require(nestcolor) |
|
66 |
#' ADSL <- teal.data::rADSL |
|
67 |
#' }) |
|
68 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
69 |
#' |
|
70 |
#' app <- init( |
|
71 |
#' data = data, |
|
72 |
#' modules = modules( |
|
73 |
#' tm_data_table( |
|
74 |
#' variables_selected = list(ADSL = c("STUDYID", "USUBJID", "SUBJID", "SITEID", "AGE", "SEX")), |
|
75 |
#' dt_args = list(caption = "ADSL Table Caption") |
|
76 |
#' ) |
|
77 |
#' ) |
|
78 |
#' ) |
|
79 |
#' if (interactive()) { |
|
80 |
#' shinyApp(app$ui, app$server) |
|
81 |
#' } |
|
82 |
#' |
|
83 |
#' @export |
|
84 |
#' |
|
85 |
tm_data_table <- function(label = "Data Table", |
|
86 |
variables_selected = list(), |
|
87 |
datasets_selected = deprecated(), |
|
88 |
datanames = if (missing(datasets_selected)) "all" else datasets_selected, |
|
89 |
dt_args = list(), |
|
90 |
dt_options = list( |
|
91 |
searching = FALSE, |
|
92 |
pageLength = 30, |
|
93 |
lengthMenu = c(5, 15, 30, 100), |
|
94 |
scrollX = TRUE |
|
95 |
), |
|
96 |
server_rendering = FALSE, |
|
97 |
pre_output = NULL, |
|
98 |
post_output = NULL, |
|
99 |
transformators = list()) { |
|
100 | ! |
message("Initializing tm_data_table") |
101 | ||
102 |
# Start of assertions |
|
103 | ! |
checkmate::assert_string(label) |
104 | ||
105 | ! |
checkmate::assert_list(variables_selected, min.len = 0, types = "character", names = "named") |
106 | ! |
if (length(variables_selected) > 0) { |
107 | ! |
lapply(seq_along(variables_selected), function(i) { |
108 | ! |
checkmate::assert_character(variables_selected[[i]], min.chars = 1, min.len = 1) |
109 | ! |
if (!is.null(names(variables_selected[[i]]))) { |
110 | ! |
checkmate::assert_names(names(variables_selected[[i]])) |
111 |
} |
|
112 |
}) |
|
113 |
} |
|
114 | ! |
if (!missing(datasets_selected)) { |
115 | ! |
lifecycle::deprecate_stop( |
116 | ! |
when = "0.4.0", |
117 | ! |
what = "tm_data_table(datasets_selected)", |
118 | ! |
with = "tm_data_table(datanames)", |
119 | ! |
details = 'Use tm_data_table(datanames = "all") to keep the previous behavior and avoid this warning.', |
120 |
) |
|
121 |
} |
|
122 | ! |
checkmate::assert_character(datanames, min.len = 0, min.chars = 1, null.ok = TRUE) |
123 | ! |
checkmate::assert( |
124 | ! |
checkmate::check_list(dt_args, len = 0), |
125 | ! |
checkmate::check_subset(names(dt_args), choices = names(formals(DT::datatable))) |
126 |
) |
|
127 | ! |
checkmate::assert_list(dt_options, names = "named") |
128 | ! |
checkmate::assert_flag(server_rendering) |
129 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
130 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
131 | ||
132 |
# End of assertions |
|
133 | ||
134 | ! |
ans <- module( |
135 | ! |
label, |
136 | ! |
server = srv_page_data_table, |
137 | ! |
ui = ui_page_data_table, |
138 | ! |
datanames = datanames, |
139 | ! |
server_args = list( |
140 | ! |
datanames = if (is.null(datanames)) "all" else datanames, |
141 | ! |
variables_selected = variables_selected, |
142 | ! |
dt_args = dt_args, |
143 | ! |
dt_options = dt_options, |
144 | ! |
server_rendering = server_rendering |
145 |
), |
|
146 | ! |
ui_args = list( |
147 | ! |
pre_output = pre_output, |
148 | ! |
post_output = post_output |
149 |
), |
|
150 | ! |
transformators = transformators |
151 |
) |
|
152 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
153 | ! |
ans |
154 |
} |
|
155 | ||
156 |
# UI page module |
|
157 |
ui_page_data_table <- function(id, pre_output = NULL, post_output = NULL) { |
|
158 | ! |
ns <- NS(id) |
159 | ||
160 | ! |
tagList( |
161 | ! |
teal.widgets::standard_layout( |
162 | ! |
output = teal.widgets::white_small_well( |
163 | ! |
bslib::page_fluid( |
164 | ! |
checkboxInput( |
165 | ! |
ns("if_distinct"), |
166 | ! |
"Show only distinct rows:", |
167 | ! |
value = FALSE |
168 |
) |
|
169 |
), |
|
170 | ! |
bslib::page_fluid( |
171 | ! |
uiOutput(ns("dataset_table")) |
172 |
) |
|
173 |
), |
|
174 | ! |
pre_output = pre_output, |
175 | ! |
post_output = post_output |
176 |
) |
|
177 |
) |
|
178 |
} |
|
179 | ||
180 |
# Server page module |
|
181 |
srv_page_data_table <- function(id, |
|
182 |
data, |
|
183 |
datanames, |
|
184 |
variables_selected, |
|
185 |
dt_args, |
|
186 |
dt_options, |
|
187 |
server_rendering) { |
|
188 | ! |
checkmate::assert_class(data, "reactive") |
189 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
190 | ! |
moduleServer(id, function(input, output, session) { |
191 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
192 | ||
193 | ! |
if_filtered <- reactive(as.logical(input$if_filtered)) |
194 | ! |
if_distinct <- reactive(as.logical(input$if_distinct)) |
195 | ||
196 | ! |
datanames <- Filter(function(name) { |
197 | ! |
is.data.frame(isolate(data())[[name]]) |
198 | ! |
}, if (identical(datanames, "all")) names(isolate(data())) else datanames) |
199 | ||
200 | ||
201 | ! |
output$dataset_table <- renderUI({ |
202 | ! |
do.call( |
203 | ! |
tabsetPanel, |
204 | ! |
c( |
205 | ! |
list(id = session$ns("dataname_tab")), |
206 | ! |
lapply( |
207 | ! |
datanames, |
208 | ! |
function(x) { |
209 | ! |
dataset <- isolate(data()[[x]]) |
210 | ! |
choices <- names(dataset) |
211 | ! |
labels <- vapply( |
212 | ! |
dataset, |
213 | ! |
function(x) ifelse(is.null(attr(x, "label")), "", attr(x, "label")), |
214 | ! |
character(1) |
215 |
) |
|
216 | ! |
names(choices) <- ifelse( |
217 | ! |
is.na(labels) | labels == "", |
218 | ! |
choices, |
219 | ! |
paste(choices, labels, sep = ": ") |
220 |
) |
|
221 | ! |
variables_selected <- if (!is.null(variables_selected[[x]])) { |
222 | ! |
variables_selected[[x]] |
223 |
} else { |
|
224 | ! |
utils::head(choices) |
225 |
} |
|
226 | ! |
tabPanel( |
227 | ! |
title = x, |
228 | ! |
bslib::layout_columns( |
229 | ! |
col_widths = 12, |
230 | ! |
ui_data_table( |
231 | ! |
id = session$ns(x), |
232 | ! |
choices = choices, |
233 | ! |
selected = variables_selected |
234 |
) |
|
235 |
) |
|
236 |
) |
|
237 |
} |
|
238 |
) |
|
239 |
) |
|
240 |
) |
|
241 |
}) |
|
242 | ||
243 | ! |
lapply( |
244 | ! |
datanames, |
245 | ! |
function(x) { |
246 | ! |
srv_data_table( |
247 | ! |
id = x, |
248 | ! |
data = data, |
249 | ! |
dataname = x, |
250 | ! |
if_filtered = if_filtered, |
251 | ! |
if_distinct = if_distinct, |
252 | ! |
dt_args = dt_args, |
253 | ! |
dt_options = dt_options, |
254 | ! |
server_rendering = server_rendering |
255 |
) |
|
256 |
} |
|
257 |
) |
|
258 |
}) |
|
259 |
} |
|
260 | ||
261 |
# UI function for the data_table module |
|
262 |
ui_data_table <- function(id, choices, selected) { |
|
263 | ! |
ns <- NS(id) |
264 | ||
265 | ! |
if (!is.null(selected)) { |
266 | ! |
all_choices <- choices |
267 | ! |
choices <- c(selected, setdiff(choices, selected)) |
268 | ! |
names(choices) <- names(all_choices)[match(choices, all_choices)] |
269 |
} |
|
270 | ||
271 | ! |
tagList( |
272 | ! |
teal.widgets::get_dt_rows(ns("data_table"), ns("dt_rows")), |
273 | ! |
bslib::page_fluid( |
274 | ! |
teal.widgets::optionalSelectInput( |
275 | ! |
ns("variables"), |
276 | ! |
"Select variables:", |
277 | ! |
choices = choices, |
278 | ! |
selected = selected, |
279 | ! |
multiple = TRUE, |
280 | ! |
width = "100%" |
281 |
) |
|
282 |
), |
|
283 | ! |
bslib::page_fluid( |
284 | ! |
DT::dataTableOutput(ns("data_table"), width = "100%") |
285 |
) |
|
286 |
) |
|
287 |
} |
|
288 | ||
289 |
# Server function for the data_table module |
|
290 |
srv_data_table <- function(id, |
|
291 |
data, |
|
292 |
dataname, |
|
293 |
if_filtered, |
|
294 |
if_distinct, |
|
295 |
dt_args, |
|
296 |
dt_options, |
|
297 |
server_rendering) { |
|
298 | ! |
moduleServer(id, function(input, output, session) { |
299 | ! |
iv <- shinyvalidate::InputValidator$new() |
300 | ! |
iv$add_rule("variables", shinyvalidate::sv_required("Please select valid variable names")) |
301 | ! |
iv$add_rule("variables", shinyvalidate::sv_in_set( |
302 | ! |
set = names(isolate(data())[[dataname]]), message_fmt = "Not all selected variables exist in the data" |
303 |
)) |
|
304 | ! |
iv$enable() |
305 | ||
306 | ! |
data_table_data <- reactive({ |
307 | ! |
df <- data()[[dataname]] |
308 | ||
309 | ! |
teal::validate_has_data(df, min_nrow = 1L, msg = paste("data", dataname, "is empty")) |
310 | ! |
qenv <- teal.code::eval_code( |
311 | ! |
data(), |
312 | ! |
'library("dplyr");library("DT")' # nolint: quotes. |
313 |
) |
|
314 | ! |
teal.code::eval_code( |
315 | ! |
qenv, |
316 | ! |
substitute( |
317 | ! |
expr = { |
318 | ! |
variables <- vars |
319 | ! |
dataframe_selected <- if (if_distinct) { |
320 | ! |
dplyr::count(dataname, dplyr::across(dplyr::all_of(variables))) |
321 |
} else { |
|
322 | ! |
dataname[variables] |
323 |
} |
|
324 | ! |
dt_args <- args |
325 | ! |
dt_args$options <- dt_options |
326 | ! |
if (!is.null(dt_rows)) { |
327 | ! |
dt_args$options$pageLength <- dt_rows |
328 |
} |
|
329 | ! |
dt_args$data <- dataframe_selected |
330 | ! |
table <- do.call(DT::datatable, dt_args) |
331 |
}, |
|
332 | ! |
env = list( |
333 | ! |
dataname = as.name(dataname), |
334 | ! |
if_distinct = if_distinct(), |
335 | ! |
vars = input$variables, |
336 | ! |
args = dt_args, |
337 | ! |
dt_options = dt_options, |
338 | ! |
dt_rows = input$dt_rows |
339 |
) |
|
340 |
) |
|
341 |
) |
|
342 |
}) |
|
343 | ||
344 | ! |
output$data_table <- DT::renderDataTable(server = server_rendering, { |
345 | ! |
teal::validate_inputs(iv) |
346 | ! |
req(data_table_data())[["table"]] |
347 |
}) |
|
348 |
}) |
|
349 |
} |
1 |
#' `teal` module: Scatterplot matrix |
|
2 |
#' |
|
3 |
#' Generates a scatterplot matrix from selected `variables` from datasets. |
|
4 |
#' Each plot within the matrix represents the relationship between two variables, |
|
5 |
#' providing the overview of correlations and distributions across selected data. |
|
6 |
#' |
|
7 |
#' @note For more examples, please see the vignette "Using scatterplot matrix" via |
|
8 |
#' `vignette("using-scatterplot-matrix", package = "teal.modules.general")`. |
|
9 |
#' |
|
10 |
#' @inheritParams teal::module |
|
11 |
#' @inheritParams tm_g_scatterplot |
|
12 |
#' @inheritParams shared_params |
|
13 |
#' |
|
14 |
#' @param variables (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
15 |
#' Specifies plotting variables from an incoming dataset with filtering and selecting. In case of |
|
16 |
#' `data_extract_spec` use `select_spec(..., ordered = TRUE)` if plot elements should be |
|
17 |
#' rendered according to selection order. |
|
18 |
#' |
|
19 |
#' @inherit shared_params return |
|
20 |
#' |
|
21 |
#' @section Decorating Module: |
|
22 |
#' |
|
23 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
24 |
#' - `plot` (`trellis` - output of `lattice::splom`) |
|
25 |
#' |
|
26 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
27 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
28 |
#' See code snippet below: |
|
29 |
#' |
|
30 |
#' ``` |
|
31 |
#' tm_g_scatterplotmatrix( |
|
32 |
#' ..., # arguments for module |
|
33 |
#' decorators = list( |
|
34 |
#' plot = teal_transform_module(...) # applied to the `plot` output |
|
35 |
#' ) |
|
36 |
#' ) |
|
37 |
#' ``` |
|
38 |
#' |
|
39 |
#' For additional details and examples of decorators, refer to the vignette |
|
40 |
#' `vignette("decorate-module-output", package = "teal.modules.general")`. |
|
41 |
#' |
|
42 |
#' To learn more please refer to the vignette |
|
43 |
#' `vignette("transform-module-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
44 |
#' |
|
45 |
#' @inheritSection teal::example_module Reporting |
|
46 |
#' |
|
47 |
#' @examplesShinylive |
|
48 |
#' library(teal.modules.general) |
|
49 |
#' interactive <- function() TRUE |
|
50 |
#' {{ next_example }} |
|
51 |
#' @examples |
|
52 |
#' # general data example |
|
53 |
#' data <- teal_data() |
|
54 |
#' data <- within(data, { |
|
55 |
#' countries <- data.frame( |
|
56 |
#' id = c("DE", "FR", "IT", "ES", "PT", "GR", "NL", "BE", "LU", "AT"), |
|
57 |
#' government = factor( |
|
58 |
#' c(2, 2, 2, 1, 2, 2, 1, 1, 1, 2), |
|
59 |
#' labels = c("Monarchy", "Republic") |
|
60 |
#' ), |
|
61 |
#' language_family = factor( |
|
62 |
#' c(1, 3, 3, 3, 3, 2, 1, 1, 3, 1), |
|
63 |
#' labels = c("Germanic", "Hellenic", "Romance") |
|
64 |
#' ), |
|
65 |
#' population = c(83, 67, 60, 47, 10, 11, 17, 11, 0.6, 9), |
|
66 |
#' area = c(357, 551, 301, 505, 92, 132, 41, 30, 2.6, 83), |
|
67 |
#' gdp = c(3.4, 2.7, 2.1, 1.4, 0.3, 0.2, 0.7, 0.5, 0.1, 0.4), |
|
68 |
#' debt = c(2.1, 2.3, 2.4, 2.6, 2.3, 2.4, 2.3, 2.4, 2.3, 2.4) |
|
69 |
#' ) |
|
70 |
#' sales <- data.frame( |
|
71 |
#' id = 1:50, |
|
72 |
#' country_id = sample( |
|
73 |
#' c("DE", "FR", "IT", "ES", "PT", "GR", "NL", "BE", "LU", "AT"), |
|
74 |
#' size = 50, |
|
75 |
#' replace = TRUE |
|
76 |
#' ), |
|
77 |
#' year = sort(sample(2010:2020, 50, replace = TRUE)), |
|
78 |
#' venue = sample(c("small", "medium", "large", "online"), 50, replace = TRUE), |
|
79 |
#' cancelled = sample(c(TRUE, FALSE), 50, replace = TRUE), |
|
80 |
#' quantity = rnorm(50, 100, 20), |
|
81 |
#' costs = rnorm(50, 80, 20), |
|
82 |
#' profit = rnorm(50, 20, 10) |
|
83 |
#' ) |
|
84 |
#' }) |
|
85 |
#' join_keys(data) <- join_keys( |
|
86 |
#' join_key("countries", "countries", "id"), |
|
87 |
#' join_key("sales", "sales", "id"), |
|
88 |
#' join_key("countries", "sales", c("id" = "country_id")) |
|
89 |
#' ) |
|
90 |
#' |
|
91 |
#' app <- init( |
|
92 |
#' data = data, |
|
93 |
#' modules = modules( |
|
94 |
#' tm_g_scatterplotmatrix( |
|
95 |
#' label = "Scatterplot matrix", |
|
96 |
#' variables = list( |
|
97 |
#' data_extract_spec( |
|
98 |
#' dataname = "countries", |
|
99 |
#' select = select_spec( |
|
100 |
#' label = "Select variables:", |
|
101 |
#' choices = variable_choices(data[["countries"]]), |
|
102 |
#' selected = c("area", "gdp", "debt"), |
|
103 |
#' multiple = TRUE, |
|
104 |
#' ordered = TRUE, |
|
105 |
#' fixed = FALSE |
|
106 |
#' ) |
|
107 |
#' ), |
|
108 |
#' data_extract_spec( |
|
109 |
#' dataname = "sales", |
|
110 |
#' filter = filter_spec( |
|
111 |
#' label = "Select variable:", |
|
112 |
#' vars = "country_id", |
|
113 |
#' choices = value_choices(data[["sales"]], "country_id"), |
|
114 |
#' selected = c("DE", "FR", "IT", "PT", "GR", "NL", "BE", "LU", "AT"), |
|
115 |
#' multiple = TRUE |
|
116 |
#' ), |
|
117 |
#' select = select_spec( |
|
118 |
#' label = "Select variables:", |
|
119 |
#' choices = variable_choices(data[["sales"]], c("quantity", "costs", "profit")), |
|
120 |
#' selected = c("quantity", "costs", "profit"), |
|
121 |
#' multiple = TRUE, |
|
122 |
#' ordered = TRUE, |
|
123 |
#' fixed = FALSE |
|
124 |
#' ) |
|
125 |
#' ) |
|
126 |
#' ) |
|
127 |
#' ) |
|
128 |
#' ) |
|
129 |
#' ) |
|
130 |
#' if (interactive()) { |
|
131 |
#' shinyApp(app$ui, app$server) |
|
132 |
#' } |
|
133 |
#' |
|
134 |
#' @examplesShinylive |
|
135 |
#' library(teal.modules.general) |
|
136 |
#' interactive <- function() TRUE |
|
137 |
#' {{ next_example }} |
|
138 |
#' @examples |
|
139 |
#' # CDISC data example |
|
140 |
#' data <- teal_data() |
|
141 |
#' data <- within(data, { |
|
142 |
#' ADSL <- teal.data::rADSL |
|
143 |
#' ADRS <- teal.data::rADRS |
|
144 |
#' }) |
|
145 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
146 |
#' |
|
147 |
#' app <- init( |
|
148 |
#' data = data, |
|
149 |
#' modules = modules( |
|
150 |
#' tm_g_scatterplotmatrix( |
|
151 |
#' label = "Scatterplot matrix", |
|
152 |
#' variables = list( |
|
153 |
#' data_extract_spec( |
|
154 |
#' dataname = "ADSL", |
|
155 |
#' select = select_spec( |
|
156 |
#' label = "Select variables:", |
|
157 |
#' choices = variable_choices(data[["ADSL"]]), |
|
158 |
#' selected = c("AGE", "RACE", "SEX"), |
|
159 |
#' multiple = TRUE, |
|
160 |
#' ordered = TRUE, |
|
161 |
#' fixed = FALSE |
|
162 |
#' ) |
|
163 |
#' ), |
|
164 |
#' data_extract_spec( |
|
165 |
#' dataname = "ADRS", |
|
166 |
#' filter = filter_spec( |
|
167 |
#' label = "Select endpoints:", |
|
168 |
#' vars = c("PARAMCD", "AVISIT"), |
|
169 |
#' choices = value_choices(data[["ADRS"]], c("PARAMCD", "AVISIT"), c("PARAM", "AVISIT")), |
|
170 |
#' selected = "INVET - END OF INDUCTION", |
|
171 |
#' multiple = TRUE |
|
172 |
#' ), |
|
173 |
#' select = select_spec( |
|
174 |
#' label = "Select variables:", |
|
175 |
#' choices = variable_choices(data[["ADRS"]]), |
|
176 |
#' selected = c("AGE", "AVAL", "ADY"), |
|
177 |
#' multiple = TRUE, |
|
178 |
#' ordered = TRUE, |
|
179 |
#' fixed = FALSE |
|
180 |
#' ) |
|
181 |
#' ) |
|
182 |
#' ) |
|
183 |
#' ) |
|
184 |
#' ) |
|
185 |
#' ) |
|
186 |
#' if (interactive()) { |
|
187 |
#' shinyApp(app$ui, app$server) |
|
188 |
#' } |
|
189 |
#' |
|
190 |
#' @export |
|
191 |
#' |
|
192 |
tm_g_scatterplotmatrix <- function(label = "Scatterplot Matrix", |
|
193 |
variables, |
|
194 |
plot_height = c(600, 200, 2000), |
|
195 |
plot_width = NULL, |
|
196 |
pre_output = NULL, |
|
197 |
post_output = NULL, |
|
198 |
transformators = list(), |
|
199 |
decorators = list()) { |
|
200 | ! |
message("Initializing tm_g_scatterplotmatrix") |
201 | ||
202 |
# Normalize the parameters |
|
203 | ! |
if (inherits(variables, "data_extract_spec")) variables <- list(variables) |
204 | ||
205 |
# Start of assertions |
|
206 | ! |
checkmate::assert_string(label) |
207 | ! |
checkmate::assert_list(variables, types = "data_extract_spec") |
208 | ||
209 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
210 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
211 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
212 | ! |
checkmate::assert_numeric( |
213 | ! |
plot_width[1], |
214 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
215 |
) |
|
216 | ||
217 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
218 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
219 | ||
220 | ! |
assert_decorators(decorators, "plot") |
221 |
# End of assertions |
|
222 | ||
223 |
# Make UI args |
|
224 | ! |
args <- as.list(environment()) |
225 | ||
226 | ! |
ans <- module( |
227 | ! |
label = label, |
228 | ! |
server = srv_g_scatterplotmatrix, |
229 | ! |
ui = ui_g_scatterplotmatrix, |
230 | ! |
ui_args = args, |
231 | ! |
server_args = list( |
232 | ! |
variables = variables, |
233 | ! |
plot_height = plot_height, |
234 | ! |
plot_width = plot_width, |
235 | ! |
decorators = decorators |
236 |
), |
|
237 | ! |
transformators = transformators, |
238 | ! |
datanames = teal.transform::get_extract_datanames(variables) |
239 |
) |
|
240 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
241 | ! |
ans |
242 |
} |
|
243 | ||
244 |
# UI function for the scatterplot matrix module |
|
245 |
ui_g_scatterplotmatrix <- function(id, ...) { |
|
246 | ! |
args <- list(...) |
247 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$variables) |
248 | ! |
ns <- NS(id) |
249 | ! |
teal.widgets::standard_layout( |
250 | ! |
output = teal.widgets::white_small_well( |
251 | ! |
textOutput(ns("message")), |
252 | ! |
tags$br(), |
253 | ! |
teal.widgets::plot_with_settings_ui(id = ns("myplot")) |
254 |
), |
|
255 | ! |
encoding = tags$div( |
256 | ! |
tags$label("Encodings", class = "text-primary"), |
257 | ! |
teal.transform::datanames_input(args$variables), |
258 | ! |
teal.transform::data_extract_ui( |
259 | ! |
id = ns("variables"), |
260 | ! |
label = "Variables", |
261 | ! |
data_extract_spec = args$variables, |
262 | ! |
is_single_dataset = is_single_dataset_value |
263 |
), |
|
264 | ! |
tags$hr(), |
265 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")), |
266 | ! |
bslib::accordion( |
267 | ! |
open = TRUE, |
268 | ! |
bslib::accordion_panel( |
269 | ! |
title = "Plot settings", |
270 | ! |
sliderInput( |
271 | ! |
ns("alpha"), "Opacity:", |
272 | ! |
min = 0, max = 1, |
273 | ! |
step = .05, value = .5, ticks = FALSE |
274 |
), |
|
275 | ! |
sliderInput( |
276 | ! |
ns("cex"), "Points size:", |
277 | ! |
min = 0.2, max = 3, |
278 | ! |
step = .05, value = .65, ticks = FALSE |
279 |
), |
|
280 | ! |
checkboxInput(ns("cor"), "Add Correlation", value = FALSE), |
281 | ! |
radioButtons( |
282 | ! |
ns("cor_method"), "Select Correlation Method", |
283 | ! |
choiceNames = c("Pearson", "Kendall", "Spearman"), |
284 | ! |
choiceValues = c("pearson", "kendall", "spearman"), |
285 | ! |
inline = TRUE |
286 |
), |
|
287 | ! |
checkboxInput(ns("cor_na_omit"), "Omit Missing Values", value = TRUE) |
288 |
) |
|
289 |
) |
|
290 |
), |
|
291 | ! |
forms = tagList( |
292 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
293 |
), |
|
294 | ! |
pre_output = args$pre_output, |
295 | ! |
post_output = args$post_output |
296 |
) |
|
297 |
} |
|
298 | ||
299 |
# Server function for the scatterplot matrix module |
|
300 |
srv_g_scatterplotmatrix <- function(id, |
|
301 |
data, |
|
302 |
variables, |
|
303 |
plot_height, |
|
304 |
plot_width, |
|
305 |
decorators) { |
|
306 | ! |
checkmate::assert_class(data, "reactive") |
307 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
308 | ! |
moduleServer(id, function(input, output, session) { |
309 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
310 | ||
311 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
312 | ! |
data_extract = list(variables = variables), |
313 | ! |
datasets = data, |
314 | ! |
select_validation_rule = list( |
315 | ! |
variables = ~ if (length(.) <= 1) "Please select at least 2 columns." |
316 |
) |
|
317 |
) |
|
318 | ||
319 | ! |
iv_r <- reactive({ |
320 | ! |
iv <- shinyvalidate::InputValidator$new() |
321 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
322 |
}) |
|
323 | ||
324 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
325 | ! |
datasets = data, |
326 | ! |
selector_list = selector_list |
327 |
) |
|
328 | ||
329 | ! |
anl_merged_q <- reactive({ |
330 | ! |
req(anl_merged_input()) |
331 | ! |
obj <- data() |
332 | ! |
teal.reporter::teal_card(obj) <- c( |
333 | ! |
teal.reporter::teal_card("# Scatter Plot Matrix"), |
334 | ! |
teal.reporter::teal_card(obj), |
335 | ! |
teal.reporter::teal_card("## Module's code") |
336 |
) |
|
337 | ! |
qenv <- teal.code::eval_code(obj, 'library("dplyr");library("lattice")') # nolint quotes |
338 | ! |
teal.code::eval_code(qenv, as.expression(anl_merged_input()$expr)) |
339 |
}) |
|
340 | ||
341 | ! |
merged <- list( |
342 | ! |
anl_input_r = anl_merged_input, |
343 | ! |
anl_q_r = anl_merged_q |
344 |
) |
|
345 | ||
346 |
# plot |
|
347 | ! |
output_q <- reactive({ |
348 | ! |
teal::validate_inputs(iv_r()) |
349 | ||
350 | ! |
qenv <- merged$anl_q_r() |
351 | ! |
ANL <- qenv[["ANL"]] |
352 | ||
353 | ! |
cols_names <- merged$anl_input_r()$columns_source$variables |
354 | ! |
alpha <- input$alpha |
355 | ! |
cex <- input$cex |
356 | ! |
add_cor <- input$cor |
357 | ! |
cor_method <- input$cor_method |
358 | ! |
cor_na_omit <- input$cor_na_omit |
359 | ||
360 | ! |
cor_na_action <- if (isTruthy(cor_na_omit)) { |
361 | ! |
"na.omit" |
362 |
} else { |
|
363 | ! |
"na.fail" |
364 |
} |
|
365 | ||
366 | ! |
teal::validate_has_data(ANL, 10) |
367 | ! |
teal::validate_has_data(ANL[, cols_names, drop = FALSE], 10, complete = TRUE, allow_inf = FALSE) |
368 | ||
369 |
# get labels and proper variable names |
|
370 | ! |
varnames <- varname_w_label(cols_names, ANL, wrap_width = 20) |
371 | ||
372 |
# check character columns. If any, then those are converted to factors |
|
373 | ! |
check_char <- vapply(ANL[, cols_names], is.character, logical(1)) |
374 | ! |
if (any(check_char)) { |
375 | ! |
qenv <- teal.code::eval_code( |
376 | ! |
qenv, |
377 | ! |
substitute( |
378 | ! |
expr = ANL <- ANL[, cols_names] %>% |
379 | ! |
dplyr::mutate_if(is.character, as.factor) %>% |
380 | ! |
droplevels(), |
381 | ! |
env = list(cols_names = cols_names) |
382 |
) |
|
383 |
) |
|
384 |
} else { |
|
385 | ! |
qenv <- teal.code::eval_code( |
386 | ! |
qenv, |
387 | ! |
substitute( |
388 | ! |
expr = ANL <- ANL[, cols_names] %>% |
389 | ! |
droplevels(), |
390 | ! |
env = list(cols_names = cols_names) |
391 |
) |
|
392 |
) |
|
393 |
} |
|
394 | ||
395 | ||
396 |
# create plot |
|
397 | ! |
teal.reporter::teal_card(qenv) <- c(teal.reporter::teal_card(qenv), "## Plot") |
398 | ||
399 | ! |
if (add_cor) { |
400 | ! |
shinyjs::show("cor_method") |
401 | ! |
shinyjs::show("cor_use") |
402 | ! |
shinyjs::show("cor_na_omit") |
403 | ||
404 | ! |
qenv <- teal.code::eval_code( |
405 | ! |
qenv, |
406 | ! |
substitute( |
407 | ! |
expr = { |
408 | ! |
plot <- lattice::splom( |
409 | ! |
ANL, |
410 | ! |
varnames = varnames_value, |
411 | ! |
panel = function(x, y, ...) { |
412 | ! |
lattice::panel.splom(x = x, y = y, ...) |
413 | ! |
cpl <- lattice::current.panel.limits() |
414 | ! |
lattice::panel.text( |
415 | ! |
mean(cpl$xlim), |
416 | ! |
mean(cpl$ylim), |
417 | ! |
get_scatterplotmatrix_stats( |
418 | ! |
x, |
419 | ! |
y, |
420 | ! |
.f = stats::cor.test, |
421 | ! |
.f_args = list(method = cor_method, na.action = cor_na_action) |
422 |
), |
|
423 | ! |
alpha = 0.6, |
424 | ! |
fontsize = 18, |
425 | ! |
fontface = "bold" |
426 |
) |
|
427 |
}, |
|
428 | ! |
pch = 16, |
429 | ! |
alpha = alpha_value, |
430 | ! |
cex = cex_value |
431 |
) |
|
432 |
}, |
|
433 | ! |
env = list( |
434 | ! |
varnames_value = varnames, |
435 | ! |
cor_method = cor_method, |
436 | ! |
cor_na_action = cor_na_action, |
437 | ! |
alpha_value = alpha, |
438 | ! |
cex_value = cex |
439 |
) |
|
440 |
) |
|
441 |
) |
|
442 |
} else { |
|
443 | ! |
shinyjs::hide("cor_method") |
444 | ! |
shinyjs::hide("cor_use") |
445 | ! |
shinyjs::hide("cor_na_omit") |
446 | ! |
qenv <- teal.code::eval_code( |
447 | ! |
qenv, |
448 | ! |
substitute( |
449 | ! |
expr = { |
450 | ! |
plot <- lattice::splom( |
451 | ! |
ANL, |
452 | ! |
varnames = varnames_value, |
453 | ! |
pch = 16, |
454 | ! |
alpha = alpha_value, |
455 | ! |
cex = cex_value |
456 |
) |
|
457 |
}, |
|
458 | ! |
env = list(varnames_value = varnames, alpha_value = alpha, cex_value = cex) |
459 |
) |
|
460 |
) |
|
461 |
} |
|
462 | ! |
qenv |
463 |
}) |
|
464 | ||
465 | ! |
decorated_output_q <- srv_decorate_teal_data( |
466 | ! |
id = "decorator", |
467 | ! |
data = output_q, |
468 | ! |
decorators = select_decorators(decorators, "plot"), |
469 | ! |
expr = quote(plot) |
470 |
) |
|
471 | ||
472 | ! |
plot_r <- reactive(req(decorated_output_q())[["plot"]]) |
473 | ||
474 |
# Insert the plot into a plot_with_settings module |
|
475 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
476 | ! |
id = "myplot", |
477 | ! |
plot_r = plot_r, |
478 | ! |
height = plot_height, |
479 | ! |
width = plot_width |
480 |
) |
|
481 | ||
482 | ! |
decorated_output_dims_q <- set_chunk_dims(pws, decorated_output_q) |
483 | ||
484 |
# show a message if conversion to factors took place |
|
485 | ! |
output$message <- renderText({ |
486 | ! |
req(iv_r()$is_valid()) |
487 | ! |
req(selector_list()$variables()) |
488 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
489 | ! |
cols_names <- unique(unname(do.call(c, merged$anl_input_r()$columns_source))) |
490 | ! |
check_char <- vapply(ANL[, cols_names], is.character, logical(1)) |
491 | ! |
if (any(check_char)) { |
492 | ! |
is_single <- sum(check_char) == 1 |
493 | ! |
paste( |
494 | ! |
"Character", |
495 | ! |
ifelse(is_single, "variable", "variables"), |
496 | ! |
paste0("(", paste(cols_names[check_char], collapse = ", "), ")"), |
497 | ! |
ifelse(is_single, "was", "were"), |
498 | ! |
"converted to", |
499 | ! |
ifelse(is_single, "factor.", "factors.") |
500 |
) |
|
501 |
} else { |
|
502 |
"" |
|
503 |
} |
|
504 |
}) |
|
505 | ||
506 |
# Render R code. |
|
507 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_output_dims_q()))) |
508 | ||
509 | ! |
teal.widgets::verbatim_popup_srv( |
510 | ! |
id = "rcode", |
511 | ! |
verbatim_content = source_code_r, |
512 | ! |
title = "Show R Code for Scatterplotmatrix" |
513 |
) |
|
514 | ! |
decorated_output_dims_q |
515 |
}) |
|
516 |
} |
|
517 | ||
518 |
#' Get stats for x-y pairs in scatterplot matrix |
|
519 |
#' |
|
520 |
#' Uses [stats::cor.test()] per default for all numerical input variables and converts results |
|
521 |
#' to character vector. |
|
522 |
#' Could be extended if different stats for different variable types are needed. |
|
523 |
#' Meant to be called from [lattice::panel.text()]. |
|
524 |
#' |
|
525 |
#' Presently we need to use a formula input for `stats::cor.test` because |
|
526 |
#' `na.fail` only gets evaluated when a formula is passed (see below). |
|
527 |
#' ``` |
|
528 |
#' x = c(1,3,5,7,NA) |
|
529 |
#' y = c(3,6,7,8,1) |
|
530 |
#' stats::cor.test(x, y, na.action = "na.fail") |
|
531 |
#' stats::cor.test(~ x + y, na.action = "na.fail") |
|
532 |
#' ``` |
|
533 |
#' |
|
534 |
#' @param x,y (`numeric`) vectors of data values. `x` and `y` must have the same length. |
|
535 |
#' @param .f (`function`) function that accepts x and y as formula input `~ x + y`. |
|
536 |
#' Default `stats::cor.test`. |
|
537 |
#' @param .f_args (`list`) of arguments to be passed to `.f`. |
|
538 |
#' @param round_stat (`integer(1)`) optional, number of decimal places to use when rounding the estimate. |
|
539 |
#' @param round_pval (`integer(1)`) optional, number of decimal places to use when rounding the p-value. |
|
540 |
#' |
|
541 |
#' @return Character with stats. For [stats::cor.test()] correlation coefficient and p-value. |
|
542 |
#' |
|
543 |
#' @examples |
|
544 |
#' set.seed(1) |
|
545 |
#' x <- runif(25, 0, 1) |
|
546 |
#' y <- runif(25, 0, 1) |
|
547 |
#' x[c(3, 10, 18)] <- NA |
|
548 |
#' |
|
549 |
#' get_scatterplotmatrix_stats(x, y, .f = stats::cor.test, .f_args = list(method = "pearson")) |
|
550 |
#' get_scatterplotmatrix_stats(x, y, .f = stats::cor.test, .f_args = list( |
|
551 |
#' method = "pearson", |
|
552 |
#' na.action = na.fail |
|
553 |
#' )) |
|
554 |
#' |
|
555 |
#' @export |
|
556 |
#' |
|
557 |
get_scatterplotmatrix_stats <- function(x, y, |
|
558 |
.f = stats::cor.test, |
|
559 |
.f_args = list(), |
|
560 |
round_stat = 2, |
|
561 |
round_pval = 4) { |
|
562 | 6x |
if (is.numeric(x) && is.numeric(y)) { |
563 | 3x |
stat <- tryCatch(do.call(.f, c(list(~ x + y), .f_args)), error = function(e) NA) |
564 | ||
565 | 3x |
if (anyNA(stat)) { |
566 | 1x |
return("NA") |
567 | 2x |
} else if (all(c("estimate", "p.value") %in% names(stat))) { |
568 | 2x |
return(paste( |
569 | 2x |
c( |
570 | 2x |
paste0(names(stat$estimate), ":", round(stat$estimate, round_stat)), |
571 | 2x |
paste0("P:", round(stat$p.value, round_pval)) |
572 |
), |
|
573 | 2x |
collapse = "\n" |
574 |
)) |
|
575 |
} else { |
|
576 | ! |
stop("function not supported") |
577 |
} |
|
578 |
} else { |
|
579 | 3x |
if ("method" %in% names(.f_args)) { |
580 | 3x |
if (.f_args$method == "pearson") { |
581 | 1x |
return("cor:-") |
582 |
} |
|
583 | 2x |
if (.f_args$method == "kendall") { |
584 | 1x |
return("tau:-") |
585 |
} |
|
586 | 1x |
if (.f_args$method == "spearman") { |
587 | 1x |
return("rho:-") |
588 |
} |
|
589 |
} |
|
590 | ! |
return("-") |
591 |
} |
|
592 |
} |
1 |
#' `teal` module: Scatterplot and regression analysis |
|
2 |
#' |
|
3 |
#' Module for visualizing regression analysis, including scatterplots and |
|
4 |
#' various regression diagnostics plots. |
|
5 |
#' It allows users to explore the relationship between a set of regressors and a response variable, |
|
6 |
#' visualize residuals, and identify outliers. |
|
7 |
#' |
|
8 |
#' @note For more examples, please see the vignette "Using regression plots" via |
|
9 |
#' `vignette("using-regression-plots", package = "teal.modules.general")`. |
|
10 |
#' |
|
11 |
#' @inheritParams teal::module |
|
12 |
#' @inheritParams shared_params |
|
13 |
#' @param regressor (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
14 |
#' Regressor variables from an incoming dataset with filtering and selecting. |
|
15 |
#' @param response (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
16 |
#' Response variables from an incoming dataset with filtering and selecting. |
|
17 |
#' @param default_outlier_label (`character`) optional, default column selected to label outliers. |
|
18 |
#' @param default_plot_type (`numeric`) optional, defaults to "Response vs Regressor". |
|
19 |
#' 1. Response vs Regressor |
|
20 |
#' 2. Residuals vs Fitted |
|
21 |
#' 3. Normal Q-Q |
|
22 |
#' 4. Scale-Location |
|
23 |
#' 5. Cook's distance |
|
24 |
#' 6. Residuals vs Leverage |
|
25 |
#' 7. Cook's dist vs Leverage |
|
26 |
#' @param label_segment_threshold (`numeric(1)` or `numeric(3)`) |
|
27 |
#' Minimum distance between label and point on the plot that triggers the creation of |
|
28 |
#' a line segment between the two. |
|
29 |
#' This may happen when the label cannot be placed next to the point as it overlaps another |
|
30 |
#' label or point. |
|
31 |
#' The value is used as the `min.segment.length` parameter to the [ggrepel::geom_text_repel()] function. |
|
32 |
#' |
|
33 |
#' It can take the following forms: |
|
34 |
#' - `numeric(1)`: Fixed value used for the minimum distance and the slider is not presented in the UI. |
|
35 |
#' - `numeric(3)`: A slider is presented in the UI (under "Plot settings") to adjust the minimum distance dynamically. |
|
36 |
#' |
|
37 |
#' It takes the form of `c(value, min, max)` and it is passed to the `value_min_max` |
|
38 |
#' argument in `teal.widgets::optionalSliderInputValMinMax`. |
|
39 |
#' |
|
40 |
# nolint start: line_length. |
|
41 |
#' @param ggplot2_args `r roxygen_ggplot2_args_param("Response vs Regressor", "Residuals vs Fitted", "Scale-Location", "Cook's distance", "Residuals vs Leverage", "Cook's dist vs Leverage")` |
|
42 |
# nolint end: line_length. |
|
43 |
#' |
|
44 |
#' @inherit shared_params return |
|
45 |
#' |
|
46 |
#' @section Decorating Module: |
|
47 |
#' |
|
48 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
49 |
#' - `plot` (`ggplot`) |
|
50 |
#' |
|
51 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
52 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
53 |
#' See code snippet below: |
|
54 |
#' |
|
55 |
#' ``` |
|
56 |
#' tm_a_regression( |
|
57 |
#' ..., # arguments for module |
|
58 |
#' decorators = list( |
|
59 |
#' plot = teal_transform_module(...) # applied to the `plot` output |
|
60 |
#' ) |
|
61 |
#' ) |
|
62 |
#' ``` |
|
63 |
#' |
|
64 |
#' For additional details and examples of decorators, refer to the vignette |
|
65 |
#' `vignette("decorate-module-output", package = "teal.modules.general")`. |
|
66 |
#' |
|
67 |
#' To learn more please refer to the vignette |
|
68 |
#' `vignette("transform-module-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
69 |
#' |
|
70 |
#' @inheritSection teal::example_module Reporting |
|
71 |
#' |
|
72 |
#' @examplesShinylive |
|
73 |
#' library(teal.modules.general) |
|
74 |
#' interactive <- function() TRUE |
|
75 |
#' {{ next_example }} |
|
76 |
#' @examples |
|
77 |
#' |
|
78 |
#' # general data example |
|
79 |
#' data <- teal_data() |
|
80 |
#' data <- within(data, { |
|
81 |
#' require(nestcolor) |
|
82 |
#' CO2 <- CO2 |
|
83 |
#' }) |
|
84 |
#' |
|
85 |
#' app <- init( |
|
86 |
#' data = data, |
|
87 |
#' modules = modules( |
|
88 |
#' tm_a_regression( |
|
89 |
#' label = "Regression", |
|
90 |
#' response = data_extract_spec( |
|
91 |
#' dataname = "CO2", |
|
92 |
#' select = select_spec( |
|
93 |
#' label = "Select variable:", |
|
94 |
#' choices = "uptake", |
|
95 |
#' selected = "uptake", |
|
96 |
#' multiple = FALSE, |
|
97 |
#' fixed = TRUE |
|
98 |
#' ) |
|
99 |
#' ), |
|
100 |
#' regressor = data_extract_spec( |
|
101 |
#' dataname = "CO2", |
|
102 |
#' select = select_spec( |
|
103 |
#' label = "Select variables:", |
|
104 |
#' choices = variable_choices(data[["CO2"]], c("conc", "Treatment")), |
|
105 |
#' selected = "conc", |
|
106 |
#' multiple = TRUE, |
|
107 |
#' fixed = FALSE |
|
108 |
#' ) |
|
109 |
#' ) |
|
110 |
#' ) |
|
111 |
#' ) |
|
112 |
#' ) |
|
113 |
#' if (interactive()) { |
|
114 |
#' shinyApp(app$ui, app$server) |
|
115 |
#' } |
|
116 |
#' |
|
117 |
#' @examplesShinylive |
|
118 |
#' library(teal.modules.general) |
|
119 |
#' interactive <- function() TRUE |
|
120 |
#' {{ next_example }} |
|
121 |
#' @examples |
|
122 |
#' # CDISC data example |
|
123 |
#' data <- teal_data() |
|
124 |
#' data <- within(data, { |
|
125 |
#' require(nestcolor) |
|
126 |
#' ADSL <- teal.data::rADSL |
|
127 |
#' }) |
|
128 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
129 |
#' |
|
130 |
#' app <- init( |
|
131 |
#' data = data, |
|
132 |
#' modules = modules( |
|
133 |
#' tm_a_regression( |
|
134 |
#' label = "Regression", |
|
135 |
#' response = data_extract_spec( |
|
136 |
#' dataname = "ADSL", |
|
137 |
#' select = select_spec( |
|
138 |
#' label = "Select variable:", |
|
139 |
#' choices = "BMRKR1", |
|
140 |
#' selected = "BMRKR1", |
|
141 |
#' multiple = FALSE, |
|
142 |
#' fixed = TRUE |
|
143 |
#' ) |
|
144 |
#' ), |
|
145 |
#' regressor = data_extract_spec( |
|
146 |
#' dataname = "ADSL", |
|
147 |
#' select = select_spec( |
|
148 |
#' label = "Select variables:", |
|
149 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "SEX", "RACE")), |
|
150 |
#' selected = "AGE", |
|
151 |
#' multiple = TRUE, |
|
152 |
#' fixed = FALSE |
|
153 |
#' ) |
|
154 |
#' ) |
|
155 |
#' ) |
|
156 |
#' ) |
|
157 |
#' ) |
|
158 |
#' if (interactive()) { |
|
159 |
#' shinyApp(app$ui, app$server) |
|
160 |
#' } |
|
161 |
#' |
|
162 |
#' @export |
|
163 |
#' |
|
164 |
tm_a_regression <- function(label = "Regression Analysis", |
|
165 |
regressor, |
|
166 |
response, |
|
167 |
plot_height = c(600, 200, 2000), |
|
168 |
plot_width = NULL, |
|
169 |
alpha = c(1, 0, 1), |
|
170 |
size = c(2, 1, 8), |
|
171 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
172 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
173 |
pre_output = NULL, |
|
174 |
post_output = NULL, |
|
175 |
default_plot_type = 1, |
|
176 |
default_outlier_label = "USUBJID", |
|
177 |
label_segment_threshold = c(0.5, 0, 10), |
|
178 |
transformators = list(), |
|
179 |
decorators = list()) { |
|
180 | ! |
message("Initializing tm_a_regression") |
181 | ||
182 |
# Normalize the parameters |
|
183 | ! |
if (inherits(regressor, "data_extract_spec")) regressor <- list(regressor) |
184 | ! |
if (inherits(response, "data_extract_spec")) response <- list(response) |
185 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
186 | ||
187 |
# Start of assertions |
|
188 | ! |
checkmate::assert_string(label) |
189 | ! |
checkmate::assert_list(regressor, types = "data_extract_spec") |
190 | ||
191 | ! |
checkmate::assert_list(response, types = "data_extract_spec") |
192 | ! |
assert_single_selection(response) |
193 | ||
194 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
195 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
196 | ||
197 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
198 | ! |
checkmate::assert_numeric( |
199 | ! |
plot_width[1], |
200 | ! |
lower = plot_width[2], |
201 | ! |
upper = plot_width[3], |
202 | ! |
null.ok = TRUE, |
203 | ! |
.var.name = "plot_width" |
204 |
) |
|
205 | ||
206 | ! |
if (length(alpha) == 1) { |
207 | ! |
checkmate::assert_numeric(alpha, any.missing = FALSE, finite = TRUE) |
208 |
} else { |
|
209 | ! |
checkmate::assert_numeric(alpha, len = 3, any.missing = FALSE, finite = TRUE) |
210 | ! |
checkmate::assert_numeric(alpha[1], lower = alpha[2], upper = alpha[3], .var.name = "alpha") |
211 |
} |
|
212 | ||
213 | ! |
if (length(size) == 1) { |
214 | ! |
checkmate::assert_numeric(size, any.missing = FALSE, finite = TRUE) |
215 |
} else { |
|
216 | ! |
checkmate::assert_numeric(size, len = 3, any.missing = FALSE, finite = TRUE) |
217 | ! |
checkmate::assert_numeric(size[1], lower = size[2], upper = size[3], .var.name = "size") |
218 |
} |
|
219 | ||
220 | ! |
ggtheme <- match.arg(ggtheme) |
221 | ||
222 | ! |
plot_choices <- c( |
223 | ! |
"Response vs Regressor", "Residuals vs Fitted", "Normal Q-Q", "Scale-Location", |
224 | ! |
"Cook's distance", "Residuals vs Leverage", "Cook's dist vs Leverage" |
225 |
) |
|
226 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
227 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
228 | ||
229 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
230 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
231 | ! |
checkmate::assert_choice(default_plot_type, seq.int(1L, length(plot_choices))) |
232 | ! |
checkmate::assert_string(default_outlier_label) |
233 | ! |
checkmate::assert_list(decorators, "teal_transform_module") |
234 | ||
235 | ! |
if (length(label_segment_threshold) == 1) { |
236 | ! |
checkmate::assert_numeric(label_segment_threshold, any.missing = FALSE, finite = TRUE) |
237 |
} else { |
|
238 | ! |
checkmate::assert_numeric(label_segment_threshold, len = 3, any.missing = FALSE, finite = TRUE) |
239 | ! |
checkmate::assert_numeric( |
240 | ! |
label_segment_threshold[1], |
241 | ! |
lower = label_segment_threshold[2], |
242 | ! |
upper = label_segment_threshold[3], |
243 | ! |
.var.name = "label_segment_threshold" |
244 |
) |
|
245 |
} |
|
246 | ! |
assert_decorators(decorators, "plot") |
247 |
# End of assertions |
|
248 | ||
249 |
# Make UI args |
|
250 | ! |
args <- as.list(environment()) |
251 | ! |
args[["plot_choices"]] <- plot_choices |
252 | ! |
data_extract_list <- list( |
253 | ! |
regressor = regressor, |
254 | ! |
response = response |
255 |
) |
|
256 | ||
257 | ! |
ans <- module( |
258 | ! |
label = label, |
259 | ! |
server = srv_a_regression, |
260 | ! |
ui = ui_a_regression, |
261 | ! |
ui_args = args, |
262 | ! |
server_args = c( |
263 | ! |
data_extract_list, |
264 | ! |
list( |
265 | ! |
plot_height = plot_height, |
266 | ! |
plot_width = plot_width, |
267 | ! |
default_outlier_label = default_outlier_label, |
268 | ! |
ggplot2_args = ggplot2_args, |
269 | ! |
decorators = decorators |
270 |
) |
|
271 |
), |
|
272 | ! |
transformators = transformators, |
273 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
274 |
) |
|
275 | ! |
attr(ans, "teal_bookmarkable") <- FALSE |
276 | ! |
ans |
277 |
} |
|
278 | ||
279 |
# UI function for the regression module |
|
280 |
ui_a_regression <- function(id, ...) { |
|
281 | ! |
ns <- NS(id) |
282 | ! |
args <- list(...) |
283 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$regressor, args$response) |
284 | ! |
teal.widgets::standard_layout( |
285 | ! |
output = teal.widgets::white_small_well(tags$div( |
286 | ! |
teal.widgets::plot_with_settings_ui(id = ns("myplot")), |
287 | ! |
tags$div(verbatimTextOutput(ns("text"))) |
288 |
)), |
|
289 | ! |
encoding = tags$div( |
290 | ! |
tags$label("Encodings", class = "text-primary"), tags$br(), |
291 | ! |
teal.transform::datanames_input(args[c("response", "regressor")]), |
292 | ! |
teal.transform::data_extract_ui( |
293 | ! |
id = ns("response"), |
294 | ! |
label = "Response variable", |
295 | ! |
data_extract_spec = args$response, |
296 | ! |
is_single_dataset = is_single_dataset_value |
297 |
), |
|
298 | ! |
teal.transform::data_extract_ui( |
299 | ! |
id = ns("regressor"), |
300 | ! |
label = "Regressor variables", |
301 | ! |
data_extract_spec = args$regressor, |
302 | ! |
is_single_dataset = is_single_dataset_value |
303 |
), |
|
304 | ! |
radioButtons( |
305 | ! |
ns("plot_type"), |
306 | ! |
label = "Plot type:", |
307 | ! |
choices = args$plot_choices, |
308 | ! |
selected = args$plot_choices[args$default_plot_type] |
309 |
), |
|
310 | ! |
checkboxInput(ns("show_outlier"), label = "Display outlier labels", value = TRUE), |
311 | ! |
conditionalPanel( |
312 | ! |
condition = "input['show_outlier']", |
313 | ! |
ns = ns, |
314 | ! |
teal.widgets::optionalSliderInput( |
315 | ! |
ns("outlier"), |
316 | ! |
tags$div( |
317 | ! |
tagList( |
318 | ! |
"Outlier definition:", |
319 | ! |
bslib::tooltip( |
320 | ! |
icon("fas fa-circle-info"), |
321 | ! |
paste( |
322 | ! |
"Use the slider to choose the cut-off value to define outliers.", |
323 | ! |
"Points with a Cook's distance greater than", |
324 | ! |
"the value on the slider times the mean of the Cook's distance of the dataset will have labels." |
325 |
) |
|
326 |
) |
|
327 |
) |
|
328 |
), |
|
329 | ! |
min = 1, max = 10, value = 9, ticks = FALSE, step = .1 |
330 |
), |
|
331 | ! |
teal.widgets::optionalSelectInput( |
332 | ! |
ns("label_var"), |
333 | ! |
multiple = FALSE, |
334 | ! |
label = "Outlier label" |
335 |
) |
|
336 |
), |
|
337 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")), |
338 | ! |
bslib::accordion( |
339 | ! |
open = TRUE, |
340 | ! |
bslib::accordion_panel( |
341 | ! |
title = "Plot settings", |
342 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("alpha"), "Opacity:", args$alpha, ticks = FALSE), |
343 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("size"), "Points size:", args$size, ticks = FALSE), |
344 | ! |
teal.widgets::optionalSliderInputValMinMax( |
345 | ! |
inputId = ns("label_min_segment"), |
346 | ! |
label = tags$div( |
347 | ! |
tagList( |
348 | ! |
"Label min. segment:", |
349 | ! |
bslib::tooltip( |
350 | ! |
icon("circle-info"), |
351 | ! |
tags$span( |
352 | ! |
paste( |
353 | ! |
"Use the slider to choose the cut-off value to define minimum distance between label and point", |
354 | ! |
"that generates a line segment.", |
355 | ! |
"It's only valid when 'Display outlier labels' is checked." |
356 |
) |
|
357 |
) |
|
358 |
) |
|
359 |
) |
|
360 |
), |
|
361 | ! |
value_min_max = args$label_segment_threshold, |
362 |
# Extra parameters to sliderInput |
|
363 | ! |
ticks = FALSE, |
364 | ! |
step = .1, |
365 | ! |
round = FALSE |
366 |
), |
|
367 | ! |
selectInput( |
368 | ! |
inputId = ns("ggtheme"), |
369 | ! |
label = "Theme (by ggplot):", |
370 | ! |
choices = ggplot_themes, |
371 | ! |
selected = args$ggtheme, |
372 | ! |
multiple = FALSE |
373 |
) |
|
374 |
) |
|
375 |
) |
|
376 |
), |
|
377 | ! |
forms = tagList( |
378 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
379 |
), |
|
380 | ! |
pre_output = args$pre_output, |
381 | ! |
post_output = args$post_output |
382 |
) |
|
383 |
} |
|
384 | ||
385 |
# Server function for the regression module |
|
386 |
srv_a_regression <- function(id, |
|
387 |
data, |
|
388 |
response, |
|
389 |
regressor, |
|
390 |
plot_height, |
|
391 |
plot_width, |
|
392 |
ggplot2_args, |
|
393 |
default_outlier_label, |
|
394 |
decorators) { |
|
395 | ! |
checkmate::assert_class(data, "reactive") |
396 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
397 | ! |
moduleServer(id, function(input, output, session) { |
398 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
399 | ||
400 | ! |
ns <- session$ns |
401 | ||
402 | ! |
rule_rvr1 <- function(value) { |
403 | ! |
if (isTRUE(input$plot_type == "Response vs Regressor")) { |
404 | ! |
if (length(value) > 1L) { |
405 | ! |
"This plot can only have one regressor." |
406 |
} |
|
407 |
} |
|
408 |
} |
|
409 | ! |
rule_rvr2 <- function(other) { |
410 | ! |
function(value) { |
411 | ! |
if (isTRUE(input$plot_type == "Response vs Regressor")) { |
412 | ! |
otherval <- selector_list()[[other]]()$select |
413 | ! |
if (isTRUE(value == otherval)) { |
414 | ! |
"Response and Regressor must be different." |
415 |
} |
|
416 |
} |
|
417 |
} |
|
418 |
} |
|
419 | ||
420 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
421 | ! |
data_extract = list(response = response, regressor = regressor), |
422 | ! |
datasets = data, |
423 | ! |
select_validation_rule = list( |
424 | ! |
regressor = shinyvalidate::compose_rules( |
425 | ! |
shinyvalidate::sv_required("At least one regressor should be selected."), |
426 | ! |
rule_rvr1, |
427 | ! |
rule_rvr2("response") |
428 |
), |
|
429 | ! |
response = shinyvalidate::compose_rules( |
430 | ! |
shinyvalidate::sv_required("At least one response should be selected."), |
431 | ! |
rule_rvr2("regressor") |
432 |
) |
|
433 |
) |
|
434 |
) |
|
435 | ||
436 | ! |
iv_r <- reactive({ |
437 | ! |
iv <- shinyvalidate::InputValidator$new() |
438 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
439 |
}) |
|
440 | ||
441 | ! |
iv_out <- shinyvalidate::InputValidator$new() |
442 | ! |
iv_out$condition(~ isTRUE(input$show_outlier)) |
443 | ! |
iv_out$add_rule("label_var", shinyvalidate::sv_required("Please provide an `Outlier label` variable")) |
444 | ! |
iv_out$enable() |
445 | ||
446 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
447 | ! |
selector_list = selector_list, |
448 | ! |
datasets = data |
449 |
) |
|
450 | ||
451 | ! |
regression_var <- reactive({ |
452 | ! |
teal::validate_inputs(iv_r()) |
453 | ||
454 | ! |
list( |
455 | ! |
response = as.vector(anl_merged_input()$columns_source$response), |
456 | ! |
regressor = as.vector(anl_merged_input()$columns_source$regressor) |
457 |
) |
|
458 |
}) |
|
459 | ||
460 | ! |
qenv <- reactive({ |
461 | ! |
obj <- data() |
462 | ! |
teal.reporter::teal_card(obj) <- |
463 | ! |
c( |
464 | ! |
teal.reporter::teal_card("# Linear Regression Plot"), |
465 | ! |
teal.reporter::teal_card(obj), |
466 | ! |
teal.reporter::teal_card("## Module's code") |
467 |
) |
|
468 | ! |
teal.code::eval_code(obj, 'library("ggplot2");library("dplyr")') # nolint: quotes |
469 |
}) |
|
470 | ||
471 | ! |
anl_merged_q <- reactive({ |
472 | ! |
req(anl_merged_input()) |
473 | ! |
qenv() %>% |
474 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
475 |
}) |
|
476 | ||
477 |
# sets qenv object and populates it with data merge call and fit expression |
|
478 | ! |
fit_r <- reactive({ |
479 | ! |
ANL <- anl_merged_q()[["ANL"]] |
480 | ! |
teal::validate_has_data(ANL, 10) |
481 | ||
482 | ! |
validate(need(is.numeric(ANL[regression_var()$response][[1]]), "Response variable should be numeric.")) |
483 | ||
484 | ! |
teal::validate_has_data( |
485 | ! |
ANL[, c(regression_var()$response, regression_var()$regressor)], 10, |
486 | ! |
complete = TRUE, allow_inf = FALSE |
487 |
) |
|
488 | ||
489 | ! |
form <- stats::as.formula( |
490 | ! |
paste( |
491 | ! |
regression_var()$response, |
492 | ! |
paste( |
493 | ! |
regression_var()$regressor, |
494 | ! |
collapse = " + " |
495 |
), |
|
496 | ! |
sep = " ~ " |
497 |
) |
|
498 |
) |
|
499 | ||
500 | ! |
if (input$show_outlier) { |
501 | ! |
opts <- teal.transform::variable_choices(ANL) |
502 | ! |
selected <- if (!is.null(isolate(input$label_var)) && isolate(input$label_var) %in% as.character(opts)) { |
503 | ! |
isolate(input$label_var) |
504 |
} else { |
|
505 | ! |
if (length(opts[as.character(opts) == default_outlier_label]) == 0) { |
506 | ! |
opts[[1]] |
507 |
} else { |
|
508 | ! |
opts[as.character(opts) == default_outlier_label] |
509 |
} |
|
510 |
} |
|
511 | ! |
teal.widgets::updateOptionalSelectInput( |
512 | ! |
session = session, |
513 | ! |
inputId = "label_var", |
514 | ! |
choices = opts, |
515 | ! |
selected = restoreInput(ns("label_var"), selected) |
516 |
) |
|
517 | ||
518 | ! |
data <- ggplot2::fortify(stats::lm(form, data = ANL)) |
519 | ! |
cooksd <- data$.cooksd[!is.nan(data$.cooksd)] |
520 | ! |
max_outlier <- max(ceiling(max(cooksd) / mean(cooksd)), 2) |
521 | ! |
cur_outlier <- isolate(input$outlier) |
522 | ! |
updateSliderInput( |
523 | ! |
session = session, |
524 | ! |
inputId = "outlier", |
525 | ! |
min = 1, |
526 | ! |
max = max_outlier, |
527 | ! |
value = restoreInput(ns("outlier"), if (cur_outlier < max_outlier) cur_outlier else max_outlier * .9) |
528 |
) |
|
529 |
} |
|
530 | ||
531 | ! |
anl_fit <- anl_merged_q() %>% |
532 | ! |
teal.code::eval_code(substitute(fit <- stats::lm(form, data = ANL), env = list(form = form))) %>% |
533 | ! |
teal.code::eval_code(quote({ |
534 | ! |
for (regressor in names(fit$contrasts)) { |
535 | ! |
alts <- paste0(levels(ANL[[regressor]]), collapse = "|") |
536 | ! |
names(fit$coefficients) <- gsub( |
537 | ! |
paste0("^(", regressor, ")(", alts, ")$"), paste0("\\1", ": ", "\\2"), names(fit$coefficients) |
538 |
) |
|
539 |
} |
|
540 |
})) %>% |
|
541 | ! |
teal.code::eval_code(quote({ |
542 | ! |
fit_summary <- summary(fit) |
543 | ! |
fit_summary |
544 |
})) |
|
545 | ! |
teal.reporter::teal_card(anl_fit) <- c(teal.reporter::teal_card(anl_fit), "## Plot") |
546 | ! |
anl_fit |
547 |
}) |
|
548 | ||
549 | ! |
label_col <- reactive({ |
550 | ! |
teal::validate_inputs(iv_out) |
551 | ||
552 | ! |
substitute( |
553 | ! |
expr = dplyr::if_else( |
554 | ! |
data$.cooksd > outliers * mean(data$.cooksd, na.rm = TRUE), |
555 | ! |
as.character(stats::na.omit(ANL)[[label_var]]), |
556 |
"" |
|
557 |
) %>% |
|
558 | ! |
dplyr::if_else(is.na(.), "cooksd == NaN", .), |
559 | ! |
env = list(outliers = input$outlier, label_var = input$label_var) |
560 |
) |
|
561 |
}) |
|
562 | ||
563 | ! |
label_min_segment <- reactive({ |
564 | ! |
input$label_min_segment |
565 |
}) |
|
566 | ||
567 | ! |
outlier_label <- reactive({ |
568 | ! |
substitute( |
569 | ! |
expr = ggrepel::geom_text_repel( |
570 | ! |
label = label_col, |
571 | ! |
color = "red", |
572 | ! |
hjust = 0, |
573 | ! |
vjust = 1, |
574 | ! |
max.overlaps = Inf, |
575 | ! |
min.segment.length = label_min_segment, |
576 | ! |
segment.alpha = 0.5, |
577 | ! |
seed = 123 |
578 |
), |
|
579 | ! |
env = list(label_col = label_col(), label_min_segment = label_min_segment()) |
580 |
) |
|
581 |
}) |
|
582 | ||
583 | ! |
output_plot_base <- reactive({ |
584 | ! |
base_fit <- fit_r() |
585 | ! |
teal.code::eval_code( |
586 | ! |
base_fit, |
587 | ! |
quote({ |
588 | ! |
class(fit$residuals) <- NULL |
589 | ||
590 | ! |
data <- ggplot2::fortify(fit) |
591 | ||
592 | ! |
smooth <- function(x, y) { |
593 | ! |
as.data.frame(stats::lowess(x, y, f = 2 / 3, iter = 3)) |
594 |
} |
|
595 | ||
596 | ! |
smoothy_aes <- ggplot2::aes_string(x = "x", y = "y") |
597 | ||
598 | ! |
reg_form <- deparse(fit$call[[2]]) |
599 |
}) |
|
600 |
) |
|
601 |
}) |
|
602 | ||
603 | ! |
output_plot_0 <- reactive({ |
604 | ! |
fit <- fit_r()[["fit"]] |
605 | ! |
ANL <- anl_merged_q()[["ANL"]] |
606 | ||
607 | ! |
stopifnot(ncol(fit$model) == 2) |
608 | ||
609 | ! |
if (!is.factor(ANL[[regression_var()$regressor]])) { |
610 | ! |
shinyjs::show("size") |
611 | ! |
shinyjs::show("alpha") |
612 | ! |
plot <- substitute( |
613 | ! |
expr = ggplot2::ggplot(fit$model[, 2:1], ggplot2::aes_string(regressor, response)) + |
614 | ! |
ggplot2::geom_point(size = size, alpha = alpha) + |
615 | ! |
ggplot2::stat_smooth(method = "lm", formula = y ~ x, se = FALSE), |
616 | ! |
env = list( |
617 | ! |
regressor = regression_var()$regressor, |
618 | ! |
response = regression_var()$response, |
619 | ! |
size = input$size, |
620 | ! |
alpha = input$alpha |
621 |
) |
|
622 |
) |
|
623 | ! |
if (input$show_outlier) { |
624 | ! |
plot <- substitute( |
625 | ! |
expr = plot + outlier_label, |
626 | ! |
env = list(plot = plot, outlier_label = outlier_label()) |
627 |
) |
|
628 |
} |
|
629 |
} else { |
|
630 | ! |
shinyjs::hide("size") |
631 | ! |
shinyjs::hide("alpha") |
632 | ! |
plot <- substitute( |
633 | ! |
expr = ggplot2::ggplot(fit$model[, 2:1], ggplot2::aes_string(regressor, response)) + |
634 | ! |
ggplot2::geom_boxplot(), |
635 | ! |
env = list(regressor = regression_var()$regressor, response = regression_var()$response) |
636 |
) |
|
637 | ! |
if (input$show_outlier) { |
638 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
639 |
} |
|
640 |
} |
|
641 | ||
642 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
643 | ! |
teal.widgets::resolve_ggplot2_args( |
644 | ! |
user_plot = ggplot2_args[["Response vs Regressor"]], |
645 | ! |
user_default = ggplot2_args$default, |
646 | ! |
module_plot = teal.widgets::ggplot2_args( |
647 | ! |
labs = list( |
648 | ! |
title = "Response vs Regressor", |
649 | ! |
x = varname_w_label(regression_var()$regressor, ANL), |
650 | ! |
y = varname_w_label(regression_var()$response, ANL) |
651 |
), |
|
652 | ! |
theme = list() |
653 |
) |
|
654 |
), |
|
655 | ! |
ggtheme = input$ggtheme |
656 |
) |
|
657 | ||
658 | ! |
teal.code::eval_code( |
659 | ! |
fit_r(), |
660 | ! |
substitute( |
661 | ! |
expr = { |
662 | ! |
class(fit$residuals) <- NULL |
663 | ! |
data <- ggplot2::fortify(fit) |
664 | ! |
plot <- graph |
665 |
}, |
|
666 | ! |
env = list( |
667 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
668 |
) |
|
669 |
) |
|
670 |
) |
|
671 |
}) |
|
672 | ||
673 | ! |
output_plot_1 <- reactive({ |
674 | ! |
plot_base <- output_plot_base() |
675 | ! |
shinyjs::show("size") |
676 | ! |
shinyjs::show("alpha") |
677 | ! |
plot <- substitute( |
678 | ! |
expr = ggplot2::ggplot(data = data, ggplot2::aes(.fitted, .resid)) + |
679 | ! |
ggplot2::geom_point(size = size, alpha = alpha) + |
680 | ! |
ggplot2::geom_hline(yintercept = 0, linetype = "dashed", size = 1) + |
681 | ! |
ggplot2::geom_line(data = smoothy, mapping = smoothy_aes), |
682 | ! |
env = list(size = input$size, alpha = input$alpha) |
683 |
) |
|
684 | ! |
if (input$show_outlier) { |
685 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
686 |
} |
|
687 | ||
688 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
689 | ! |
teal.widgets::resolve_ggplot2_args( |
690 | ! |
user_plot = ggplot2_args[["Residuals vs Fitted"]], |
691 | ! |
user_default = ggplot2_args$default, |
692 | ! |
module_plot = teal.widgets::ggplot2_args( |
693 | ! |
labs = list( |
694 | ! |
x = quote(paste0("Fitted values\nlm(", reg_form, ")")), |
695 | ! |
y = "Residuals", |
696 | ! |
title = "Residuals vs Fitted" |
697 |
) |
|
698 |
) |
|
699 |
), |
|
700 | ! |
ggtheme = input$ggtheme |
701 |
) |
|
702 | ||
703 | ! |
teal.code::eval_code( |
704 | ! |
plot_base, |
705 | ! |
substitute( |
706 | ! |
expr = { |
707 | ! |
smoothy <- smooth(data$.fitted, data$.resid) |
708 | ! |
plot <- graph |
709 |
}, |
|
710 | ! |
env = list( |
711 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
712 |
) |
|
713 |
) |
|
714 |
) |
|
715 |
}) |
|
716 | ||
717 | ! |
output_plot_2 <- reactive({ |
718 | ! |
shinyjs::show("size") |
719 | ! |
shinyjs::show("alpha") |
720 | ! |
plot_base <- output_plot_base() |
721 | ! |
plot <- substitute( |
722 | ! |
expr = ggplot2::ggplot(data = data, ggplot2::aes(sample = .stdresid)) + |
723 | ! |
ggplot2::stat_qq(size = size, alpha = alpha) + |
724 | ! |
ggplot2::geom_abline(linetype = "dashed"), |
725 | ! |
env = list(size = input$size, alpha = input$alpha) |
726 |
) |
|
727 | ! |
if (input$show_outlier) { |
728 | ! |
plot <- substitute( |
729 | ! |
expr = plot + |
730 | ! |
ggplot2::stat_qq( |
731 | ! |
geom = ggrepel::GeomTextRepel, |
732 | ! |
label = label_col %>% |
733 | ! |
data.frame(label = .) %>% |
734 | ! |
dplyr::filter(label != "cooksd == NaN") %>% |
735 | ! |
unlist(), |
736 | ! |
color = "red", |
737 | ! |
hjust = 0, |
738 | ! |
vjust = 0, |
739 | ! |
max.overlaps = Inf, |
740 | ! |
min.segment.length = label_min_segment, |
741 | ! |
segment.alpha = .5, |
742 | ! |
seed = 123 |
743 |
), |
|
744 | ! |
env = list(plot = plot, label_col = label_col(), label_min_segment = label_min_segment()) |
745 |
) |
|
746 |
} |
|
747 | ||
748 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
749 | ! |
teal.widgets::resolve_ggplot2_args( |
750 | ! |
user_plot = ggplot2_args[["Normal Q-Q"]], |
751 | ! |
user_default = ggplot2_args$default, |
752 | ! |
module_plot = teal.widgets::ggplot2_args( |
753 | ! |
labs = list( |
754 | ! |
x = quote(paste0("Theoretical Quantiles\nlm(", reg_form, ")")), |
755 | ! |
y = "Standardized residuals", |
756 | ! |
title = "Normal Q-Q" |
757 |
) |
|
758 |
) |
|
759 |
), |
|
760 | ! |
ggtheme = input$ggtheme |
761 |
) |
|
762 | ||
763 | ! |
teal.code::eval_code( |
764 | ! |
plot_base, |
765 | ! |
substitute( |
766 | ! |
expr = { |
767 | ! |
plot <- graph |
768 |
}, |
|
769 | ! |
env = list( |
770 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
771 |
) |
|
772 |
) |
|
773 |
) |
|
774 |
}) |
|
775 | ||
776 | ! |
output_plot_3 <- reactive({ |
777 | ! |
shinyjs::show("size") |
778 | ! |
shinyjs::show("alpha") |
779 | ! |
plot_base <- output_plot_base() |
780 | ! |
plot <- substitute( |
781 | ! |
expr = ggplot2::ggplot(data = data, ggplot2::aes(.fitted, sqrt(abs(.stdresid)))) + |
782 | ! |
ggplot2::geom_point(size = size, alpha = alpha) + |
783 | ! |
ggplot2::geom_line(data = smoothy, mapping = smoothy_aes), |
784 | ! |
env = list(size = input$size, alpha = input$alpha) |
785 |
) |
|
786 | ! |
if (input$show_outlier) { |
787 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
788 |
} |
|
789 | ||
790 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
791 | ! |
teal.widgets::resolve_ggplot2_args( |
792 | ! |
user_plot = ggplot2_args[["Scale-Location"]], |
793 | ! |
user_default = ggplot2_args$default, |
794 | ! |
module_plot = teal.widgets::ggplot2_args( |
795 | ! |
labs = list( |
796 | ! |
x = quote(paste0("Fitted values\nlm(", reg_form, ")")), |
797 | ! |
y = quote(expression(sqrt(abs(`Standardized residuals`)))), |
798 | ! |
title = "Scale-Location" |
799 |
) |
|
800 |
) |
|
801 |
), |
|
802 | ! |
ggtheme = input$ggtheme |
803 |
) |
|
804 | ||
805 | ! |
teal.code::eval_code( |
806 | ! |
plot_base, |
807 | ! |
substitute( |
808 | ! |
expr = { |
809 | ! |
smoothy <- smooth(data$.fitted, sqrt(abs(data$.stdresid))) |
810 | ! |
plot <- graph |
811 |
}, |
|
812 | ! |
env = list( |
813 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
814 |
) |
|
815 |
) |
|
816 |
) |
|
817 |
}) |
|
818 | ||
819 | ! |
output_plot_4 <- reactive({ |
820 | ! |
shinyjs::hide("size") |
821 | ! |
shinyjs::show("alpha") |
822 | ! |
plot_base <- output_plot_base() |
823 | ! |
plot <- substitute( |
824 | ! |
expr = ggplot2::ggplot(data = data, ggplot2::aes(seq_along(.cooksd), .cooksd)) + |
825 | ! |
ggplot2::geom_col(alpha = alpha), |
826 | ! |
env = list(alpha = input$alpha) |
827 |
) |
|
828 | ! |
if (input$show_outlier) { |
829 | ! |
plot <- substitute( |
830 | ! |
expr = plot + |
831 | ! |
ggplot2::geom_hline( |
832 | ! |
yintercept = c( |
833 | ! |
outlier * mean(data$.cooksd, na.rm = TRUE), |
834 | ! |
mean(data$.cooksd, na.rm = TRUE) |
835 |
), |
|
836 | ! |
color = "red", |
837 | ! |
linetype = "dashed" |
838 |
) + |
|
839 | ! |
ggplot2::annotate( |
840 | ! |
geom = "text", |
841 | ! |
x = 0, |
842 | ! |
y = mean(data$.cooksd, na.rm = TRUE), |
843 | ! |
label = paste("mu", "=", round(mean(data$.cooksd, na.rm = TRUE), 4)), |
844 | ! |
vjust = -1, |
845 | ! |
hjust = 0, |
846 | ! |
color = "red", |
847 | ! |
angle = 90 |
848 |
) + |
|
849 | ! |
outlier_label, |
850 | ! |
env = list(plot = plot, outlier = input$outlier, outlier_label = outlier_label()) |
851 |
) |
|
852 |
} |
|
853 | ||
854 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
855 | ! |
teal.widgets::resolve_ggplot2_args( |
856 | ! |
user_plot = ggplot2_args[["Cook's distance"]], |
857 | ! |
user_default = ggplot2_args$default, |
858 | ! |
module_plot = teal.widgets::ggplot2_args( |
859 | ! |
labs = list( |
860 | ! |
x = quote(paste0("Obs. number\nlm(", reg_form, ")")), |
861 | ! |
y = "Cook's distance", |
862 | ! |
title = "Cook's distance" |
863 |
) |
|
864 |
) |
|
865 |
), |
|
866 | ! |
ggtheme = input$ggtheme |
867 |
) |
|
868 | ||
869 | ! |
teal.code::eval_code( |
870 | ! |
plot_base, |
871 | ! |
substitute( |
872 | ! |
expr = { |
873 | ! |
plot <- graph |
874 |
}, |
|
875 | ! |
env = list( |
876 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
877 |
) |
|
878 |
) |
|
879 |
) |
|
880 |
}) |
|
881 | ||
882 | ! |
output_plot_5 <- reactive({ |
883 | ! |
shinyjs::show("size") |
884 | ! |
shinyjs::show("alpha") |
885 | ! |
plot_base <- output_plot_base() |
886 | ! |
plot <- substitute( |
887 | ! |
expr = ggplot2::ggplot(data = data, ggplot2::aes(.hat, .stdresid)) + |
888 | ! |
ggplot2::geom_vline( |
889 | ! |
size = 1, |
890 | ! |
colour = "black", |
891 | ! |
linetype = "dashed", |
892 | ! |
xintercept = 0 |
893 |
) + |
|
894 | ! |
ggplot2::geom_hline( |
895 | ! |
size = 1, |
896 | ! |
colour = "black", |
897 | ! |
linetype = "dashed", |
898 | ! |
yintercept = 0 |
899 |
) + |
|
900 | ! |
ggplot2::geom_point(size = size, alpha = alpha) + |
901 | ! |
ggplot2::geom_line(data = smoothy, mapping = smoothy_aes), |
902 | ! |
env = list(size = input$size, alpha = input$alpha) |
903 |
) |
|
904 | ! |
if (input$show_outlier) { |
905 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
906 |
} |
|
907 | ||
908 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
909 | ! |
teal.widgets::resolve_ggplot2_args( |
910 | ! |
user_plot = ggplot2_args[["Residuals vs Leverage"]], |
911 | ! |
user_default = ggplot2_args$default, |
912 | ! |
module_plot = teal.widgets::ggplot2_args( |
913 | ! |
labs = list( |
914 | ! |
x = quote(paste0("Standardized residuals\nlm(", reg_form, ")")), |
915 | ! |
y = "Leverage", |
916 | ! |
title = "Residuals vs Leverage" |
917 |
) |
|
918 |
) |
|
919 |
), |
|
920 | ! |
ggtheme = input$ggtheme |
921 |
) |
|
922 | ||
923 | ! |
teal.code::eval_code( |
924 | ! |
plot_base, |
925 | ! |
substitute( |
926 | ! |
expr = { |
927 | ! |
smoothy <- smooth(data$.hat, data$.stdresid) |
928 | ! |
plot <- graph |
929 |
}, |
|
930 | ! |
env = list( |
931 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
932 |
) |
|
933 |
) |
|
934 |
) |
|
935 |
}) |
|
936 | ||
937 | ! |
output_plot_6 <- reactive({ |
938 | ! |
shinyjs::show("size") |
939 | ! |
shinyjs::show("alpha") |
940 | ! |
plot_base <- output_plot_base() |
941 | ! |
plot <- substitute( |
942 | ! |
expr = ggplot2::ggplot(data = data, ggplot2::aes(.hat, .cooksd)) + |
943 | ! |
ggplot2::geom_vline(xintercept = 0, colour = NA) + |
944 | ! |
ggplot2::geom_abline( |
945 | ! |
slope = seq(0, 3, by = 0.5), |
946 | ! |
colour = "black", |
947 | ! |
linetype = "dashed", |
948 | ! |
size = 1 |
949 |
) + |
|
950 | ! |
ggplot2::geom_line(data = smoothy, mapping = smoothy_aes) + |
951 | ! |
ggplot2::geom_point(size = size, alpha = alpha), |
952 | ! |
env = list(size = input$size, alpha = input$alpha) |
953 |
) |
|
954 | ! |
if (input$show_outlier) { |
955 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
956 |
} |
|
957 | ||
958 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
959 | ! |
teal.widgets::resolve_ggplot2_args( |
960 | ! |
user_plot = ggplot2_args[["Cook's dist vs Leverage"]], |
961 | ! |
user_default = ggplot2_args$default, |
962 | ! |
module_plot = teal.widgets::ggplot2_args( |
963 | ! |
labs = list( |
964 | ! |
x = quote(paste0("Leverage\nlm(", reg_form, ")")), |
965 | ! |
y = "Cooks's distance", |
966 | ! |
title = "Cook's dist vs Leverage" |
967 |
) |
|
968 |
) |
|
969 |
), |
|
970 | ! |
ggtheme = input$ggtheme |
971 |
) |
|
972 | ||
973 | ! |
teal.code::eval_code( |
974 | ! |
plot_base, |
975 | ! |
substitute( |
976 | ! |
expr = { |
977 | ! |
smoothy <- smooth(data$.hat, data$.cooksd) |
978 | ! |
plot <- graph |
979 |
}, |
|
980 | ! |
env = list( |
981 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
982 |
) |
|
983 |
) |
|
984 |
) |
|
985 |
}) |
|
986 | ||
987 | ! |
output_q <- reactive({ |
988 | ! |
teal::validate_inputs(iv_r()) |
989 | ! |
switch(input$plot_type, |
990 | ! |
"Response vs Regressor" = output_plot_0(), |
991 | ! |
"Residuals vs Fitted" = output_plot_1(), |
992 | ! |
"Normal Q-Q" = output_plot_2(), |
993 | ! |
"Scale-Location" = output_plot_3(), |
994 | ! |
"Cook's distance" = output_plot_4(), |
995 | ! |
"Residuals vs Leverage" = output_plot_5(), |
996 | ! |
"Cook's dist vs Leverage" = output_plot_6() |
997 |
) |
|
998 |
}) |
|
999 | ||
1000 | ! |
decorated_output_q <- srv_decorate_teal_data( |
1001 | ! |
"decorator", |
1002 | ! |
data = output_q, |
1003 | ! |
decorators = select_decorators(decorators, "plot"), |
1004 | ! |
expr = quote(plot) |
1005 |
) |
|
1006 | ||
1007 | ! |
fitted <- reactive({ |
1008 | ! |
req(decorated_output_q()) |
1009 | ! |
decorated_output_q()[["fit"]] |
1010 |
}) |
|
1011 | ! |
plot_r <- reactive({ |
1012 | ! |
req(decorated_output_q()) |
1013 | ! |
decorated_output_q()[["plot"]] |
1014 |
}) |
|
1015 | ||
1016 |
# Insert the plot into a plot_with_settings module from teal.widgets |
|
1017 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
1018 | ! |
id = "myplot", |
1019 | ! |
plot_r = plot_r, |
1020 | ! |
height = plot_height, |
1021 | ! |
width = plot_width |
1022 |
) |
|
1023 | ||
1024 | ! |
decorated_output_dims_q <- set_chunk_dims(pws, decorated_output_q) |
1025 | ||
1026 | ! |
output$text <- renderText({ |
1027 | ! |
req(iv_r()$is_valid()) |
1028 | ! |
req(iv_out$is_valid()) |
1029 | ! |
paste(utils::capture.output(summary(fitted()))[-1], collapse = "\n") |
1030 |
}) |
|
1031 | ||
1032 |
# Render R code. |
|
1033 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_output_dims_q()))) |
1034 | ||
1035 | ! |
teal.widgets::verbatim_popup_srv( |
1036 | ! |
id = "rcode", |
1037 | ! |
verbatim_content = source_code_r, |
1038 | ! |
title = "R code for the regression plot", |
1039 |
) |
|
1040 | ! |
decorated_output_dims_q |
1041 |
}) |
|
1042 |
} |
1 |
#' `teal` module: Scatterplot |
|
2 |
#' |
|
3 |
#' Generates a customizable scatterplot using `ggplot2`. |
|
4 |
#' This module allows users to select variables for the x and y axes, |
|
5 |
#' color and size encodings, faceting options, and more. It supports log transformations, |
|
6 |
#' trend line additions, and dynamic adjustments of point opacity and size through UI controls. |
|
7 |
#' |
|
8 |
#' @note For more examples, please see the vignette "Using scatterplot" via |
|
9 |
#' `vignette("using-scatterplot", package = "teal.modules.general")`. |
|
10 |
#' |
|
11 |
#' @inheritParams teal::module |
|
12 |
#' @inheritParams shared_params |
|
13 |
#' @param x (`data_extract_spec` or `list` of multiple `data_extract_spec`) Specifies |
|
14 |
#' variable names selected to plot along the x-axis by default. |
|
15 |
#' @param y (`data_extract_spec` or `list` of multiple `data_extract_spec`) Specifies |
|
16 |
#' variable names selected to plot along the y-axis by default. |
|
17 |
#' @param color_by (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
18 |
#' defines the color encoding. If `NULL` then no color encoding option will be displayed. |
|
19 |
#' @param size_by (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
20 |
#' defines the point size encoding. If `NULL` then no size encoding option will be displayed. |
|
21 |
#' @param row_facet (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
22 |
#' specifies the variable(s) for faceting rows. |
|
23 |
#' @param col_facet (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
24 |
#' specifies the variable(s) for faceting columns. |
|
25 |
#' @param shape (`character`) optional, character vector with the names of the |
|
26 |
#' shape, e.g. `c("triangle", "square", "circle")`. It defaults to `shape_names`. This is a complete list from |
|
27 |
#' `vignette("ggplot2-specs", package="ggplot2")`. |
|
28 |
#' @param max_deg (`integer`) optional, maximum degree for the polynomial trend line. Must not be less than 1. |
|
29 |
#' @param table_dec (`integer`) optional, number of decimal places used to round numeric values in the table. |
|
30 |
#' |
|
31 |
#' @inherit shared_params return |
|
32 |
#' |
|
33 |
#' @section Decorating Module: |
|
34 |
#' |
|
35 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
36 |
#' - `plot` (`ggplot`) |
|
37 |
#' |
|
38 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
39 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
40 |
#' See code snippet below: |
|
41 |
#' |
|
42 |
#' ``` |
|
43 |
#' tm_g_scatterplot( |
|
44 |
#' ..., # arguments for module |
|
45 |
#' decorators = list( |
|
46 |
#' plot = teal_transform_module(...) # applied to the `plot` output |
|
47 |
#' ) |
|
48 |
#' ) |
|
49 |
#' ``` |
|
50 |
#' |
|
51 |
#' For additional details and examples of decorators, refer to the vignette |
|
52 |
#' `vignette("decorate-module-output", package = "teal.modules.general")`. |
|
53 |
#' |
|
54 |
#' To learn more please refer to the vignette |
|
55 |
#' `vignette("transform-module-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
56 |
#' |
|
57 |
#' @inheritSection teal::example_module Reporting |
|
58 |
#' |
|
59 |
#' @examplesShinylive |
|
60 |
#' library(teal.modules.general) |
|
61 |
#' interactive <- function() TRUE |
|
62 |
#' {{ next_example }} |
|
63 |
# nolint start: line_length_linter. |
|
64 |
#' @examples |
|
65 |
# nolint end: line_length_linter. |
|
66 |
#' # general data example |
|
67 |
#' data <- teal_data() |
|
68 |
#' data <- within(data, { |
|
69 |
#' require(nestcolor) |
|
70 |
#' CO2 <- CO2 |
|
71 |
#' }) |
|
72 |
#' |
|
73 |
#' app <- init( |
|
74 |
#' data = data, |
|
75 |
#' modules = modules( |
|
76 |
#' tm_g_scatterplot( |
|
77 |
#' label = "Scatterplot Choices", |
|
78 |
#' x = data_extract_spec( |
|
79 |
#' dataname = "CO2", |
|
80 |
#' select = select_spec( |
|
81 |
#' label = "Select variable:", |
|
82 |
#' choices = variable_choices(data[["CO2"]], c("conc", "uptake")), |
|
83 |
#' selected = "conc", |
|
84 |
#' multiple = FALSE, |
|
85 |
#' fixed = FALSE |
|
86 |
#' ) |
|
87 |
#' ), |
|
88 |
#' y = data_extract_spec( |
|
89 |
#' dataname = "CO2", |
|
90 |
#' select = select_spec( |
|
91 |
#' label = "Select variable:", |
|
92 |
#' choices = variable_choices(data[["CO2"]], c("conc", "uptake")), |
|
93 |
#' selected = "uptake", |
|
94 |
#' multiple = FALSE, |
|
95 |
#' fixed = FALSE |
|
96 |
#' ) |
|
97 |
#' ), |
|
98 |
#' color_by = data_extract_spec( |
|
99 |
#' dataname = "CO2", |
|
100 |
#' select = select_spec( |
|
101 |
#' label = "Select variable:", |
|
102 |
#' choices = variable_choices( |
|
103 |
#' data[["CO2"]], |
|
104 |
#' c("Plant", "Type", "Treatment", "conc", "uptake") |
|
105 |
#' ), |
|
106 |
#' selected = NULL, |
|
107 |
#' multiple = FALSE, |
|
108 |
#' fixed = FALSE |
|
109 |
#' ) |
|
110 |
#' ), |
|
111 |
#' size_by = data_extract_spec( |
|
112 |
#' dataname = "CO2", |
|
113 |
#' select = select_spec( |
|
114 |
#' label = "Select variable:", |
|
115 |
#' choices = variable_choices(data[["CO2"]], c("conc", "uptake")), |
|
116 |
#' selected = "uptake", |
|
117 |
#' multiple = FALSE, |
|
118 |
#' fixed = FALSE |
|
119 |
#' ) |
|
120 |
#' ), |
|
121 |
#' row_facet = data_extract_spec( |
|
122 |
#' dataname = "CO2", |
|
123 |
#' select = select_spec( |
|
124 |
#' label = "Select variable:", |
|
125 |
#' choices = variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment")), |
|
126 |
#' selected = NULL, |
|
127 |
#' multiple = FALSE, |
|
128 |
#' fixed = FALSE |
|
129 |
#' ) |
|
130 |
#' ), |
|
131 |
#' col_facet = data_extract_spec( |
|
132 |
#' dataname = "CO2", |
|
133 |
#' select = select_spec( |
|
134 |
#' label = "Select variable:", |
|
135 |
#' choices = variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment")), |
|
136 |
#' selected = NULL, |
|
137 |
#' multiple = FALSE, |
|
138 |
#' fixed = FALSE |
|
139 |
#' ) |
|
140 |
#' ) |
|
141 |
#' ) |
|
142 |
#' ) |
|
143 |
#' ) |
|
144 |
#' if (interactive()) { |
|
145 |
#' shinyApp(app$ui, app$server) |
|
146 |
#' } |
|
147 |
#' |
|
148 |
#' @examplesShinylive |
|
149 |
#' library(teal.modules.general) |
|
150 |
#' interactive <- function() TRUE |
|
151 |
#' {{ next_example }} |
|
152 |
# nolint start: line_length_linter. |
|
153 |
#' @examples |
|
154 |
# nolint end: line_length_linter. |
|
155 |
#' # CDISC data example |
|
156 |
#' data <- teal_data() |
|
157 |
#' data <- within(data, { |
|
158 |
#' require(nestcolor) |
|
159 |
#' ADSL <- teal.data::rADSL |
|
160 |
#' }) |
|
161 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
162 |
#' |
|
163 |
#' app <- init( |
|
164 |
#' data = data, |
|
165 |
#' modules = modules( |
|
166 |
#' tm_g_scatterplot( |
|
167 |
#' label = "Scatterplot Choices", |
|
168 |
#' x = data_extract_spec( |
|
169 |
#' dataname = "ADSL", |
|
170 |
#' select = select_spec( |
|
171 |
#' label = "Select variable:", |
|
172 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1", "BMRKR2")), |
|
173 |
#' selected = "AGE", |
|
174 |
#' multiple = FALSE, |
|
175 |
#' fixed = FALSE |
|
176 |
#' ) |
|
177 |
#' ), |
|
178 |
#' y = data_extract_spec( |
|
179 |
#' dataname = "ADSL", |
|
180 |
#' select = select_spec( |
|
181 |
#' label = "Select variable:", |
|
182 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1", "BMRKR2")), |
|
183 |
#' selected = "BMRKR1", |
|
184 |
#' multiple = FALSE, |
|
185 |
#' fixed = FALSE |
|
186 |
#' ) |
|
187 |
#' ), |
|
188 |
#' color_by = data_extract_spec( |
|
189 |
#' dataname = "ADSL", |
|
190 |
#' select = select_spec( |
|
191 |
#' label = "Select variable:", |
|
192 |
#' choices = variable_choices( |
|
193 |
#' data[["ADSL"]], |
|
194 |
#' c("AGE", "BMRKR1", "BMRKR2", "RACE", "REGION1") |
|
195 |
#' ), |
|
196 |
#' selected = NULL, |
|
197 |
#' multiple = FALSE, |
|
198 |
#' fixed = FALSE |
|
199 |
#' ) |
|
200 |
#' ), |
|
201 |
#' size_by = data_extract_spec( |
|
202 |
#' dataname = "ADSL", |
|
203 |
#' select = select_spec( |
|
204 |
#' label = "Select variable:", |
|
205 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1")), |
|
206 |
#' selected = "AGE", |
|
207 |
#' multiple = FALSE, |
|
208 |
#' fixed = FALSE |
|
209 |
#' ) |
|
210 |
#' ), |
|
211 |
#' row_facet = data_extract_spec( |
|
212 |
#' dataname = "ADSL", |
|
213 |
#' select = select_spec( |
|
214 |
#' label = "Select variable:", |
|
215 |
#' choices = variable_choices(data[["ADSL"]], c("BMRKR2", "RACE", "REGION1")), |
|
216 |
#' selected = NULL, |
|
217 |
#' multiple = FALSE, |
|
218 |
#' fixed = FALSE |
|
219 |
#' ) |
|
220 |
#' ), |
|
221 |
#' col_facet = data_extract_spec( |
|
222 |
#' dataname = "ADSL", |
|
223 |
#' select = select_spec( |
|
224 |
#' label = "Select variable:", |
|
225 |
#' choices = variable_choices(data[["ADSL"]], c("BMRKR2", "RACE", "REGION1")), |
|
226 |
#' selected = NULL, |
|
227 |
#' multiple = FALSE, |
|
228 |
#' fixed = FALSE |
|
229 |
#' ) |
|
230 |
#' ) |
|
231 |
#' ) |
|
232 |
#' ) |
|
233 |
#' ) |
|
234 |
#' if (interactive()) { |
|
235 |
#' shinyApp(app$ui, app$server) |
|
236 |
#' } |
|
237 |
#' |
|
238 |
#' @export |
|
239 |
#' |
|
240 |
tm_g_scatterplot <- function(label = "Scatterplot", |
|
241 |
x, |
|
242 |
y, |
|
243 |
color_by = NULL, |
|
244 |
size_by = NULL, |
|
245 |
row_facet = NULL, |
|
246 |
col_facet = NULL, |
|
247 |
plot_height = c(600, 200, 2000), |
|
248 |
plot_width = NULL, |
|
249 |
alpha = c(1, 0, 1), |
|
250 |
shape = shape_names, |
|
251 |
size = c(5, 1, 15), |
|
252 |
max_deg = 5L, |
|
253 |
rotate_xaxis_labels = FALSE, |
|
254 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
255 |
pre_output = NULL, |
|
256 |
post_output = NULL, |
|
257 |
table_dec = 4, |
|
258 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
259 |
transformators = list(), |
|
260 |
decorators = list()) { |
|
261 | ! |
message("Initializing tm_g_scatterplot") |
262 | ||
263 |
# Normalize the parameters |
|
264 | ! |
if (inherits(x, "data_extract_spec")) x <- list(x) |
265 | ! |
if (inherits(y, "data_extract_spec")) y <- list(y) |
266 | ! |
if (inherits(color_by, "data_extract_spec")) color_by <- list(color_by) |
267 | ! |
if (inherits(size_by, "data_extract_spec")) size_by <- list(size_by) |
268 | ! |
if (inherits(row_facet, "data_extract_spec")) row_facet <- list(row_facet) |
269 | ! |
if (inherits(col_facet, "data_extract_spec")) col_facet <- list(col_facet) |
270 | ! |
if (is.double(max_deg)) max_deg <- as.integer(max_deg) |
271 | ||
272 |
# Start of assertions |
|
273 | ! |
checkmate::assert_string(label) |
274 | ! |
checkmate::assert_list(x, types = "data_extract_spec") |
275 | ! |
checkmate::assert_list(y, types = "data_extract_spec") |
276 | ! |
checkmate::assert_list(color_by, types = "data_extract_spec", null.ok = TRUE) |
277 | ! |
checkmate::assert_list(size_by, types = "data_extract_spec", null.ok = TRUE) |
278 | ||
279 | ! |
checkmate::assert_list(row_facet, types = "data_extract_spec", null.ok = TRUE) |
280 | ! |
assert_single_selection(row_facet) |
281 | ||
282 | ! |
checkmate::assert_list(col_facet, types = "data_extract_spec", null.ok = TRUE) |
283 | ! |
assert_single_selection(col_facet) |
284 | ||
285 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
286 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
287 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
288 | ! |
checkmate::assert_numeric( |
289 | ! |
plot_width[1], |
290 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
291 |
) |
|
292 | ||
293 | ! |
if (length(alpha) == 1) { |
294 | ! |
checkmate::assert_numeric(alpha, any.missing = FALSE, finite = TRUE) |
295 |
} else { |
|
296 | ! |
checkmate::assert_numeric(alpha, len = 3, any.missing = FALSE, finite = TRUE) |
297 | ! |
checkmate::assert_numeric(alpha[1], lower = alpha[2], upper = alpha[3], .var.name = "alpha") |
298 |
} |
|
299 | ||
300 | ! |
checkmate::assert_character(shape) |
301 | ||
302 | ! |
if (length(size) == 1) { |
303 | ! |
checkmate::assert_numeric(size, any.missing = FALSE, finite = TRUE) |
304 |
} else { |
|
305 | ! |
checkmate::assert_numeric(size, len = 3, any.missing = FALSE, finite = TRUE) |
306 | ! |
checkmate::assert_numeric(size[1], lower = size[2], upper = size[3], .var.name = "size") |
307 |
} |
|
308 | ||
309 | ! |
checkmate::assert_int(max_deg, lower = 1L) |
310 | ! |
checkmate::assert_flag(rotate_xaxis_labels) |
311 | ! |
ggtheme <- match.arg(ggtheme) |
312 | ||
313 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
314 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
315 | ||
316 | ! |
checkmate::assert_scalar(table_dec) |
317 | ! |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
318 | ||
319 | ! |
assert_decorators(decorators, "plot") |
320 | ||
321 |
# End of assertions |
|
322 | ||
323 |
# Make UI args |
|
324 | ! |
args <- as.list(environment()) |
325 | ||
326 | ! |
data_extract_list <- list( |
327 | ! |
x = x, |
328 | ! |
y = y, |
329 | ! |
color_by = color_by, |
330 | ! |
size_by = size_by, |
331 | ! |
row_facet = row_facet, |
332 | ! |
col_facet = col_facet |
333 |
) |
|
334 | ||
335 | ! |
ans <- module( |
336 | ! |
label = label, |
337 | ! |
server = srv_g_scatterplot, |
338 | ! |
ui = ui_g_scatterplot, |
339 | ! |
ui_args = args, |
340 | ! |
server_args = c( |
341 | ! |
data_extract_list, |
342 | ! |
list( |
343 | ! |
plot_height = plot_height, |
344 | ! |
plot_width = plot_width, |
345 | ! |
table_dec = table_dec, |
346 | ! |
ggplot2_args = ggplot2_args, |
347 | ! |
decorators = decorators |
348 |
) |
|
349 |
), |
|
350 | ! |
transformators = transformators, |
351 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
352 |
) |
|
353 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
354 | ! |
ans |
355 |
} |
|
356 | ||
357 |
# UI function for the scatterplot module |
|
358 |
ui_g_scatterplot <- function(id, ...) { |
|
359 | ! |
args <- list(...) |
360 | ! |
ns <- NS(id) |
361 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset( |
362 | ! |
args$x, args$y, args$color_by, args$size_by, args$row_facet, args$col_facet |
363 |
) |
|
364 | ||
365 | ! |
tagList( |
366 | ! |
teal.widgets::standard_layout( |
367 | ! |
output = teal.widgets::white_small_well( |
368 | ! |
teal.widgets::plot_with_settings_ui(id = ns("scatter_plot")), |
369 | ! |
tags$br(), |
370 | ! |
tags$h1(tags$strong("Selected points:"), style = "font-size: 150%;"), |
371 | ! |
teal.widgets::get_dt_rows(ns("data_table"), ns("data_table_rows")), |
372 | ! |
DT::dataTableOutput(ns("data_table"), width = "100%") |
373 |
), |
|
374 | ! |
encoding = tags$div( |
375 | ! |
tags$label("Encodings", class = "text-primary"), |
376 | ! |
teal.transform::datanames_input(args[c("x", "y", "color_by", "size_by", "row_facet", "col_facet")]), |
377 | ! |
teal.transform::data_extract_ui( |
378 | ! |
id = ns("x"), |
379 | ! |
label = "X variable", |
380 | ! |
data_extract_spec = args$x, |
381 | ! |
is_single_dataset = is_single_dataset_value |
382 |
), |
|
383 | ! |
checkboxInput(ns("log_x"), "Use log transformation", value = FALSE), |
384 | ! |
conditionalPanel( |
385 | ! |
condition = paste0("input['", ns("log_x"), "'] == true"), |
386 | ! |
radioButtons( |
387 | ! |
ns("log_x_base"), |
388 | ! |
label = NULL, |
389 | ! |
inline = TRUE, |
390 | ! |
choices = c("Natural" = "log", "Base 10" = "log10", "Base 2" = "log2") |
391 |
) |
|
392 |
), |
|
393 | ! |
teal.transform::data_extract_ui( |
394 | ! |
id = ns("y"), |
395 | ! |
label = "Y variable", |
396 | ! |
data_extract_spec = args$y, |
397 | ! |
is_single_dataset = is_single_dataset_value |
398 |
), |
|
399 | ! |
checkboxInput(ns("log_y"), "Use log transformation", value = FALSE), |
400 | ! |
conditionalPanel( |
401 | ! |
condition = paste0("input['", ns("log_y"), "'] == true"), |
402 | ! |
radioButtons( |
403 | ! |
ns("log_y_base"), |
404 | ! |
label = NULL, |
405 | ! |
inline = TRUE, |
406 | ! |
choices = c("Natural" = "log", "Base 10" = "log10", "Base 2" = "log2") |
407 |
) |
|
408 |
), |
|
409 | ! |
if (!is.null(args$color_by)) { |
410 | ! |
teal.transform::data_extract_ui( |
411 | ! |
id = ns("color_by"), |
412 | ! |
label = "Color by variable", |
413 | ! |
data_extract_spec = args$color_by, |
414 | ! |
is_single_dataset = is_single_dataset_value |
415 |
) |
|
416 |
}, |
|
417 | ! |
if (!is.null(args$size_by)) { |
418 | ! |
teal.transform::data_extract_ui( |
419 | ! |
id = ns("size_by"), |
420 | ! |
label = "Size by variable", |
421 | ! |
data_extract_spec = args$size_by, |
422 | ! |
is_single_dataset = is_single_dataset_value |
423 |
) |
|
424 |
}, |
|
425 | ! |
if (!is.null(args$row_facet)) { |
426 | ! |
teal.transform::data_extract_ui( |
427 | ! |
id = ns("row_facet"), |
428 | ! |
label = "Row facetting", |
429 | ! |
data_extract_spec = args$row_facet, |
430 | ! |
is_single_dataset = is_single_dataset_value |
431 |
) |
|
432 |
}, |
|
433 | ! |
if (!is.null(args$col_facet)) { |
434 | ! |
teal.transform::data_extract_ui( |
435 | ! |
id = ns("col_facet"), |
436 | ! |
label = "Column facetting", |
437 | ! |
data_extract_spec = args$col_facet, |
438 | ! |
is_single_dataset = is_single_dataset_value |
439 |
) |
|
440 |
}, |
|
441 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")), |
442 | ! |
bslib::accordion( |
443 | ! |
open = TRUE, |
444 | ! |
bslib::accordion_panel( |
445 | ! |
title = "Plot settings", |
446 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("alpha"), "Opacity:", args$alpha, ticks = FALSE), |
447 | ! |
teal.widgets::optionalSelectInput( |
448 | ! |
inputId = ns("shape"), |
449 | ! |
label = "Points shape:", |
450 | ! |
choices = args$shape, |
451 | ! |
selected = args$shape[1], |
452 | ! |
multiple = FALSE |
453 |
), |
|
454 | ! |
colourpicker::colourInput(ns("color"), "Points color:", "black"), |
455 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("size"), "Points size:", args$size, ticks = FALSE, step = .1), |
456 | ! |
checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = args$rotate_xaxis_labels), |
457 | ! |
checkboxInput(ns("add_density"), "Add marginal density", value = FALSE), |
458 | ! |
checkboxInput(ns("rug_plot"), "Include rug plot", value = FALSE), |
459 | ! |
checkboxInput(ns("show_count"), "Show N (number of observations)", value = FALSE), |
460 | ! |
shinyjs::hidden(helpText(id = ns("line_msg"), "Trendline needs numeric X and Y variables")), |
461 | ! |
teal.widgets::optionalSelectInput(ns("smoothing_degree"), "Smoothing degree", seq_len(args$max_deg)), |
462 | ! |
shinyjs::hidden(teal.widgets::optionalSelectInput(ns("color_sub"), label = "", multiple = TRUE)), |
463 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("ci"), "Confidence", c(.95, .8, .99), ticks = FALSE), |
464 | ! |
shinyjs::hidden(checkboxInput(ns("show_form"), "Show formula", value = TRUE)), |
465 | ! |
shinyjs::hidden(checkboxInput(ns("show_r2"), "Show adj-R Squared", value = TRUE)), |
466 | ! |
uiOutput(ns("num_na_removed")), |
467 | ! |
tags$div( |
468 | ! |
id = ns("label_pos"), |
469 | ! |
tags$div(tags$strong("Stats position")), |
470 | ! |
tags$div(style = "display: inline-block; width: 70%;", helpText("Left")), |
471 | ! |
tags$div( |
472 | ! |
style = "display: inline-block; width: 70%;", |
473 | ! |
teal.widgets::optionalSliderInput( |
474 | ! |
ns("pos"), |
475 | ! |
label = NULL, |
476 | ! |
min = 0, max = 1, value = .99, ticks = FALSE, step = .01 |
477 |
) |
|
478 |
), |
|
479 | ! |
tags$div(style = "display: inline-block; width: 10%;", helpText("Right")) |
480 |
), |
|
481 | ! |
teal.widgets::optionalSliderInput( |
482 | ! |
ns("label_size"), "Stats font size", |
483 | ! |
min = 3, max = 10, value = 5, ticks = FALSE, step = .1 |
484 |
), |
|
485 | ! |
if (!is.null(args$row_facet) || !is.null(args$col_facet)) { |
486 | ! |
checkboxInput(ns("free_scales"), "Free scales", value = FALSE) |
487 |
}, |
|
488 | ! |
selectInput( |
489 | ! |
inputId = ns("ggtheme"), |
490 | ! |
label = "Theme (by ggplot):", |
491 | ! |
choices = ggplot_themes, |
492 | ! |
selected = args$ggtheme, |
493 | ! |
multiple = FALSE |
494 |
) |
|
495 |
) |
|
496 |
) |
|
497 |
), |
|
498 | ! |
forms = tagList( |
499 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
500 |
), |
|
501 | ! |
pre_output = args$pre_output, |
502 | ! |
post_output = args$post_output |
503 |
) |
|
504 |
) |
|
505 |
} |
|
506 | ||
507 |
# Server function for the scatterplot module |
|
508 |
srv_g_scatterplot <- function(id, |
|
509 |
data, |
|
510 |
x, |
|
511 |
y, |
|
512 |
color_by, |
|
513 |
size_by, |
|
514 |
row_facet, |
|
515 |
col_facet, |
|
516 |
plot_height, |
|
517 |
plot_width, |
|
518 |
table_dec, |
|
519 |
ggplot2_args, |
|
520 |
decorators) { |
|
521 | ! |
checkmate::assert_class(data, "reactive") |
522 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
523 | ! |
moduleServer(id, function(input, output, session) { |
524 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
525 | ||
526 | ! |
data_extract <- list( |
527 | ! |
x = x, |
528 | ! |
y = y, |
529 | ! |
color_by = color_by, |
530 | ! |
size_by = size_by, |
531 | ! |
row_facet = row_facet, |
532 | ! |
col_facet = col_facet |
533 |
) |
|
534 | ||
535 | ! |
rule_diff <- function(other) { |
536 | ! |
function(value) { |
537 | ! |
othervalue <- selector_list()[[other]]()[["select"]] |
538 | ! |
if (!is.null(othervalue)) { |
539 | ! |
if (identical(value, othervalue)) { |
540 | ! |
"Row and column facetting variables must be different." |
541 |
} |
|
542 |
} |
|
543 |
} |
|
544 |
} |
|
545 | ||
546 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
547 | ! |
data_extract = data_extract, |
548 | ! |
datasets = data, |
549 | ! |
select_validation_rule = list( |
550 | ! |
x = ~ if (length(.) != 1) "Please select exactly one x var.", |
551 | ! |
y = ~ if (length(.) != 1) "Please select exactly one y var.", |
552 | ! |
color_by = ~ if (length(.) > 1) "There cannot be more than 1 color variable.", |
553 | ! |
size_by = ~ if (length(.) > 1) "There cannot be more than 1 size variable.", |
554 | ! |
row_facet = shinyvalidate::compose_rules( |
555 | ! |
shinyvalidate::sv_optional(), |
556 | ! |
rule_diff("col_facet") |
557 |
), |
|
558 | ! |
col_facet = shinyvalidate::compose_rules( |
559 | ! |
shinyvalidate::sv_optional(), |
560 | ! |
rule_diff("row_facet") |
561 |
) |
|
562 |
) |
|
563 |
) |
|
564 | ||
565 | ! |
iv_r <- reactive({ |
566 | ! |
iv_facet <- shinyvalidate::InputValidator$new() |
567 | ! |
iv <- shinyvalidate::InputValidator$new() |
568 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
569 |
}) |
|
570 | ! |
iv_facet <- shinyvalidate::InputValidator$new() |
571 | ! |
iv_facet$add_rule("add_density", ~ if ( |
572 | ! |
isTRUE(.) && |
573 |
( |
|
574 | ! |
length(selector_list()$row_facet()$select) > 0L || |
575 | ! |
length(selector_list()$col_facet()$select) > 0L |
576 |
) |
|
577 |
) { |
|
578 | ! |
"Cannot add marginal density when Row or Column facetting has been selected" |
579 |
}) |
|
580 | ! |
iv_facet$enable() |
581 | ||
582 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
583 | ! |
selector_list = selector_list, |
584 | ! |
datasets = data, |
585 | ! |
merge_function = "dplyr::inner_join" |
586 |
) |
|
587 | ! |
qenv <- reactive({ |
588 | ! |
obj <- data() |
589 | ! |
teal.reporter::teal_card(obj) <- c( |
590 | ! |
teal.reporter::teal_card("# Scatter Plot"), |
591 | ! |
teal.reporter::teal_card(obj), |
592 | ! |
teal.reporter::teal_card("## Module's code") |
593 |
) |
|
594 | ! |
teal.code::eval_code(data(), 'library("ggplot2");library("dplyr")') # nolint quotes |
595 |
}) |
|
596 | ||
597 | ! |
anl_merged_q <- reactive({ |
598 | ! |
req(anl_merged_input()) |
599 | ! |
qenv() %>% |
600 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
601 |
}) |
|
602 | ||
603 | ! |
merged <- list( |
604 | ! |
anl_input_r = anl_merged_input, |
605 | ! |
anl_q_r = anl_merged_q |
606 |
) |
|
607 | ||
608 | ! |
trend_line_is_applicable <- reactive({ |
609 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
610 | ! |
x_var <- as.vector(merged$anl_input_r()$columns_source$x) |
611 | ! |
y_var <- as.vector(merged$anl_input_r()$columns_source$y) |
612 | ! |
length(x_var) > 0 && length(y_var) > 0 && is.numeric(ANL[[x_var]]) && is.numeric(ANL[[y_var]]) |
613 |
}) |
|
614 | ||
615 | ! |
add_trend_line <- reactive({ |
616 | ! |
smoothing_degree <- as.integer(input$smoothing_degree) |
617 | ! |
trend_line_is_applicable() && length(smoothing_degree) > 0 |
618 |
}) |
|
619 | ||
620 | ! |
if (!is.null(color_by)) { |
621 | ! |
observeEvent( |
622 | ! |
eventExpr = merged$anl_input_r()$columns_source$color_by, |
623 | ! |
handlerExpr = { |
624 | ! |
color_by_var <- as.vector(merged$anl_input_r()$columns_source$color_by) |
625 | ! |
if (length(color_by_var) > 0) { |
626 | ! |
shinyjs::hide("color") |
627 |
} else { |
|
628 | ! |
shinyjs::show("color") |
629 |
} |
|
630 |
} |
|
631 |
) |
|
632 |
} |
|
633 | ||
634 | ! |
output$num_na_removed <- renderUI({ |
635 | ! |
if (add_trend_line()) { |
636 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
637 | ! |
x_var <- as.vector(merged$anl_input_r()$columns_source$x) |
638 | ! |
y_var <- as.vector(merged$anl_input_r()$columns_source$y) |
639 | ! |
if ((num_total_na <- nrow(ANL) - nrow(stats::na.omit(ANL[, c(x_var, y_var)]))) > 0) { |
640 | ! |
tags$div(paste(num_total_na, "row(s) with missing values were removed"), tags$hr()) |
641 |
} |
|
642 |
} |
|
643 |
}) |
|
644 | ||
645 | ! |
observeEvent( |
646 | ! |
eventExpr = merged$anl_input_r()$columns_source[c("col_facet", "row_facet")], |
647 | ! |
handlerExpr = { |
648 | ! |
if ( |
649 | ! |
length(merged$anl_input_r()$columns_source$col_facet) == 0 && |
650 | ! |
length(merged$anl_input_r()$columns_source$row_facet) == 0 |
651 |
) { |
|
652 | ! |
shinyjs::hide("free_scales") |
653 |
} else { |
|
654 | ! |
shinyjs::show("free_scales") |
655 |
} |
|
656 |
} |
|
657 |
) |
|
658 | ||
659 | ! |
output_q <- reactive({ |
660 | ! |
teal::validate_inputs(iv_r(), iv_facet) |
661 | ||
662 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
663 | ||
664 | ! |
x_var <- as.vector(merged$anl_input_r()$columns_source$x) |
665 | ! |
y_var <- as.vector(merged$anl_input_r()$columns_source$y) |
666 | ! |
color_by_var <- as.vector(merged$anl_input_r()$columns_source$color_by) |
667 | ! |
size_by_var <- as.vector(merged$anl_input_r()$columns_source$size_by) |
668 | ! |
row_facet_name <- if (length(merged$anl_input_r()$columns_source$row_facet) == 0) { |
669 | ! |
character(0) |
670 |
} else { |
|
671 | ! |
as.vector(merged$anl_input_r()$columns_source$row_facet) |
672 |
} |
|
673 | ! |
col_facet_name <- if (length(merged$anl_input_r()$columns_source$col_facet) == 0) { |
674 | ! |
character(0) |
675 |
} else { |
|
676 | ! |
as.vector(merged$anl_input_r()$columns_source$col_facet) |
677 |
} |
|
678 | ! |
alpha <- input$alpha |
679 | ! |
size <- input$size |
680 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
681 | ! |
add_density <- input$add_density |
682 | ! |
ggtheme <- input$ggtheme |
683 | ! |
rug_plot <- input$rug_plot |
684 | ! |
color <- input$color |
685 | ! |
shape <- `if`(is.null(input$shape) || identical(input$shape, ""), "circle", input$shape) |
686 | ! |
smoothing_degree <- as.integer(input$smoothing_degree) |
687 | ! |
ci <- input$ci |
688 | ||
689 | ! |
log_x <- input$log_x |
690 | ! |
log_y <- input$log_y |
691 | ||
692 | ! |
validate(need( |
693 | ! |
length(row_facet_name) == 0 || inherits(ANL[[row_facet_name]], c("character", "factor", "Date", "integer")), |
694 | ! |
"`Row facetting` variable must be of class `character`, `factor`, `Date`, or `integer`" |
695 |
)) |
|
696 | ! |
validate(need( |
697 | ! |
length(col_facet_name) == 0 || inherits(ANL[[col_facet_name]], c("character", "factor", "Date", "integer")), |
698 | ! |
"`Column facetting` variable must be of class `character`, `factor`, `Date`, or `integer`" |
699 |
)) |
|
700 | ||
701 | ! |
if (add_density && length(color_by_var) > 0) { |
702 | ! |
validate(need( |
703 | ! |
!is.numeric(ANL[[color_by_var]]), |
704 | ! |
"Marginal plots cannot be produced when the points are colored by numeric variables. |
705 | ! |
\n Uncheck the 'Add marginal density' checkbox to display the plot." |
706 |
)) |
|
707 | ! |
validate(need( |
708 |
!( |
|
709 | ! |
inherits(ANL[[color_by_var]], "Date") || |
710 | ! |
inherits(ANL[[color_by_var]], "POSIXct") || |
711 | ! |
inherits(ANL[[color_by_var]], "POSIXlt") |
712 |
), |
|
713 | ! |
"Marginal plots cannot be produced when the points are colored by Date or POSIX variables. |
714 | ! |
\n Uncheck the 'Add marginal density' checkbox to display the plot." |
715 |
)) |
|
716 |
} |
|
717 | ||
718 | ! |
teal::validate_has_data(ANL[, c(x_var, y_var)], 1, complete = TRUE, allow_inf = FALSE) |
719 | ||
720 | ! |
if (log_x) { |
721 | ! |
validate( |
722 | ! |
need( |
723 | ! |
is.numeric(ANL[[x_var]]) && all( |
724 | ! |
ANL[[x_var]] > 0 | is.na(ANL[[x_var]]) |
725 |
), |
|
726 | ! |
"X variable can only be log transformed if variable is numeric and all values are positive." |
727 |
) |
|
728 |
) |
|
729 |
} |
|
730 | ! |
if (log_y) { |
731 | ! |
validate( |
732 | ! |
need( |
733 | ! |
is.numeric(ANL[[y_var]]) && all( |
734 | ! |
ANL[[y_var]] > 0 | is.na(ANL[[y_var]]) |
735 |
), |
|
736 | ! |
"Y variable can only be log transformed if variable is numeric and all values are positive." |
737 |
) |
|
738 |
) |
|
739 |
} |
|
740 | ||
741 | ! |
facet_cl <- facet_ggplot_call( |
742 | ! |
row_facet_name, |
743 | ! |
col_facet_name, |
744 | ! |
free_x_scales = isTRUE(input$free_scales), |
745 | ! |
free_y_scales = isTRUE(input$free_scales) |
746 |
) |
|
747 | ||
748 | ! |
point_sizes <- if (length(size_by_var) > 0) { |
749 | ! |
validate(need(is.numeric(ANL[[size_by_var]]), "Variable to size by must be numeric")) |
750 | ! |
substitute( |
751 | ! |
expr = size * ANL[[size_by_var]] / max(ANL[[size_by_var]], na.rm = TRUE), |
752 | ! |
env = list(size = size, size_by_var = size_by_var) |
753 |
) |
|
754 |
} else { |
|
755 | ! |
size |
756 |
} |
|
757 | ||
758 | ! |
plot_q <- merged$anl_q_r() |
759 | ||
760 | ! |
if (log_x) { |
761 | ! |
log_x_fn <- input$log_x_base |
762 | ! |
plot_q <- teal.code::eval_code( |
763 | ! |
object = plot_q, |
764 | ! |
code = substitute( |
765 | ! |
expr = ANL[, log_x_var] <- log_x_fn(ANL[, x_var]), |
766 | ! |
env = list( |
767 | ! |
x_var = x_var, |
768 | ! |
log_x_fn = as.name(log_x_fn), |
769 | ! |
log_x_var = paste0(log_x_fn, "_", x_var) |
770 |
) |
|
771 |
) |
|
772 |
) |
|
773 |
} |
|
774 | ||
775 | ! |
if (log_y) { |
776 | ! |
log_y_fn <- input$log_y_base |
777 | ! |
plot_q <- teal.code::eval_code( |
778 | ! |
object = plot_q, |
779 | ! |
code = substitute( |
780 | ! |
expr = ANL[, log_y_var] <- log_y_fn(ANL[, y_var]), |
781 | ! |
env = list( |
782 | ! |
y_var = y_var, |
783 | ! |
log_y_fn = as.name(log_y_fn), |
784 | ! |
log_y_var = paste0(log_y_fn, "_", y_var) |
785 |
) |
|
786 |
) |
|
787 |
) |
|
788 |
} |
|
789 | ||
790 | ! |
pre_pro_anl <- if (input$show_count) { |
791 | ! |
paste0( |
792 | ! |
"ANL %>% dplyr::group_by(", |
793 | ! |
paste( |
794 | ! |
c( |
795 | ! |
if (length(color_by_var) > 0 && inherits(ANL[[color_by_var]], c("factor", "character"))) color_by_var, |
796 | ! |
row_facet_name, |
797 | ! |
col_facet_name |
798 |
), |
|
799 | ! |
collapse = ", " |
800 |
), |
|
801 | ! |
") %>% dplyr::mutate(n = dplyr::n()) %>% dplyr::ungroup()" |
802 |
) |
|
803 |
} else { |
|
804 | ! |
"ANL" |
805 |
} |
|
806 | ||
807 | ! |
plot_call <- substitute(expr = pre_pro_anl %>% ggplot2::ggplot(), env = list(pre_pro_anl = str2lang(pre_pro_anl))) |
808 | ||
809 | ! |
plot_call <- if (length(color_by_var) == 0) { |
810 | ! |
substitute( |
811 | ! |
expr = plot_call + |
812 | ! |
ggplot2::aes(x = x_name, y = y_name) + |
813 | ! |
ggplot2::geom_point(alpha = alpha_value, size = point_sizes, shape = shape_value, color = color_value), |
814 | ! |
env = list( |
815 | ! |
plot_call = plot_call, |
816 | ! |
x_name = if (log_x) as.name(paste0(log_x_fn, "_", x_var)) else as.name(x_var), |
817 | ! |
y_name = if (log_y) as.name(paste0(log_y_fn, "_", y_var)) else as.name(y_var), |
818 | ! |
alpha_value = alpha, |
819 | ! |
point_sizes = point_sizes, |
820 | ! |
shape_value = shape, |
821 | ! |
color_value = color |
822 |
) |
|
823 |
) |
|
824 |
} else { |
|
825 | ! |
substitute( |
826 | ! |
expr = plot_call + |
827 | ! |
ggplot2::aes(x = x_name, y = y_name, color = color_by_var_name) + |
828 | ! |
ggplot2::geom_point(alpha = alpha_value, size = point_sizes, shape = shape_value), |
829 | ! |
env = list( |
830 | ! |
plot_call = plot_call, |
831 | ! |
x_name = if (log_x) as.name(paste0(log_x_fn, "_", x_var)) else as.name(x_var), |
832 | ! |
y_name = if (log_y) as.name(paste0(log_y_fn, "_", y_var)) else as.name(y_var), |
833 | ! |
color_by_var_name = as.name(color_by_var), |
834 | ! |
alpha_value = alpha, |
835 | ! |
point_sizes = point_sizes, |
836 | ! |
shape_value = shape |
837 |
) |
|
838 |
) |
|
839 |
} |
|
840 | ||
841 | ! |
if (rug_plot) plot_call <- substitute(expr = plot_call + geom_rug(), env = list(plot_call = plot_call)) |
842 | ||
843 | ! |
plot_label_generator <- function(rhs_formula = quote(y ~ 1), |
844 | ! |
show_form = input$show_form, |
845 | ! |
show_r2 = input$show_r2, |
846 | ! |
show_count = input$show_count, |
847 | ! |
pos = input$pos, |
848 | ! |
label_size = input$label_size) { |
849 | ! |
stopifnot(sum(show_form, show_r2, show_count) >= 1) |
850 | ! |
aes_label <- paste0( |
851 | ! |
"aes(", |
852 | ! |
if (show_count) "n = n, ", |
853 | ! |
"label = ", |
854 | ! |
if (sum(show_form, show_r2, show_count) > 1) "paste(", |
855 | ! |
paste( |
856 | ! |
c( |
857 | ! |
if (show_form) "stat(eq.label)", |
858 | ! |
if (show_r2) "stat(adj.rr.label)", |
859 | ! |
if (show_count) "paste('N ~`=`~', n)" |
860 |
), |
|
861 | ! |
collapse = ", " |
862 |
), |
|
863 | ! |
if (sum(show_form, show_r2, show_count) > 1) ", sep = '*\", \"*'))" else ")" |
864 |
) |
|
865 | ! |
label_geom <- substitute( |
866 | ! |
expr = ggpmisc::stat_poly_eq( |
867 | ! |
mapping = aes_label, |
868 | ! |
formula = rhs_formula, |
869 | ! |
parse = TRUE, |
870 | ! |
label.x = pos, |
871 | ! |
size = label_size |
872 |
), |
|
873 | ! |
env = list( |
874 | ! |
rhs_formula = rhs_formula, |
875 | ! |
pos = pos, |
876 | ! |
aes_label = str2lang(aes_label), |
877 | ! |
label_size = label_size |
878 |
) |
|
879 |
) |
|
880 | ! |
substitute( |
881 | ! |
expr = plot_call + label_geom, |
882 | ! |
env = list( |
883 | ! |
plot_call = plot_call, |
884 | ! |
label_geom = label_geom |
885 |
) |
|
886 |
) |
|
887 |
} |
|
888 | ||
889 | ! |
if (trend_line_is_applicable()) { |
890 | ! |
shinyjs::hide("line_msg") |
891 | ! |
shinyjs::show("smoothing_degree") |
892 | ! |
if (!add_trend_line()) { |
893 | ! |
shinyjs::hide("ci") |
894 | ! |
shinyjs::hide("color_sub") |
895 | ! |
shinyjs::hide("show_form") |
896 | ! |
shinyjs::hide("show_r2") |
897 | ! |
if (input$show_count) { |
898 | ! |
plot_call <- plot_label_generator(show_form = FALSE, show_r2 = FALSE) |
899 | ! |
shinyjs::show("label_pos") |
900 | ! |
shinyjs::show("label_size") |
901 |
} else { |
|
902 | ! |
shinyjs::hide("label_pos") |
903 | ! |
shinyjs::hide("label_size") |
904 |
} |
|
905 |
} else { |
|
906 | ! |
shinyjs::show("ci") |
907 | ! |
shinyjs::show("show_form") |
908 | ! |
shinyjs::show("show_r2") |
909 | ! |
if (nrow(ANL) - nrow(stats::na.omit(ANL[, c(x_var, y_var)])) > 0) { |
910 | ! |
plot_q <- teal.code::eval_code( |
911 | ! |
plot_q, |
912 | ! |
substitute( |
913 | ! |
expr = ANL <- dplyr::filter(ANL, !is.na(x_var) & !is.na(y_var)), |
914 | ! |
env = list(x_var = as.name(x_var), y_var = as.name(y_var)) |
915 |
) |
|
916 |
) |
|
917 |
} |
|
918 | ! |
rhs_formula <- substitute( |
919 | ! |
expr = y ~ poly(x, smoothing_degree, raw = TRUE), |
920 | ! |
env = list(smoothing_degree = smoothing_degree) |
921 |
) |
|
922 | ! |
if (input$show_form || input$show_r2 || input$show_count) { |
923 | ! |
plot_call <- plot_label_generator(rhs_formula = rhs_formula) |
924 | ! |
shinyjs::show("label_pos") |
925 | ! |
shinyjs::show("label_size") |
926 |
} else { |
|
927 | ! |
shinyjs::hide("label_pos") |
928 | ! |
shinyjs::hide("label_size") |
929 |
} |
|
930 | ! |
plot_call <- substitute( |
931 | ! |
expr = plot_call + ggplot2::geom_smooth(formula = rhs_formula, se = TRUE, level = ci, method = "lm"), |
932 | ! |
env = list(plot_call = plot_call, rhs_formula = rhs_formula, ci = ci) |
933 |
) |
|
934 |
} |
|
935 |
} else { |
|
936 | ! |
shinyjs::hide("smoothing_degree") |
937 | ! |
shinyjs::hide("ci") |
938 | ! |
shinyjs::hide("color_sub") |
939 | ! |
shinyjs::hide("show_form") |
940 | ! |
shinyjs::hide("show_r2") |
941 | ! |
if (input$show_count) { |
942 | ! |
plot_call <- plot_label_generator(show_form = FALSE, show_r2 = FALSE) |
943 | ! |
shinyjs::show("label_pos") |
944 | ! |
shinyjs::show("label_size") |
945 |
} else { |
|
946 | ! |
shinyjs::hide("label_pos") |
947 | ! |
shinyjs::hide("label_size") |
948 |
} |
|
949 | ! |
shinyjs::show("line_msg") |
950 |
} |
|
951 | ||
952 | ! |
if (!is.null(facet_cl)) { |
953 | ! |
plot_call <- substitute(expr = plot_call + facet_cl, env = list(plot_call = plot_call, facet_cl = facet_cl)) |
954 |
} |
|
955 | ||
956 | ! |
y_label <- varname_w_label( |
957 | ! |
y_var, |
958 | ! |
ANL, |
959 | ! |
prefix = if (log_y) paste(log_y_fn, "(") else NULL, |
960 | ! |
suffix = if (log_y) ")" else NULL |
961 |
) |
|
962 | ! |
x_label <- varname_w_label( |
963 | ! |
x_var, |
964 | ! |
ANL, |
965 | ! |
prefix = if (log_x) paste(log_x_fn, "(") else NULL, |
966 | ! |
suffix = if (log_x) ")" else NULL |
967 |
) |
|
968 | ||
969 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
970 | ! |
labs = list(y = y_label, x = x_label), |
971 | ! |
theme = list(legend.position = "bottom") |
972 |
) |
|
973 | ||
974 | ! |
if (rotate_xaxis_labels) { |
975 | ! |
dev_ggplot2_args$theme[["axis.text.x"]] <- quote(ggplot2::element_text(angle = 45, hjust = 1)) |
976 |
} |
|
977 | ||
978 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
979 | ! |
user_plot = ggplot2_args, |
980 | ! |
module_plot = dev_ggplot2_args |
981 |
) |
|
982 | ||
983 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args(all_ggplot2_args, ggtheme = ggtheme) |
984 | ||
985 | ||
986 | ! |
if (add_density) { |
987 | ! |
plot_call <- substitute( |
988 | ! |
expr = ggExtra::ggMarginal( |
989 | ! |
plot_call + labs + ggthemes + themes, |
990 | ! |
type = "density", |
991 | ! |
groupColour = group_colour |
992 |
), |
|
993 | ! |
env = list( |
994 | ! |
plot_call = plot_call, |
995 | ! |
group_colour = if (length(color_by_var) > 0) TRUE else FALSE, |
996 | ! |
labs = parsed_ggplot2_args$labs, |
997 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
998 | ! |
themes = parsed_ggplot2_args$theme |
999 |
) |
|
1000 |
) |
|
1001 |
} else { |
|
1002 | ! |
plot_call <- substitute( |
1003 | ! |
expr = plot_call + |
1004 | ! |
labs + |
1005 | ! |
ggthemes + |
1006 | ! |
themes, |
1007 | ! |
env = list( |
1008 | ! |
plot_call = plot_call, |
1009 | ! |
labs = parsed_ggplot2_args$labs, |
1010 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
1011 | ! |
themes = parsed_ggplot2_args$theme |
1012 |
) |
|
1013 |
) |
|
1014 |
} |
|
1015 | ||
1016 | ! |
plot_call <- substitute(expr = plot <- plot_call, env = list(plot_call = plot_call)) |
1017 | ||
1018 | ! |
teal.reporter::teal_card(plot_q) <- c(teal.reporter::teal_card(plot_q), "## Plot") |
1019 | ! |
teal.code::eval_code(plot_q, plot_call) |
1020 |
}) |
|
1021 | ||
1022 | ! |
decorated_output_plot_q <- srv_decorate_teal_data( |
1023 | ! |
id = "decorator", |
1024 | ! |
data = output_q, |
1025 | ! |
decorators = select_decorators(decorators, "plot"), |
1026 | ! |
expr = quote(plot) |
1027 |
) |
|
1028 | ||
1029 | ! |
plot_r <- reactive(req(decorated_output_plot_q())[["plot"]]) |
1030 | ||
1031 |
# Insert the plot into a plot_with_settings module from teal.widgets |
|
1032 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
1033 | ! |
id = "scatter_plot", |
1034 | ! |
plot_r = plot_r, |
1035 | ! |
height = plot_height, |
1036 | ! |
width = plot_width, |
1037 | ! |
brushing = TRUE |
1038 |
) |
|
1039 | ||
1040 | ! |
decorated_output_dims_q <- set_chunk_dims(pws, decorated_output_plot_q) |
1041 | ||
1042 | ! |
output$data_table <- DT::renderDataTable({ |
1043 | ! |
plot_brush <- pws$brush() |
1044 | ||
1045 | ! |
if (!is.null(plot_brush)) { |
1046 | ! |
validate(need(!input$add_density, "Brushing feature is currently not supported when plot has marginal density")) |
1047 |
} |
|
1048 | ||
1049 | ! |
merged_data <- isolate(output_q()[["ANL"]]) |
1050 | ||
1051 | ! |
brushed_df <- teal.widgets::clean_brushedPoints(merged_data, plot_brush) |
1052 | ! |
numeric_cols <- names(brushed_df)[ |
1053 | ! |
vapply(brushed_df, function(x) is.numeric(x) && !is.integer(x), FUN.VALUE = logical(1)) |
1054 |
] |
|
1055 | ||
1056 | ! |
if (length(numeric_cols) > 0) { |
1057 | ! |
DT::formatRound( |
1058 | ! |
DT::datatable(brushed_df, |
1059 | ! |
rownames = FALSE, |
1060 | ! |
options = list(scrollX = TRUE, pageLength = input$data_table_rows) |
1061 |
), |
|
1062 | ! |
numeric_cols, |
1063 | ! |
table_dec |
1064 |
) |
|
1065 |
} else { |
|
1066 | ! |
DT::datatable(brushed_df, rownames = FALSE, options = list(scrollX = TRUE, pageLength = input$data_table_rows)) |
1067 |
} |
|
1068 |
}) |
|
1069 | ||
1070 |
# Render R code. |
|
1071 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_output_dims_q()))) |
1072 | ||
1073 | ! |
teal.widgets::verbatim_popup_srv( |
1074 | ! |
id = "rcode", |
1075 | ! |
verbatim_content = source_code_r, |
1076 | ! |
title = "R Code for scatterplot" |
1077 |
) |
|
1078 | ! |
decorated_output_dims_q |
1079 |
}) |
|
1080 |
} |
1 |
#' `teal` module: Response plot |
|
2 |
#' |
|
3 |
#' Generates a response plot for a given `response` and `x` variables. |
|
4 |
#' This module allows users customize and add annotations to the plot depending |
|
5 |
#' on the module's arguments. |
|
6 |
#' It supports showing the counts grouped by other variable facets (by row / column), |
|
7 |
#' swapping the coordinates, show count annotations and displaying the response plot |
|
8 |
#' as frequency or density. |
|
9 |
#' |
|
10 |
#' @inheritParams teal::module |
|
11 |
#' @inheritParams shared_params |
|
12 |
#' @param response (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
13 |
#' Which variable to use as the response. |
|
14 |
#' You can define one fixed column by setting `fixed = TRUE` inside the `select_spec`. |
|
15 |
#' |
|
16 |
#' The `data_extract_spec` must not allow multiple selection in this case. |
|
17 |
#' @param x (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
18 |
#' Specifies which variable to use on the X-axis of the response plot. |
|
19 |
#' Allow the user to select multiple columns from the `data` allowed in teal. |
|
20 |
#' |
|
21 |
#' The `data_extract_spec` must not allow multiple selection in this case. |
|
22 |
#' @param row_facet (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
23 |
#' optional specification of the data variable(s) to use for faceting rows. |
|
24 |
#' @param col_facet (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
25 |
#' optional specification of the data variable(s) to use for faceting columns. |
|
26 |
#' @param coord_flip (`logical(1)`) |
|
27 |
#' Indicates whether to flip coordinates between `x` and `response`. |
|
28 |
#' The default value is `FALSE` and it will show the `x` variable on the x-axis |
|
29 |
#' and the `response` variable on the y-axis. |
|
30 |
#' @param count_labels (`logical(1)`) |
|
31 |
#' Indicates whether to show count labels. |
|
32 |
#' Defaults to `TRUE`. |
|
33 |
#' @param freq (`logical(1)`) |
|
34 |
#' Indicates whether to display frequency (`TRUE`) or density (`FALSE`). |
|
35 |
#' Defaults to density (`FALSE`). |
|
36 |
#' |
|
37 |
#' @inherit shared_params return |
|
38 |
#' |
|
39 |
#' @note For more examples, please see the vignette "Using response plot" via |
|
40 |
#' `vignette("using-response-plot", package = "teal.modules.general")`. |
|
41 |
#' |
|
42 |
#' @section Decorating Module: |
|
43 |
#' |
|
44 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
45 |
#' - `plot` (`ggplot`) |
|
46 |
#' |
|
47 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
48 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
49 |
#' See code snippet below: |
|
50 |
#' |
|
51 |
#' ``` |
|
52 |
#' tm_g_response( |
|
53 |
#' ..., # arguments for module |
|
54 |
#' decorators = list( |
|
55 |
#' plot = teal_transform_module(...) # applied to the `plot` output |
|
56 |
#' ) |
|
57 |
#' ) |
|
58 |
#' ``` |
|
59 |
#' |
|
60 |
#' For additional details and examples of decorators, refer to the vignette |
|
61 |
#' `vignette("decorate-module-output", package = "teal.modules.general")`. |
|
62 |
#' |
|
63 |
#' To learn more please refer to the vignette |
|
64 |
#' `vignette("transform-module-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
65 |
#' |
|
66 |
#' @inheritSection teal::example_module Reporting |
|
67 |
#' |
|
68 |
#' @examplesShinylive |
|
69 |
#' library(teal.modules.general) |
|
70 |
#' interactive <- function() TRUE |
|
71 |
#' {{ next_example }} |
|
72 |
#' @examples |
|
73 |
#' # general data example |
|
74 |
#' data <- teal_data() |
|
75 |
#' data <- within(data, { |
|
76 |
#' require(nestcolor) |
|
77 |
#' mtcars <- mtcars |
|
78 |
#' for (v in c("cyl", "vs", "am", "gear")) { |
|
79 |
#' mtcars[[v]] <- as.factor(mtcars[[v]]) |
|
80 |
#' } |
|
81 |
#' }) |
|
82 |
#' |
|
83 |
#' app <- init( |
|
84 |
#' data = data, |
|
85 |
#' modules = modules( |
|
86 |
#' tm_g_response( |
|
87 |
#' label = "Response Plots", |
|
88 |
#' response = data_extract_spec( |
|
89 |
#' dataname = "mtcars", |
|
90 |
#' select = select_spec( |
|
91 |
#' label = "Select variable:", |
|
92 |
#' choices = variable_choices(data[["mtcars"]], c("cyl", "gear")), |
|
93 |
#' selected = "cyl", |
|
94 |
#' multiple = FALSE, |
|
95 |
#' fixed = FALSE |
|
96 |
#' ) |
|
97 |
#' ), |
|
98 |
#' x = data_extract_spec( |
|
99 |
#' dataname = "mtcars", |
|
100 |
#' select = select_spec( |
|
101 |
#' label = "Select variable:", |
|
102 |
#' choices = variable_choices(data[["mtcars"]], c("vs", "am")), |
|
103 |
#' selected = "vs", |
|
104 |
#' multiple = FALSE, |
|
105 |
#' fixed = FALSE |
|
106 |
#' ) |
|
107 |
#' ) |
|
108 |
#' ) |
|
109 |
#' ) |
|
110 |
#' ) |
|
111 |
#' if (interactive()) { |
|
112 |
#' shinyApp(app$ui, app$server) |
|
113 |
#' } |
|
114 |
#' |
|
115 |
#' @examplesShinylive |
|
116 |
#' library(teal.modules.general) |
|
117 |
#' interactive <- function() TRUE |
|
118 |
#' {{ next_example }} |
|
119 |
#' @examples |
|
120 |
#' # CDISC data example |
|
121 |
#' data <- teal_data() |
|
122 |
#' data <- within(data, { |
|
123 |
#' require(nestcolor) |
|
124 |
#' ADSL <- teal.data::rADSL |
|
125 |
#' }) |
|
126 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
127 |
#' |
|
128 |
#' app <- init( |
|
129 |
#' data = data, |
|
130 |
#' modules = modules( |
|
131 |
#' tm_g_response( |
|
132 |
#' label = "Response Plots", |
|
133 |
#' response = data_extract_spec( |
|
134 |
#' dataname = "ADSL", |
|
135 |
#' select = select_spec( |
|
136 |
#' label = "Select variable:", |
|
137 |
#' choices = variable_choices(data[["ADSL"]], c("BMRKR2", "COUNTRY")), |
|
138 |
#' selected = "BMRKR2", |
|
139 |
#' multiple = FALSE, |
|
140 |
#' fixed = FALSE |
|
141 |
#' ) |
|
142 |
#' ), |
|
143 |
#' x = data_extract_spec( |
|
144 |
#' dataname = "ADSL", |
|
145 |
#' select = select_spec( |
|
146 |
#' label = "Select variable:", |
|
147 |
#' choices = variable_choices(data[["ADSL"]], c("SEX", "RACE")), |
|
148 |
#' selected = "RACE", |
|
149 |
#' multiple = FALSE, |
|
150 |
#' fixed = FALSE |
|
151 |
#' ) |
|
152 |
#' ) |
|
153 |
#' ) |
|
154 |
#' ) |
|
155 |
#' ) |
|
156 |
#' if (interactive()) { |
|
157 |
#' shinyApp(app$ui, app$server) |
|
158 |
#' } |
|
159 |
#' |
|
160 |
#' @export |
|
161 |
#' |
|
162 |
tm_g_response <- function(label = "Response Plot", |
|
163 |
response, |
|
164 |
x, |
|
165 |
row_facet = NULL, |
|
166 |
col_facet = NULL, |
|
167 |
coord_flip = FALSE, |
|
168 |
count_labels = TRUE, |
|
169 |
rotate_xaxis_labels = FALSE, |
|
170 |
freq = FALSE, |
|
171 |
plot_height = c(600, 400, 5000), |
|
172 |
plot_width = NULL, |
|
173 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
174 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
175 |
pre_output = NULL, |
|
176 |
post_output = NULL, |
|
177 |
transformators = list(), |
|
178 |
decorators = list()) { |
|
179 | ! |
message("Initializing tm_g_response") |
180 | ||
181 |
# Normalize the parameters |
|
182 | ! |
if (inherits(response, "data_extract_spec")) response <- list(response) |
183 | ! |
if (inherits(x, "data_extract_spec")) x <- list(x) |
184 | ! |
if (inherits(row_facet, "data_extract_spec")) row_facet <- list(row_facet) |
185 | ! |
if (inherits(col_facet, "data_extract_spec")) col_facet <- list(col_facet) |
186 | ||
187 |
# Start of assertions |
|
188 | ! |
checkmate::assert_string(label) |
189 | ||
190 | ! |
checkmate::assert_list(response, types = "data_extract_spec") |
191 | ! |
if (!all(vapply(response, function(x) !("" %in% x$select$choices), logical(1)))) { |
192 | ! |
stop("'response' should not allow empty values") |
193 |
} |
|
194 | ! |
assert_single_selection(response) |
195 | ||
196 | ! |
checkmate::assert_list(x, types = "data_extract_spec") |
197 | ! |
if (!all(vapply(x, function(x) !("" %in% x$select$choices), logical(1)))) { |
198 | ! |
stop("'x' should not allow empty values") |
199 |
} |
|
200 | ! |
assert_single_selection(x) |
201 | ||
202 | ! |
checkmate::assert_list(row_facet, types = "data_extract_spec", null.ok = TRUE) |
203 | ! |
checkmate::assert_list(col_facet, types = "data_extract_spec", null.ok = TRUE) |
204 | ! |
checkmate::assert_flag(coord_flip) |
205 | ! |
checkmate::assert_flag(count_labels) |
206 | ! |
checkmate::assert_flag(rotate_xaxis_labels) |
207 | ! |
checkmate::assert_flag(freq) |
208 | ||
209 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
210 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
211 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
212 | ! |
checkmate::assert_numeric( |
213 | ! |
plot_width[1], |
214 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
215 |
) |
|
216 | ||
217 | ! |
ggtheme <- match.arg(ggtheme) |
218 | ! |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
219 | ||
220 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
221 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
222 | ||
223 | ! |
assert_decorators(decorators, "plot") |
224 |
# End of assertions |
|
225 | ||
226 |
# Make UI args |
|
227 | ! |
args <- as.list(environment()) |
228 | ||
229 | ! |
data_extract_list <- list( |
230 | ! |
response = response, |
231 | ! |
x = x, |
232 | ! |
row_facet = row_facet, |
233 | ! |
col_facet = col_facet |
234 |
) |
|
235 | ||
236 | ! |
ans <- module( |
237 | ! |
label = label, |
238 | ! |
server = srv_g_response, |
239 | ! |
ui = ui_g_response, |
240 | ! |
ui_args = args, |
241 | ! |
server_args = c( |
242 | ! |
data_extract_list, |
243 | ! |
list( |
244 | ! |
plot_height = plot_height, |
245 | ! |
plot_width = plot_width, |
246 | ! |
ggplot2_args = ggplot2_args, |
247 | ! |
decorators = decorators |
248 |
) |
|
249 |
), |
|
250 | ! |
transformators = transformators, |
251 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
252 |
) |
|
253 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
254 | ! |
ans |
255 |
} |
|
256 | ||
257 |
# UI function for the response module |
|
258 |
ui_g_response <- function(id, ...) { |
|
259 | ! |
ns <- NS(id) |
260 | ! |
args <- list(...) |
261 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$response, args$x, args$row_facet, args$col_facet) |
262 | ||
263 | ! |
teal.widgets::standard_layout( |
264 | ! |
output = teal.widgets::white_small_well( |
265 | ! |
teal.widgets::plot_with_settings_ui(id = ns("myplot")) |
266 |
), |
|
267 | ! |
encoding = tags$div( |
268 | ! |
tags$label("Encodings", class = "text-primary"), |
269 | ! |
teal.transform::datanames_input(args[c("response", "x", "row_facet", "col_facet")]), |
270 | ! |
teal.transform::data_extract_ui( |
271 | ! |
id = ns("response"), |
272 | ! |
label = "Response variable", |
273 | ! |
data_extract_spec = args$response, |
274 | ! |
is_single_dataset = is_single_dataset_value |
275 |
), |
|
276 | ! |
teal.transform::data_extract_ui( |
277 | ! |
id = ns("x"), |
278 | ! |
label = "X variable", |
279 | ! |
data_extract_spec = args$x, |
280 | ! |
is_single_dataset = is_single_dataset_value |
281 |
), |
|
282 | ! |
if (!is.null(args$row_facet)) { |
283 | ! |
teal.transform::data_extract_ui( |
284 | ! |
id = ns("row_facet"), |
285 | ! |
label = "Row facetting", |
286 | ! |
data_extract_spec = args$row_facet, |
287 | ! |
is_single_dataset = is_single_dataset_value |
288 |
) |
|
289 |
}, |
|
290 | ! |
if (!is.null(args$col_facet)) { |
291 | ! |
teal.transform::data_extract_ui( |
292 | ! |
id = ns("col_facet"), |
293 | ! |
label = "Column facetting", |
294 | ! |
data_extract_spec = args$col_facet, |
295 | ! |
is_single_dataset = is_single_dataset_value |
296 |
) |
|
297 |
}, |
|
298 | ! |
shinyWidgets::radioGroupButtons( |
299 | ! |
inputId = ns("freq"), |
300 | ! |
label = NULL, |
301 | ! |
choices = c("frequency", "density"), |
302 | ! |
selected = ifelse(args$freq, "frequency", "density"), |
303 | ! |
justified = TRUE |
304 |
), |
|
305 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")), |
306 | ! |
bslib::accordion( |
307 | ! |
open = TRUE, |
308 | ! |
bslib::accordion_panel( |
309 | ! |
title = "Plot settings", |
310 | ! |
checkboxInput(ns("count_labels"), "Add count labels", value = args$count_labels), |
311 | ! |
checkboxInput(ns("coord_flip"), "Swap axes", value = args$coord_flip), |
312 | ! |
checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = args$rotate_xaxis_labels), |
313 | ! |
selectInput( |
314 | ! |
inputId = ns("ggtheme"), |
315 | ! |
label = "Theme (by ggplot):", |
316 | ! |
choices = ggplot_themes, |
317 | ! |
selected = args$ggtheme, |
318 | ! |
multiple = FALSE |
319 |
) |
|
320 |
) |
|
321 |
) |
|
322 |
), |
|
323 | ! |
forms = tagList( |
324 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
325 |
), |
|
326 | ! |
pre_output = args$pre_output, |
327 | ! |
post_output = args$post_output |
328 |
) |
|
329 |
} |
|
330 | ||
331 |
# Server function for the response module |
|
332 |
srv_g_response <- function(id, |
|
333 |
data, |
|
334 |
response, |
|
335 |
x, |
|
336 |
row_facet, |
|
337 |
col_facet, |
|
338 |
plot_height, |
|
339 |
plot_width, |
|
340 |
ggplot2_args, |
|
341 |
decorators) { |
|
342 | ! |
checkmate::assert_class(data, "reactive") |
343 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
344 | ! |
moduleServer(id, function(input, output, session) { |
345 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
346 | ||
347 | ! |
data_extract <- list(response = response, x = x, row_facet = row_facet, col_facet = col_facet) |
348 | ||
349 | ! |
rule_diff <- function(other) { |
350 | ! |
function(value) { |
351 | ! |
if (other %in% names(selector_list())) { |
352 | ! |
othervalue <- selector_list()[[other]]()[["select"]] |
353 | ! |
if (!is.null(othervalue)) { |
354 | ! |
if (identical(value, othervalue)) { |
355 | ! |
"Row and column facetting variables must be different." |
356 |
} |
|
357 |
} |
|
358 |
} |
|
359 |
} |
|
360 |
} |
|
361 | ||
362 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
363 | ! |
data_extract = data_extract, |
364 | ! |
datasets = data, |
365 | ! |
select_validation_rule = list( |
366 | ! |
response = shinyvalidate::sv_required("Please define a column for the response variable"), |
367 | ! |
x = shinyvalidate::sv_required("Please define a column for X variable"), |
368 | ! |
row_facet = shinyvalidate::compose_rules( |
369 | ! |
shinyvalidate::sv_optional(), |
370 | ! |
~ if (length(.) > 1) "There must be 1 or no row facetting variable.", |
371 | ! |
rule_diff("col_facet") |
372 |
), |
|
373 | ! |
col_facet = shinyvalidate::compose_rules( |
374 | ! |
shinyvalidate::sv_optional(), |
375 | ! |
~ if (length(.) > 1) "There must be 1 or no column facetting variable.", |
376 | ! |
rule_diff("row_facet") |
377 |
) |
|
378 |
) |
|
379 |
) |
|
380 | ||
381 | ! |
iv_r <- reactive({ |
382 | ! |
iv <- shinyvalidate::InputValidator$new() |
383 | ! |
iv$add_rule("ggtheme", shinyvalidate::sv_required("Please select a theme")) |
384 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
385 |
}) |
|
386 | ||
387 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
388 | ! |
selector_list = selector_list, |
389 | ! |
datasets = data |
390 |
) |
|
391 | ||
392 | ! |
qenv <- reactive( |
393 | ! |
teal.code::eval_code(data(), 'library("ggplot2");library("dplyr")') # nolint quotes |
394 |
) |
|
395 | ||
396 | ! |
anl_merged_q <- reactive({ |
397 | ! |
req(anl_merged_input()) |
398 | ! |
qenv() %>% |
399 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
400 |
}) |
|
401 | ||
402 | ! |
merged <- list( |
403 | ! |
anl_input_r = anl_merged_input, |
404 | ! |
anl_q_r = anl_merged_q |
405 |
) |
|
406 | ||
407 | ! |
output_q <- reactive({ |
408 | ! |
teal::validate_inputs(iv_r()) |
409 | ||
410 | ! |
qenv <- merged$anl_q_r() |
411 | ! |
teal.reporter::teal_card(qenv) <- |
412 | ! |
c( |
413 | ! |
teal.reporter::teal_card("# Response Plot"), |
414 | ! |
teal.reporter::teal_card(qenv), |
415 | ! |
teal.reporter::teal_card("## Module's code") |
416 |
) |
|
417 | ! |
ANL <- qenv[["ANL"]] |
418 | ! |
resp_var <- as.vector(merged$anl_input_r()$columns_source$response) |
419 | ! |
x <- as.vector(merged$anl_input_r()$columns_source$x) |
420 | ||
421 | ! |
validate(need(is.factor(ANL[[resp_var]]), "Please select a factor variable as the response.")) |
422 | ! |
validate(need(is.factor(ANL[[x]]), "Please select a factor variable as the X-Variable.")) |
423 | ! |
teal::validate_has_data(ANL, 10) |
424 | ! |
teal::validate_has_data(ANL[, c(resp_var, x)], 10, complete = TRUE, allow_inf = FALSE) |
425 | ||
426 | ! |
row_facet_name <- if (length(merged$anl_input_r()$columns_source$row_facet) == 0) { |
427 | ! |
character(0) |
428 |
} else { |
|
429 | ! |
as.vector(merged$anl_input_r()$columns_source$row_facet) |
430 |
} |
|
431 | ! |
col_facet_name <- if (length(merged$anl_input_r()$columns_source$col_facet) == 0) { |
432 | ! |
character(0) |
433 |
} else { |
|
434 | ! |
as.vector(merged$anl_input_r()$columns_source$col_facet) |
435 |
} |
|
436 | ||
437 | ! |
freq <- input$freq == "frequency" |
438 | ! |
swap_axes <- input$coord_flip |
439 | ! |
counts <- input$count_labels |
440 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
441 | ! |
ggtheme <- input$ggtheme |
442 | ||
443 | ! |
arg_position <- if (freq) "stack" else "fill" |
444 | ||
445 | ! |
rowf <- if (length(row_facet_name) != 0) as.name(row_facet_name) |
446 | ! |
colf <- if (length(col_facet_name) != 0) as.name(col_facet_name) |
447 | ! |
resp_cl <- as.name(resp_var) |
448 | ! |
x_cl <- as.name(x) |
449 | ||
450 | ! |
if (swap_axes) { |
451 | ! |
qenv <- teal.code::eval_code( |
452 | ! |
qenv, |
453 | ! |
substitute( |
454 | ! |
expr = ANL[[x]] <- with(ANL, forcats::fct_rev(x_cl)), |
455 | ! |
env = list(x = x, x_cl = x_cl) |
456 |
) |
|
457 |
) |
|
458 |
} |
|
459 | ||
460 | ! |
qenv <- teal.code::eval_code( |
461 | ! |
qenv, |
462 | ! |
substitute( |
463 | ! |
expr = ANL[[resp_var]] <- factor(ANL[[resp_var]]), |
464 | ! |
env = list(resp_var = resp_var) |
465 |
) |
|
466 |
) %>% |
|
467 |
# rowf and colf will be a NULL if not set by a user |
|
468 | ! |
teal.code::eval_code( |
469 | ! |
substitute( |
470 | ! |
expr = ANL2 <- ANL %>% |
471 | ! |
dplyr::group_by_at(dplyr::vars(x_cl, resp_cl, rowf, colf)) %>% |
472 | ! |
dplyr::summarise(ns = dplyr::n()) %>% |
473 | ! |
dplyr::group_by_at(dplyr::vars(x_cl, rowf, colf)) %>% |
474 | ! |
dplyr::mutate(sums = sum(ns), percent = round(ns / sums * 100, 1)), |
475 | ! |
env = list(x_cl = x_cl, resp_cl = resp_cl, rowf = rowf, colf = colf) |
476 |
) |
|
477 |
) %>% |
|
478 | ! |
teal.code::eval_code( |
479 | ! |
substitute( |
480 | ! |
expr = ANL3 <- ANL %>% |
481 | ! |
dplyr::group_by_at(dplyr::vars(x_cl, rowf, colf)) %>% |
482 | ! |
dplyr::summarise(ns = dplyr::n()), |
483 | ! |
env = list(x_cl = x_cl, rowf = rowf, colf = colf) |
484 |
) |
|
485 |
) |
|
486 | ||
487 | ! |
plot_call <- substitute( |
488 | ! |
expr = ggplot2::ggplot(ANL2, ggplot2::aes(x = x_cl, y = ns)) + |
489 | ! |
ggplot2::geom_bar(ggplot2::aes(fill = resp_cl), stat = "identity", position = arg_position), |
490 | ! |
env = list( |
491 | ! |
x_cl = x_cl, |
492 | ! |
resp_cl = resp_cl, |
493 | ! |
arg_position = arg_position |
494 |
) |
|
495 |
) |
|
496 | ||
497 | ! |
if (!freq) { |
498 | ! |
plot_call <- substitute( |
499 | ! |
plot_call + ggplot2::expand_limits(y = c(0, 1.1)), |
500 | ! |
env = list(plot_call = plot_call) |
501 |
) |
|
502 |
} |
|
503 | ||
504 | ! |
if (counts) { |
505 | ! |
plot_call <- substitute( |
506 | ! |
expr = plot_call + |
507 | ! |
ggplot2::geom_text( |
508 | ! |
data = ANL2, |
509 | ! |
ggplot2::aes(label = ns, x = x_cl, y = ns, group = resp_cl), |
510 | ! |
col = "white", |
511 | ! |
vjust = "middle", |
512 | ! |
hjust = "middle", |
513 | ! |
position = position_anl2_value |
514 |
) + |
|
515 | ! |
ggplot2::geom_text( |
516 | ! |
data = ANL3, ggplot2::aes(label = ns, x = x_cl, y = anl3_y), |
517 | ! |
hjust = hjust_value, |
518 | ! |
vjust = vjust_value, |
519 | ! |
position = position_anl3_value |
520 |
), |
|
521 | ! |
env = list( |
522 | ! |
plot_call = plot_call, |
523 | ! |
x_cl = x_cl, |
524 | ! |
resp_cl = resp_cl, |
525 | ! |
hjust_value = if (swap_axes) "left" else "middle", |
526 | ! |
vjust_value = if (swap_axes) "middle" else -1, |
527 | ! |
position_anl2_value = if (!freq) quote(position_fill(0.5)) else quote(position_stack(0.5)), # nolint: line_length. |
528 | ! |
anl3_y = if (!freq) 1.1 else as.name("ns"), |
529 | ! |
position_anl3_value = if (!freq) "fill" else "stack" |
530 |
) |
|
531 |
) |
|
532 |
} |
|
533 | ||
534 | ! |
if (swap_axes) { |
535 | ! |
plot_call <- substitute(plot_call + coord_flip(), env = list(plot_call = plot_call)) |
536 |
} |
|
537 | ||
538 | ! |
facet_cl <- facet_ggplot_call(row_facet_name, col_facet_name) |
539 | ||
540 | ! |
if (!is.null(facet_cl)) { |
541 | ! |
plot_call <- substitute(expr = plot_call + facet_cl, env = list(plot_call = plot_call, facet_cl = facet_cl)) |
542 |
} |
|
543 | ||
544 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
545 | ! |
labs = list( |
546 | ! |
x = varname_w_label(x, ANL), |
547 | ! |
y = varname_w_label(resp_var, ANL, prefix = "Proportion of "), |
548 | ! |
fill = varname_w_label(resp_var, ANL) |
549 |
), |
|
550 | ! |
theme = list(legend.position = "bottom") |
551 |
) |
|
552 | ||
553 | ! |
if (rotate_xaxis_labels) { |
554 | ! |
dev_ggplot2_args$theme[["axis.text.x"]] <- quote(ggplot2::element_text(angle = 45, hjust = 1)) |
555 |
} |
|
556 | ||
557 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
558 | ! |
user_plot = ggplot2_args, |
559 | ! |
module_plot = dev_ggplot2_args |
560 |
) |
|
561 | ||
562 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
563 | ! |
all_ggplot2_args, |
564 | ! |
ggtheme = ggtheme |
565 |
) |
|
566 | ||
567 | ! |
plot_call <- substitute(expr = { |
568 | ! |
plot <- plot_call + labs + ggthemes + themes |
569 | ! |
}, env = list( |
570 | ! |
plot_call = plot_call, |
571 | ! |
labs = parsed_ggplot2_args$labs, |
572 | ! |
themes = parsed_ggplot2_args$theme, |
573 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
574 |
)) |
|
575 | ||
576 | ! |
teal.reporter::teal_card(qenv) <- c(teal.reporter::teal_card(qenv), "## Plot") |
577 | ! |
teal.code::eval_code(qenv, plot_call) |
578 |
}) |
|
579 | ||
580 | ! |
decorated_output_plot_q <- srv_decorate_teal_data( |
581 | ! |
id = "decorator", |
582 | ! |
data = output_q, |
583 | ! |
decorators = select_decorators(decorators, "plot"), |
584 | ! |
expr = quote(plot) |
585 |
) |
|
586 | ||
587 | ! |
plot_r <- reactive(req(decorated_output_plot_q())[["plot"]]) |
588 | ||
589 |
# Insert the plot into a plot_with_settings module from teal.widgets |
|
590 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
591 | ! |
id = "myplot", |
592 | ! |
plot_r = plot_r, |
593 | ! |
height = plot_height, |
594 | ! |
width = plot_width |
595 |
) |
|
596 | ||
597 | ! |
decorated_output_dims_q <- set_chunk_dims(pws, decorated_output_plot_q) |
598 | ||
599 |
# Render R code. |
|
600 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_output_dims_q()))) |
601 | ||
602 | ! |
teal.widgets::verbatim_popup_srv( |
603 | ! |
id = "rcode", |
604 | ! |
verbatim_content = source_code_r, |
605 | ! |
title = "Show R Code for Response" |
606 |
) |
|
607 | ! |
decorated_output_dims_q |
608 |
}) |
|
609 |
} |
1 |
#' `teal` module: Outliers analysis |
|
2 |
#' |
|
3 |
#' Module to analyze and identify outliers using different methods |
|
4 |
#' such as IQR, Z-score, and Percentiles, and offers visualizations including |
|
5 |
#' box plots, density plots, and cumulative distribution plots to help interpret the outliers. |
|
6 |
#' |
|
7 |
#' @inheritParams teal::module |
|
8 |
#' @inheritParams shared_params |
|
9 |
#' |
|
10 |
#' @param outlier_var (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
11 |
#' Specifies variable(s) to be analyzed for outliers. |
|
12 |
#' @param categorical_var (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
13 |
#' specifies the categorical variable(s) to split the selected outlier variables on. |
|
14 |
#' @param ggplot2_args `r roxygen_ggplot2_args_param("Boxplot", "Density Plot", "Cumulative Distribution Plot")` |
|
15 |
#' |
|
16 |
#' @inherit shared_params return |
|
17 |
#' |
|
18 |
#' @section Decorating Module: |
|
19 |
#' |
|
20 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
21 |
#' - `box_plot` (`ggplot`) |
|
22 |
#' - `density_plot` (`ggplot`) |
|
23 |
#' - `cumulative_plot` (`ggplot`) |
|
24 |
#' |
|
25 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
26 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
27 |
#' See code snippet below: |
|
28 |
#' |
|
29 |
#' ``` |
|
30 |
#' tm_outliers( |
|
31 |
#' ..., # arguments for module |
|
32 |
#' decorators = list( |
|
33 |
#' box_plot = teal_transform_module(...), # applied only to `box_plot` output |
|
34 |
#' density_plot = teal_transform_module(...), # applied only to `density_plot` output |
|
35 |
#' cumulative_plot = teal_transform_module(...) # applied only to `cumulative_plot` output |
|
36 |
#' ) |
|
37 |
#' ) |
|
38 |
#' ``` |
|
39 |
#' |
|
40 |
#' For additional details and examples of decorators, refer to the vignette |
|
41 |
#' `vignette("decorate-module-output", package = "teal.modules.general")`. |
|
42 |
#' |
|
43 |
#' To learn more please refer to the vignette |
|
44 |
#' `vignette("transform-module-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
45 |
#' |
|
46 |
#' @inheritSection teal::example_module Reporting |
|
47 |
#' |
|
48 |
#' @examplesShinylive |
|
49 |
#' library(teal.modules.general) |
|
50 |
#' interactive <- function() TRUE |
|
51 |
#' {{ next_example }} |
|
52 |
#' @examples |
|
53 |
#' |
|
54 |
#' # general data example |
|
55 |
#' data <- teal_data() |
|
56 |
#' data <- within(data, { |
|
57 |
#' CO2 <- CO2 |
|
58 |
#' CO2[["primary_key"]] <- seq_len(nrow(CO2)) |
|
59 |
#' }) |
|
60 |
#' join_keys(data) <- join_keys(join_key("CO2", "CO2", "primary_key")) |
|
61 |
#' |
|
62 |
#' vars <- choices_selected(variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment"))) |
|
63 |
#' |
|
64 |
#' app <- init( |
|
65 |
#' data = data, |
|
66 |
#' modules = modules( |
|
67 |
#' tm_outliers( |
|
68 |
#' outlier_var = list( |
|
69 |
#' data_extract_spec( |
|
70 |
#' dataname = "CO2", |
|
71 |
#' select = select_spec( |
|
72 |
#' label = "Select variable:", |
|
73 |
#' choices = variable_choices(data[["CO2"]], c("conc", "uptake")), |
|
74 |
#' selected = "uptake", |
|
75 |
#' multiple = FALSE, |
|
76 |
#' fixed = FALSE |
|
77 |
#' ) |
|
78 |
#' ) |
|
79 |
#' ), |
|
80 |
#' categorical_var = list( |
|
81 |
#' data_extract_spec( |
|
82 |
#' dataname = "CO2", |
|
83 |
#' filter = filter_spec( |
|
84 |
#' vars = vars, |
|
85 |
#' choices = value_choices(data[["CO2"]], vars$selected), |
|
86 |
#' selected = value_choices(data[["CO2"]], vars$selected), |
|
87 |
#' multiple = TRUE |
|
88 |
#' ) |
|
89 |
#' ) |
|
90 |
#' ) |
|
91 |
#' ) |
|
92 |
#' ) |
|
93 |
#' ) |
|
94 |
#' if (interactive()) { |
|
95 |
#' shinyApp(app$ui, app$server) |
|
96 |
#' } |
|
97 |
#' |
|
98 |
#' @examplesShinylive |
|
99 |
#' library(teal.modules.general) |
|
100 |
#' interactive <- function() TRUE |
|
101 |
#' {{ next_example }} |
|
102 |
#' @examples |
|
103 |
#' |
|
104 |
#' # CDISC data example |
|
105 |
#' data <- teal_data() |
|
106 |
#' data <- within(data, { |
|
107 |
#' ADSL <- teal.data::rADSL |
|
108 |
#' }) |
|
109 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
110 |
#' |
|
111 |
#' fact_vars_adsl <- names(Filter(isTRUE, sapply(data[["ADSL"]], is.factor))) |
|
112 |
#' vars <- choices_selected(variable_choices(data[["ADSL"]], fact_vars_adsl)) |
|
113 |
#' |
|
114 |
#' |
|
115 |
#' |
|
116 |
#' app <- init( |
|
117 |
#' data = data, |
|
118 |
#' modules = modules( |
|
119 |
#' tm_outliers( |
|
120 |
#' outlier_var = list( |
|
121 |
#' data_extract_spec( |
|
122 |
#' dataname = "ADSL", |
|
123 |
#' select = select_spec( |
|
124 |
#' label = "Select variable:", |
|
125 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1")), |
|
126 |
#' selected = "AGE", |
|
127 |
#' multiple = FALSE, |
|
128 |
#' fixed = FALSE |
|
129 |
#' ) |
|
130 |
#' ) |
|
131 |
#' ), |
|
132 |
#' categorical_var = list( |
|
133 |
#' data_extract_spec( |
|
134 |
#' dataname = "ADSL", |
|
135 |
#' filter = filter_spec( |
|
136 |
#' vars = vars, |
|
137 |
#' choices = value_choices(data[["ADSL"]], vars$selected), |
|
138 |
#' selected = value_choices(data[["ADSL"]], vars$selected), |
|
139 |
#' multiple = TRUE |
|
140 |
#' ) |
|
141 |
#' ) |
|
142 |
#' ) |
|
143 |
#' ) |
|
144 |
#' ) |
|
145 |
#' ) |
|
146 |
#' if (interactive()) { |
|
147 |
#' shinyApp(app$ui, app$server) |
|
148 |
#' } |
|
149 |
#' |
|
150 |
#' @export |
|
151 |
#' |
|
152 |
tm_outliers <- function(label = "Outliers Module", |
|
153 |
outlier_var, |
|
154 |
categorical_var = NULL, |
|
155 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
156 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
157 |
plot_height = c(600, 200, 2000), |
|
158 |
plot_width = NULL, |
|
159 |
pre_output = NULL, |
|
160 |
post_output = NULL, |
|
161 |
transformators = list(), |
|
162 |
decorators = list()) { |
|
163 | ! |
message("Initializing tm_outliers") |
164 | ||
165 |
# Normalize the parameters |
|
166 | ! |
if (inherits(outlier_var, "data_extract_spec")) outlier_var <- list(outlier_var) |
167 | ! |
if (inherits(categorical_var, "data_extract_spec")) categorical_var <- list(categorical_var) |
168 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
169 | ||
170 |
# Start of assertions |
|
171 | ! |
checkmate::assert_string(label) |
172 | ! |
checkmate::assert_list(outlier_var, types = "data_extract_spec") |
173 | ||
174 | ! |
checkmate::assert_list(categorical_var, types = "data_extract_spec", null.ok = TRUE) |
175 | ! |
if (is.list(categorical_var)) { |
176 | ! |
lapply(categorical_var, function(x) { |
177 | ! |
if (length(x$filter) > 1L) { |
178 | ! |
stop("tm_outliers: categorical_var data_extract_specs may only specify one filter_spec", call. = FALSE) |
179 |
} |
|
180 |
}) |
|
181 |
} |
|
182 | ||
183 | ! |
ggtheme <- match.arg(ggtheme) |
184 | ||
185 | ! |
plot_choices <- c("Boxplot", "Density Plot", "Cumulative Distribution Plot") |
186 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
187 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
188 | ||
189 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
190 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
191 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
192 | ! |
checkmate::assert_numeric( |
193 | ! |
plot_width[1], |
194 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
195 |
) |
|
196 | ||
197 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
198 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
199 | ||
200 | ! |
assert_decorators(decorators, names = c("box_plot", "density_plot", "cumulative_plot")) |
201 |
# End of assertions |
|
202 | ||
203 |
# Make UI args |
|
204 | ! |
args <- as.list(environment()) |
205 | ||
206 | ! |
data_extract_list <- list( |
207 | ! |
outlier_var = outlier_var, |
208 | ! |
categorical_var = categorical_var |
209 |
) |
|
210 | ||
211 | ||
212 | ! |
ans <- module( |
213 | ! |
label = label, |
214 | ! |
server = srv_outliers, |
215 | ! |
server_args = c( |
216 | ! |
data_extract_list, |
217 | ! |
list( |
218 | ! |
plot_height = plot_height, plot_width = plot_width, ggplot2_args = ggplot2_args, |
219 | ! |
decorators = decorators |
220 |
) |
|
221 |
), |
|
222 | ! |
ui = ui_outliers, |
223 | ! |
ui_args = args, |
224 | ! |
transformators = transformators, |
225 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
226 |
) |
|
227 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
228 | ! |
ans |
229 |
} |
|
230 | ||
231 |
# UI function for the outliers module |
|
232 |
ui_outliers <- function(id, ...) { |
|
233 | ! |
args <- list(...) |
234 | ! |
ns <- NS(id) |
235 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$outlier_var, args$categorical_var) |
236 | ||
237 | ! |
teal.widgets::standard_layout( |
238 | ! |
output = teal.widgets::white_small_well( |
239 | ! |
uiOutput(ns("total_outliers")), |
240 | ! |
tags$div( |
241 | ! |
style = "overflow: auto;", |
242 | ! |
DT::dataTableOutput(ns("summary_table")) |
243 |
), |
|
244 | ! |
uiOutput(ns("total_missing")), |
245 | ! |
tags$br(), tags$hr(), |
246 | ! |
tabsetPanel( |
247 | ! |
id = ns("tabs"), |
248 | ! |
tabPanel( |
249 | ! |
"Boxplot", |
250 | ! |
teal.widgets::plot_with_settings_ui(id = ns("box_plot")) |
251 |
), |
|
252 | ! |
tabPanel( |
253 | ! |
"Density Plot", |
254 | ! |
teal.widgets::plot_with_settings_ui(id = ns("density_plot")) |
255 |
), |
|
256 | ! |
tabPanel( |
257 | ! |
"Cumulative Distribution Plot", |
258 | ! |
teal.widgets::plot_with_settings_ui(id = ns("cum_density_plot")) |
259 |
) |
|
260 |
), |
|
261 | ! |
tags$br(), tags$hr(), |
262 | ! |
uiOutput(ns("table_ui_wrap")), |
263 | ! |
DT::dataTableOutput(ns("table_ui")) |
264 |
), |
|
265 | ! |
encoding = tags$div( |
266 | ! |
tags$label("Encodings", class = "text-primary"), |
267 | ! |
teal.transform::datanames_input(args[c("outlier_var", "categorical_var")]), |
268 | ! |
teal.transform::data_extract_ui( |
269 | ! |
id = ns("outlier_var"), |
270 | ! |
label = "Variable", |
271 | ! |
data_extract_spec = args$outlier_var, |
272 | ! |
is_single_dataset = is_single_dataset_value |
273 |
), |
|
274 | ! |
if (!is.null(args$categorical_var)) { |
275 | ! |
teal.transform::data_extract_ui( |
276 | ! |
id = ns("categorical_var"), |
277 | ! |
label = "Categorical factor", |
278 | ! |
data_extract_spec = args$categorical_var, |
279 | ! |
is_single_dataset = is_single_dataset_value |
280 |
) |
|
281 |
}, |
|
282 | ! |
conditionalPanel( |
283 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'Boxplot'"), |
284 | ! |
teal.widgets::optionalSelectInput( |
285 | ! |
inputId = ns("boxplot_alts"), |
286 | ! |
label = "Plot type", |
287 | ! |
choices = c("Box plot", "Violin plot"), |
288 | ! |
selected = "Box plot", |
289 | ! |
multiple = FALSE |
290 |
) |
|
291 |
), |
|
292 | ! |
shinyjs::hidden(checkboxInput(ns("split_outliers"), "Define outliers based on group splitting", value = FALSE)), |
293 | ! |
shinyjs::hidden(checkboxInput(ns("order_by_outlier"), "Re-order categories by outliers [by %]", value = FALSE)), |
294 | ! |
bslib::accordion( |
295 | ! |
open = TRUE, |
296 | ! |
bslib::accordion_panel( |
297 | ! |
title = "Method parameters", |
298 | ! |
collapsed = FALSE, |
299 | ! |
teal.widgets::optionalSelectInput( |
300 | ! |
inputId = ns("method"), |
301 | ! |
label = "Method", |
302 | ! |
choices = c("IQR", "Z-score", "Percentile"), |
303 | ! |
selected = "IQR", |
304 | ! |
multiple = FALSE |
305 |
), |
|
306 | ! |
conditionalPanel( |
307 | ! |
condition = |
308 | ! |
paste0("input['", ns("method"), "'] == 'IQR'"), |
309 | ! |
sliderInput( |
310 | ! |
ns("iqr_slider"), |
311 | ! |
"Outlier range:", |
312 | ! |
min = 1, |
313 | ! |
max = 5, |
314 | ! |
value = 3, |
315 | ! |
step = 0.5 |
316 |
) |
|
317 |
), |
|
318 | ! |
conditionalPanel( |
319 | ! |
condition = |
320 | ! |
paste0("input['", ns("method"), "'] == 'Z-score'"), |
321 | ! |
sliderInput( |
322 | ! |
ns("zscore_slider"), |
323 | ! |
"Outlier range:", |
324 | ! |
min = 1, |
325 | ! |
max = 5, |
326 | ! |
value = 3, |
327 | ! |
step = 0.5 |
328 |
) |
|
329 |
), |
|
330 | ! |
conditionalPanel( |
331 | ! |
condition = |
332 | ! |
paste0("input['", ns("method"), "'] == 'Percentile'"), |
333 | ! |
sliderInput( |
334 | ! |
ns("percentile_slider"), |
335 | ! |
"Outlier range:", |
336 | ! |
min = 0.001, |
337 | ! |
max = 0.5, |
338 | ! |
value = 0.01, |
339 | ! |
step = 0.001 |
340 |
) |
|
341 |
), |
|
342 | ! |
uiOutput(ns("ui_outlier_help")) |
343 |
) |
|
344 |
), |
|
345 | ! |
conditionalPanel( |
346 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'Boxplot'"), |
347 | ! |
ui_decorate_teal_data( |
348 | ! |
ns("d_box_plot"), |
349 | ! |
decorators = select_decorators(args$decorators, "box_plot") |
350 |
) |
|
351 |
), |
|
352 | ! |
conditionalPanel( |
353 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'Density Plot'"), |
354 | ! |
ui_decorate_teal_data( |
355 | ! |
ns("d_density_plot"), |
356 | ! |
decorators = select_decorators(args$decorators, "density_plot") |
357 |
) |
|
358 |
), |
|
359 | ! |
conditionalPanel( |
360 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'Cumulative Distribution Plot'"), |
361 | ! |
ui_decorate_teal_data( |
362 | ! |
ns("d_cumulative_plot"), |
363 | ! |
decorators = select_decorators(args$decorators, "cumulative_plot") |
364 |
) |
|
365 |
), |
|
366 | ! |
bslib::accordion_panel( |
367 | ! |
title = "Plot settings", |
368 | ! |
selectInput( |
369 | ! |
inputId = ns("ggtheme"), |
370 | ! |
label = "Theme (by ggplot):", |
371 | ! |
choices = ggplot_themes, |
372 | ! |
selected = args$ggtheme, |
373 | ! |
multiple = FALSE |
374 |
) |
|
375 |
) |
|
376 |
), |
|
377 | ! |
forms = tagList( |
378 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
379 |
), |
|
380 | ! |
pre_output = args$pre_output, |
381 | ! |
post_output = args$post_output |
382 |
) |
|
383 |
} |
|
384 | ||
385 |
# Server function for the outliers module |
|
386 |
# Server function for the outliers module |
|
387 |
srv_outliers <- function(id, data, outlier_var, |
|
388 |
categorical_var, plot_height, plot_width, ggplot2_args, decorators) { |
|
389 | ! |
checkmate::assert_class(data, "reactive") |
390 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
391 | ! |
moduleServer(id, function(input, output, session) { |
392 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
393 | ||
394 | ! |
ns <- session$ns |
395 | ||
396 | ! |
vars <- list(outlier_var = outlier_var, categorical_var = categorical_var) |
397 | ||
398 | ! |
rule_diff <- function(other) { |
399 | ! |
function(value) { |
400 | ! |
othervalue <- tryCatch(selector_list()[[other]]()[["select"]], error = function(e) NULL) |
401 | ! |
if (!is.null(othervalue) && identical(othervalue, value)) { |
402 | ! |
"`Variable` and `Categorical factor` cannot be the same" |
403 |
} |
|
404 |
} |
|
405 |
} |
|
406 | ||
407 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
408 | ! |
data_extract = vars, |
409 | ! |
datasets = data, |
410 | ! |
select_validation_rule = list( |
411 | ! |
outlier_var = shinyvalidate::compose_rules( |
412 | ! |
shinyvalidate::sv_required("Please select a variable"), |
413 | ! |
rule_diff("categorical_var") |
414 |
), |
|
415 | ! |
categorical_var = rule_diff("outlier_var") |
416 |
) |
|
417 |
) |
|
418 | ||
419 | ! |
iv_r <- reactive({ |
420 | ! |
iv <- shinyvalidate::InputValidator$new() |
421 | ! |
iv$add_rule("method", shinyvalidate::sv_required("Please select a method")) |
422 | ! |
iv$add_rule("boxplot_alts", shinyvalidate::sv_required("Please select Plot Type")) |
423 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
424 |
}) |
|
425 | ||
426 | ! |
reactive_select_input <- reactive({ |
427 | ! |
if (is.null(selector_list()$categorical_var) || length(selector_list()$categorical_var()$select) == 0) { |
428 | ! |
selector_list()[names(selector_list()) != "categorical_var"] |
429 |
} else { |
|
430 | ! |
selector_list() |
431 |
} |
|
432 |
}) |
|
433 | ||
434 |
# Used to create outlier table and the dropdown with additional columns |
|
435 | ! |
dataname_first <- isolate(names(data())[[1]]) |
436 | ||
437 | ! |
data_obj <- reactive({ |
438 | ! |
obj <- data() |
439 | ! |
if (length(teal.data::join_keys(obj)) == 0) { |
440 | ! |
if (!".row_id" %in% names(obj[[dataname_first]])) { |
441 | ! |
obj[[dataname_first]]$.row_id <- seq_len(nrow(obj[[dataname_first]])) |
442 |
} |
|
443 | ! |
teal.data::join_keys(obj) <- |
444 | ! |
teal.data::join_keys(teal.data::join_key(dataname_first, dataname_first, ".row_id")) |
445 |
} |
|
446 | ! |
obj |
447 |
}) |
|
448 | ||
449 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
450 | ! |
selector_list = reactive_select_input, |
451 | ! |
datasets = data_obj, |
452 | ! |
merge_function = "dplyr::inner_join" |
453 |
) |
|
454 | ||
455 | ! |
anl_merged_q <- reactive({ |
456 | ! |
req(anl_merged_input()) |
457 | ! |
teal.code::eval_code( |
458 | ! |
data_obj(), |
459 | ! |
'library("dplyr");library("tidyr");library("tibble");library("ggplot2")' # nolint quotes |
460 |
) %>% |
|
461 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
462 |
}) |
|
463 | ||
464 | ! |
merged <- list( |
465 | ! |
anl_input_r = anl_merged_input, |
466 | ! |
anl_q_r = anl_merged_q |
467 |
) |
|
468 | ||
469 | ! |
n_outlier_missing <- reactive({ |
470 | ! |
req(iv_r()$is_valid()) |
471 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
472 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
473 | ! |
sum(is.na(ANL[[outlier_var]])) |
474 |
}) |
|
475 | ||
476 | ! |
common_code_q <- reactive({ |
477 | ! |
req(iv_r()$is_valid()) |
478 | ||
479 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
480 | ! |
qenv <- merged$anl_q_r() |
481 | ! |
teal.reporter::teal_card(qenv) <- |
482 | ! |
c( |
483 | ! |
teal.reporter::teal_card("# Outliers Analysis"), |
484 | ! |
teal.reporter::teal_card(qenv), |
485 | ! |
teal.reporter::teal_card("## Module's code") |
486 |
) |
|
487 | ||
488 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
489 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
490 | ! |
order_by_outlier <- input$order_by_outlier |
491 | ! |
method <- input$method |
492 | ! |
split_outliers <- input$split_outliers |
493 | ! |
teal::validate_has_data( |
494 |
# missing values in the categorical variable may be used to form a category of its own |
|
495 | ! |
`if`( |
496 | ! |
length(categorical_var) == 0, |
497 | ! |
ANL, |
498 | ! |
ANL[, names(ANL) != categorical_var, drop = FALSE] |
499 |
), |
|
500 | ! |
min_nrow = 10, |
501 | ! |
complete = TRUE, |
502 | ! |
allow_inf = FALSE |
503 |
) |
|
504 | ! |
validate(need(is.numeric(ANL[[outlier_var]]), "`Variable` is not numeric")) |
505 | ! |
validate(need(length(unique(ANL[[outlier_var]])) > 1, "Variable has no variation, i.e. only one unique value")) |
506 | ||
507 |
# show/hide split_outliers |
|
508 | ! |
if (length(categorical_var) == 0) { |
509 | ! |
shinyjs::hide("split_outliers") |
510 | ! |
if (n_outlier_missing() > 0) { |
511 | ! |
qenv <- teal.code::eval_code( |
512 | ! |
qenv, |
513 | ! |
substitute( |
514 | ! |
expr = ANL <- ANL %>% dplyr::filter(!is.na(outlier_var_name)), |
515 | ! |
env = list(outlier_var_name = as.name(outlier_var)) |
516 |
) |
|
517 |
) |
|
518 |
} |
|
519 |
} else { |
|
520 | ! |
validate(need( |
521 | ! |
is.factor(ANL[[categorical_var]]) || |
522 | ! |
is.character(ANL[[categorical_var]]) || |
523 | ! |
is.integer(ANL[[categorical_var]]), |
524 | ! |
"`Categorical factor` must be `factor`, `character`, or `integer`" |
525 |
)) |
|
526 | ||
527 | ! |
if (n_outlier_missing() > 0) { |
528 | ! |
qenv <- teal.code::eval_code( |
529 | ! |
qenv, |
530 | ! |
substitute( |
531 | ! |
expr = ANL <- ANL %>% dplyr::filter(!is.na(outlier_var_name)), |
532 | ! |
env = list(outlier_var_name = as.name(outlier_var)) |
533 |
) |
|
534 |
) |
|
535 |
} |
|
536 | ! |
shinyjs::show("split_outliers") |
537 |
} |
|
538 | ||
539 |
# slider |
|
540 | ! |
outlier_definition_param <- if (method == "IQR") { |
541 | ! |
input$iqr_slider |
542 | ! |
} else if (method == "Z-score") { |
543 | ! |
input$zscore_slider |
544 | ! |
} else if (method == "Percentile") { |
545 | ! |
input$percentile_slider |
546 |
} |
|
547 | ||
548 |
# this is utils function that converts a %>% NULL %>% b into a %>% b |
|
549 | ! |
remove_pipe_null <- function(x) { |
550 | ! |
if (length(x) == 1) { |
551 | ! |
x |
552 | ! |
} else if (identical(x[[1]], as.name("%>%")) && is.null(x[[3]])) { |
553 | ! |
remove_pipe_null(x[[2]]) |
554 |
} else { |
|
555 | ! |
as.call(c(x[[1]], lapply(x[-1], remove_pipe_null))) |
556 |
} |
|
557 |
} |
|
558 | ||
559 | ! |
qenv <- teal.code::eval_code( |
560 | ! |
qenv, |
561 | ! |
substitute( |
562 | ! |
expr = { |
563 | ! |
ANL_OUTLIER <- ANL %>% |
564 | ! |
group_expr %>% # styler: off |
565 | ! |
dplyr::mutate(is_outlier = { |
566 | ! |
q1_q3 <- stats::quantile(outlier_var_name, probs = c(0.25, 0.75)) |
567 | ! |
iqr <- q1_q3[2] - q1_q3[1] |
568 | ! |
!(outlier_var_name >= q1_q3[1] - 1.5 * iqr & outlier_var_name <= q1_q3[2] + 1.5 * iqr) |
569 |
}) %>% |
|
570 | ! |
calculate_outliers %>% # styler: off |
571 | ! |
ungroup_expr %>% # styler: off |
572 | ! |
dplyr::filter(is_outlier | is_outlier_selected) %>% |
573 | ! |
dplyr::select(-is_outlier) |
574 |
}, |
|
575 | ! |
env = list( |
576 | ! |
calculate_outliers = if (method == "IQR") { |
577 | ! |
substitute( |
578 | ! |
expr = dplyr::mutate(is_outlier_selected = { |
579 | ! |
q1_q3 <- stats::quantile(outlier_var_name, probs = c(0.25, 0.75)) |
580 | ! |
iqr <- q1_q3[2] - q1_q3[1] |
581 |
!( |
|
582 | ! |
outlier_var_name >= q1_q3[1] - outlier_definition_param * iqr & |
583 | ! |
outlier_var_name <= q1_q3[2] + outlier_definition_param * iqr |
584 |
) |
|
585 |
}), |
|
586 | ! |
env = list( |
587 | ! |
outlier_var_name = as.name(outlier_var), |
588 | ! |
outlier_definition_param = outlier_definition_param |
589 |
) |
|
590 |
) |
|
591 | ! |
} else if (method == "Z-score") { |
592 | ! |
substitute( |
593 | ! |
expr = dplyr::mutate( |
594 | ! |
is_outlier_selected = abs(outlier_var_name - mean(outlier_var_name)) / |
595 | ! |
stats::sd(outlier_var_name) > outlier_definition_param |
596 |
), |
|
597 | ! |
env = list( |
598 | ! |
outlier_var_name = as.name(outlier_var), |
599 | ! |
outlier_definition_param = outlier_definition_param |
600 |
) |
|
601 |
) |
|
602 | ! |
} else if (method == "Percentile") { |
603 | ! |
substitute( |
604 | ! |
expr = dplyr::mutate( |
605 | ! |
is_outlier_selected = outlier_var_name < stats::quantile(outlier_var_name, outlier_definition_param) | |
606 | ! |
outlier_var_name > stats::quantile(outlier_var_name, 1 - outlier_definition_param) |
607 |
), |
|
608 | ! |
env = list( |
609 | ! |
outlier_var_name = as.name(outlier_var), |
610 | ! |
outlier_definition_param = outlier_definition_param |
611 |
) |
|
612 |
) |
|
613 |
}, |
|
614 | ! |
outlier_var_name = as.name(outlier_var), |
615 | ! |
group_expr = if (isTRUE(split_outliers) && length(categorical_var) != 0) { |
616 | ! |
substitute(dplyr::group_by(x), list(x = as.name(categorical_var))) |
617 |
}, |
|
618 | ! |
ungroup_expr = if (isTRUE(split_outliers) && length(categorical_var) != 0) { |
619 | ! |
substitute(dplyr::ungroup()) |
620 |
} |
|
621 |
) |
|
622 |
) %>% |
|
623 | ! |
remove_pipe_null() |
624 |
) |
|
625 | ||
626 |
# ANL_OUTLIER_EXTENDED is the base table |
|
627 | ! |
join_keys <- as.character(teal.data::join_keys(data_obj())[dataname_first, dataname_first]) |
628 | ||
629 | ! |
if (length(join_keys) == 1 && join_keys == ".row_id") { |
630 |
# Dummy join key - single dataset, no join needed |
|
631 | ! |
qenv <- teal.code::eval_code(qenv, quote(ANL_OUTLIER_EXTENDED <- ANL_OUTLIER)) |
632 |
} else { |
|
633 |
# Join keys exist - perform left join |
|
634 | ! |
qenv <- teal.code::eval_code( |
635 | ! |
qenv, |
636 | ! |
substitute( |
637 | ! |
expr = { |
638 | ! |
ANL_OUTLIER_EXTENDED <- dplyr::left_join( |
639 | ! |
ANL_OUTLIER, |
640 | ! |
dplyr::select( |
641 | ! |
dataname, |
642 | ! |
dplyr::setdiff(names(dataname), dplyr::setdiff(names(ANL_OUTLIER), join_keys)) |
643 |
), |
|
644 | ! |
by = join_keys |
645 |
) |
|
646 |
}, |
|
647 | ! |
env = list( |
648 | ! |
dataname = as.name(dataname_first), |
649 | ! |
join_keys = join_keys |
650 |
) |
|
651 |
) |
|
652 |
) |
|
653 |
} |
|
654 | ||
655 | ! |
qenv <- if (length(categorical_var) > 0) { |
656 | ! |
teal.reporter::teal_card(qenv) <- c(teal.reporter::teal_card(qenv), "## Summary Table") |
657 | ! |
qenv <- teal.code::eval_code( |
658 | ! |
qenv, |
659 | ! |
substitute( |
660 | ! |
expr = summary_data_pre <- ANL_OUTLIER %>% |
661 | ! |
dplyr::filter(is_outlier_selected) %>% |
662 | ! |
dplyr::select(outlier_var_name, categorical_var_name) %>% |
663 | ! |
dplyr::group_by(categorical_var_name) %>% |
664 | ! |
dplyr::summarise(n_outliers = dplyr::n()) %>% |
665 | ! |
dplyr::right_join( |
666 | ! |
ANL %>% |
667 | ! |
dplyr::select(outlier_var_name, categorical_var_name) %>% |
668 | ! |
dplyr::group_by(categorical_var_name) %>% |
669 | ! |
dplyr::summarise( |
670 | ! |
total_in_cat = dplyr::n(), |
671 | ! |
n_na = sum(is.na(outlier_var_name) | is.na(categorical_var_name)) |
672 |
), |
|
673 | ! |
by = categorical_var |
674 |
) %>% |
|
675 |
# This is important as there may be categorical variables with natural orderings, e.g. AGE. |
|
676 |
# The plots should be displayed by default in increasing order in these situations. |
|
677 |
# dplyr::arrange will sort integer, factor, and character data types in the expected way. |
|
678 | ! |
dplyr::arrange(categorical_var_name) %>% |
679 | ! |
dplyr::mutate( |
680 | ! |
n_outliers = dplyr::if_else(is.na(n_outliers), 0, as.numeric(n_outliers)), |
681 | ! |
display_str = dplyr::if_else( |
682 | ! |
n_outliers > 0, |
683 | ! |
sprintf("%d [%.02f%%]", n_outliers, 100 * n_outliers / total_in_cat), |
684 | ! |
"0" |
685 |
), |
|
686 | ! |
display_str_na = dplyr::if_else( |
687 | ! |
n_na > 0, |
688 | ! |
sprintf("%d [%.02f%%]", n_na, 100 * n_na / total_in_cat), |
689 | ! |
"0" |
690 |
), |
|
691 | ! |
order = seq_along(n_outliers) |
692 |
), |
|
693 | ! |
env = list( |
694 | ! |
categorical_var = categorical_var, |
695 | ! |
categorical_var_name = as.name(categorical_var), |
696 | ! |
outlier_var_name = as.name(outlier_var) |
697 |
) |
|
698 |
) |
|
699 |
) |
|
700 |
# now to handle when user chooses to order based on amount of outliers |
|
701 | ! |
if (order_by_outlier) { |
702 | ! |
qenv <- teal.code::eval_code( |
703 | ! |
qenv, |
704 | ! |
quote( |
705 | ! |
summary_data_pre <- summary_data_pre %>% |
706 | ! |
dplyr::arrange(desc(n_outliers / total_in_cat)) %>% |
707 | ! |
dplyr::mutate(order = seq_len(nrow(summary_data_pre))) |
708 |
) |
|
709 |
) |
|
710 |
} |
|
711 | ||
712 | ! |
teal.code::eval_code( |
713 | ! |
qenv, |
714 | ! |
substitute( |
715 | ! |
expr = { |
716 |
# In order for geom_rug to work properly when reordering takes place inside facet_grid, |
|
717 |
# all tables must have the column used for reording. |
|
718 |
# In this case, the column used for reordering is `order`. |
|
719 | ! |
ANL_OUTLIER <- dplyr::left_join( |
720 | ! |
ANL_OUTLIER, |
721 | ! |
summary_data_pre[, c("order", categorical_var)], |
722 | ! |
by = categorical_var |
723 |
) |
|
724 |
# so that x axis of plot aligns with columns of summary table, from most outliers to least by percentage |
|
725 | ! |
ANL <- ANL %>% |
726 | ! |
dplyr::left_join( |
727 | ! |
dplyr::select(summary_data_pre, categorical_var_name, order), |
728 | ! |
by = categorical_var |
729 |
) %>% |
|
730 | ! |
dplyr::arrange(order) |
731 | ! |
summary_data <- summary_data_pre %>% |
732 | ! |
dplyr::select( |
733 | ! |
categorical_var_name, |
734 | ! |
Outliers = display_str, Missings = display_str_na, Total = total_in_cat |
735 |
) %>% |
|
736 | ! |
dplyr::mutate_all(as.character) %>% |
737 | ! |
tidyr::pivot_longer(-categorical_var_name) %>% |
738 | ! |
tidyr::pivot_wider(names_from = categorical_var, values_from = value) %>% |
739 | ! |
tibble::column_to_rownames("name") |
740 |
}, |
|
741 | ! |
env = list( |
742 | ! |
categorical_var = categorical_var, |
743 | ! |
categorical_var_name = as.name(categorical_var) |
744 |
) |
|
745 |
) |
|
746 |
) |
|
747 |
} else { |
|
748 | ! |
within(qenv, summary_data <- data.frame()) |
749 |
} |
|
750 | ||
751 |
# Generate decoratable object from data |
|
752 | ! |
qenv <- within(qenv, { |
753 | ! |
table <- rtables::df_to_tt(summary_data) |
754 | ! |
table |
755 |
}) |
|
756 | ||
757 | ! |
if (length(categorical_var) > 0 && nrow(qenv[["ANL_OUTLIER"]]) > 0) { |
758 | ! |
shinyjs::show("order_by_outlier") |
759 |
} else { |
|
760 | ! |
shinyjs::hide("order_by_outlier") |
761 |
} |
|
762 | ||
763 | ! |
qenv |
764 |
}) |
|
765 | ||
766 |
# boxplot/violinplot # nolint commented_code |
|
767 | ! |
box_plot_q <- reactive({ |
768 | ! |
req(common_code_q()) |
769 | ! |
qenv <- common_code_q() |
770 | ! |
teal.reporter::teal_card(qenv) <- c(teal.reporter::teal_card(qenv), "## Box Plot") |
771 | ||
772 | ! |
ANL <- qenv[["ANL"]] |
773 | ! |
ANL_OUTLIER <- qenv[["ANL_OUTLIER"]] |
774 | ||
775 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
776 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
777 | ||
778 |
# validation |
|
779 | ! |
teal::validate_has_data(ANL, 1) |
780 | ||
781 |
# boxplot |
|
782 | ! |
plot_call <- quote(ANL %>% ggplot()) |
783 | ||
784 | ! |
plot_call <- if (input$boxplot_alts == "Box plot") { |
785 | ! |
substitute(expr = plot_call + ggplot2::geom_boxplot(outlier.shape = NA), env = list(plot_call = plot_call)) |
786 | ! |
} else if (input$boxplot_alts == "Violin plot") { |
787 | ! |
substitute(expr = plot_call + ggplot2::geom_violin(), env = list(plot_call = plot_call)) |
788 |
} else { |
|
789 | ! |
NULL |
790 |
} |
|
791 | ||
792 | ! |
plot_call <- if (identical(categorical_var, character(0)) || is.null(categorical_var)) { |
793 | ! |
inner_call <- substitute( |
794 | ! |
expr = plot_call + |
795 | ! |
ggplot2::aes(x = "Entire dataset", y = outlier_var_name) + |
796 | ! |
ggplot2::scale_x_discrete(), |
797 | ! |
env = list(plot_call = plot_call, outlier_var_name = as.name(outlier_var)) |
798 |
) |
|
799 | ! |
if (nrow(ANL_OUTLIER) > 0) { |
800 | ! |
substitute( |
801 | ! |
expr = inner_call + ggplot2::geom_point( |
802 | ! |
data = ANL_OUTLIER, |
803 | ! |
ggplot2::aes(x = "Entire dataset", y = outlier_var_name, color = is_outlier_selected) |
804 |
), |
|
805 | ! |
env = list(inner_call = inner_call, outlier_var_name = as.name(outlier_var)) |
806 |
) |
|
807 |
} else { |
|
808 | ! |
inner_call |
809 |
} |
|
810 |
} else { |
|
811 | ! |
substitute( |
812 | ! |
expr = plot_call + |
813 | ! |
ggplot2::aes(y = outlier_var_name, x = reorder(categorical_var_name, order)) + |
814 | ! |
ggplot2::xlab(categorical_var) + |
815 | ! |
ggplot2::scale_x_discrete() + |
816 | ! |
ggplot2::geom_point( |
817 | ! |
data = ANL_OUTLIER, |
818 | ! |
ggplot2::aes(x = as.factor(categorical_var_name), y = outlier_var_name, color = is_outlier_selected) |
819 |
), |
|
820 | ! |
env = list( |
821 | ! |
plot_call = plot_call, |
822 | ! |
outlier_var_name = as.name(outlier_var), |
823 | ! |
categorical_var_name = as.name(categorical_var), |
824 | ! |
categorical_var = categorical_var |
825 |
) |
|
826 |
) |
|
827 |
} |
|
828 | ||
829 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
830 | ! |
labs = list(color = "Is outlier?"), |
831 | ! |
theme = list(legend.position = "top") |
832 |
) |
|
833 | ||
834 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
835 | ! |
user_plot = ggplot2_args[["Boxplot"]], |
836 | ! |
user_default = ggplot2_args$default, |
837 | ! |
module_plot = dev_ggplot2_args |
838 |
) |
|
839 | ||
840 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
841 | ! |
all_ggplot2_args, |
842 | ! |
ggtheme = input$ggtheme |
843 |
) |
|
844 | ||
845 | ! |
teal.code::eval_code( |
846 | ! |
qenv, |
847 | ! |
substitute( |
848 | ! |
expr = box_plot <- plot_call + |
849 | ! |
ggplot2::scale_color_manual(values = c("TRUE" = "red", "FALSE" = "black")) + |
850 | ! |
labs + ggthemes + themes, |
851 | ! |
env = list( |
852 | ! |
plot_call = plot_call, |
853 | ! |
labs = parsed_ggplot2_args$labs, |
854 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
855 | ! |
themes = parsed_ggplot2_args$theme |
856 |
) |
|
857 |
) |
|
858 |
) |
|
859 |
}) |
|
860 | ||
861 |
# density plot |
|
862 | ! |
density_plot_q <- reactive({ |
863 | ! |
qenv <- common_code_q() |
864 | ! |
teal.reporter::teal_card(qenv) <- c(teal.reporter::teal_card(qenv), "## Density Plot") |
865 | ||
866 | ! |
ANL <- qenv[["ANL"]] |
867 | ! |
ANL_OUTLIER <- qenv[["ANL_OUTLIER"]] |
868 | ||
869 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
870 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
871 | ||
872 |
# validation |
|
873 | ! |
teal::validate_has_data(ANL, 1) |
874 |
# plot |
|
875 | ! |
plot_call <- substitute( |
876 | ! |
expr = ANL %>% |
877 | ! |
ggplot2::ggplot(ggplot2::aes(x = outlier_var_name)) + |
878 | ! |
ggplot2::geom_density() + |
879 | ! |
ggplot2::geom_rug(data = ANL_OUTLIER, ggplot2::aes(x = outlier_var_name, color = is_outlier_selected)) + |
880 | ! |
ggplot2::scale_color_manual(values = c("TRUE" = "red", "FALSE" = "black")), |
881 | ! |
env = list(outlier_var_name = as.name(outlier_var)) |
882 |
) |
|
883 | ||
884 | ! |
plot_call <- if (identical(categorical_var, character(0)) || is.null(categorical_var)) { |
885 | ! |
substitute(expr = plot_call, env = list(plot_call = plot_call)) |
886 |
} else { |
|
887 | ! |
substitute( |
888 | ! |
expr = plot_call + ggplot2::facet_grid(~ reorder(categorical_var_name, order)), |
889 | ! |
env = list(plot_call = plot_call, categorical_var_name = as.name(categorical_var)) |
890 |
) |
|
891 |
} |
|
892 | ||
893 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
894 | ! |
labs = list(color = "Is outlier?"), |
895 | ! |
theme = list(legend.position = "top") |
896 |
) |
|
897 | ||
898 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
899 | ! |
user_plot = ggplot2_args[["Density Plot"]], |
900 | ! |
user_default = ggplot2_args$default, |
901 | ! |
module_plot = dev_ggplot2_args |
902 |
) |
|
903 | ||
904 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
905 | ! |
all_ggplot2_args, |
906 | ! |
ggtheme = input$ggtheme |
907 |
) |
|
908 | ||
909 | ! |
teal.code::eval_code( |
910 | ! |
qenv, |
911 | ! |
substitute( |
912 | ! |
expr = density_plot <- plot_call + labs + ggthemes + themes, |
913 | ! |
env = list( |
914 | ! |
plot_call = plot_call, |
915 | ! |
labs = parsed_ggplot2_args$labs, |
916 | ! |
themes = parsed_ggplot2_args$theme, |
917 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
918 |
) |
|
919 |
) |
|
920 |
) |
|
921 |
}) |
|
922 | ||
923 |
# Cumulative distribution plot |
|
924 | ! |
cumulative_plot_q <- reactive({ |
925 | ! |
qenv <- common_code_q() |
926 | ! |
teal.reporter::teal_card(qenv) <- c(teal.reporter::teal_card(qenv), "## Cumulative Distribution Plot") |
927 | ||
928 | ! |
ANL <- qenv[["ANL"]] |
929 | ! |
ANL_OUTLIER <- qenv[["ANL_OUTLIER"]] |
930 | ||
931 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
932 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
933 | ||
934 |
# validation |
|
935 | ! |
teal::validate_has_data(ANL, 1) |
936 | ||
937 |
# plot |
|
938 | ! |
plot_call <- substitute( |
939 | ! |
expr = ANL %>% ggplot2::ggplot(ggplot2::aes(x = outlier_var_name)) + |
940 | ! |
ggplot2::stat_ecdf(), |
941 | ! |
env = list(outlier_var_name = as.name(outlier_var)) |
942 |
) |
|
943 | ! |
if (length(categorical_var) == 0) { |
944 | ! |
qenv <- teal.code::eval_code( |
945 | ! |
qenv, |
946 | ! |
substitute( |
947 | ! |
expr = { |
948 | ! |
ecdf_df <- ANL %>% |
949 | ! |
dplyr::mutate( |
950 | ! |
y = stats::ecdf(ANL[[outlier_var]])(ANL[[outlier_var]]) |
951 |
) |
|
952 | ||
953 | ! |
outlier_points <- dplyr::left_join( |
954 | ! |
ecdf_df, |
955 | ! |
ANL_OUTLIER, |
956 | ! |
by = dplyr::setdiff(names(ecdf_df), "y") |
957 |
) %>% |
|
958 | ! |
dplyr::filter(!is.na(is_outlier_selected)) |
959 |
}, |
|
960 | ! |
env = list(outlier_var = outlier_var) |
961 |
) |
|
962 |
) |
|
963 |
} else { |
|
964 | ! |
qenv <- teal.code::eval_code( |
965 | ! |
qenv, |
966 | ! |
substitute( |
967 | ! |
expr = { |
968 | ! |
all_categories <- lapply( |
969 | ! |
unique(ANL[[categorical_var]]), |
970 | ! |
function(x) { |
971 | ! |
ANL <- ANL %>% dplyr::filter(get(categorical_var) == x) |
972 | ! |
anl_outlier2 <- ANL_OUTLIER %>% dplyr::filter(get(categorical_var) == x) |
973 | ! |
ecdf_df <- ANL %>% |
974 | ! |
dplyr::mutate(y = stats::ecdf(ANL[[outlier_var]])(ANL[[outlier_var]])) |
975 | ||
976 | ! |
dplyr::left_join( |
977 | ! |
ecdf_df, |
978 | ! |
anl_outlier2, |
979 | ! |
by = dplyr::setdiff(names(ecdf_df), "y") |
980 |
) %>% |
|
981 | ! |
dplyr::filter(!is.na(is_outlier_selected)) |
982 |
} |
|
983 |
) |
|
984 | ! |
outlier_points <- do.call(rbind, all_categories) |
985 |
}, |
|
986 | ! |
env = list(categorical_var = categorical_var, outlier_var = outlier_var) |
987 |
) |
|
988 |
) |
|
989 | ! |
plot_call <- substitute( |
990 | ! |
expr = plot_call + ggplot2::facet_grid(~ reorder(categorical_var_name, order)), |
991 | ! |
env = list(plot_call = plot_call, categorical_var_name = as.name(categorical_var)) |
992 |
) |
|
993 |
} |
|
994 | ||
995 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
996 | ! |
labs = list(color = "Is outlier?"), |
997 | ! |
theme = list(legend.position = "top") |
998 |
) |
|
999 | ||
1000 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
1001 | ! |
user_plot = ggplot2_args[["Cumulative Distribution Plot"]], |
1002 | ! |
user_default = ggplot2_args$default, |
1003 | ! |
module_plot = dev_ggplot2_args |
1004 |
) |
|
1005 | ||
1006 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
1007 | ! |
all_ggplot2_args, |
1008 | ! |
ggtheme = input$ggtheme |
1009 |
) |
|
1010 | ||
1011 | ! |
teal.code::eval_code( |
1012 | ! |
qenv, |
1013 | ! |
substitute( |
1014 | ! |
expr = cumulative_plot <- plot_call + |
1015 | ! |
ggplot2::geom_point( |
1016 | ! |
data = outlier_points, |
1017 | ! |
ggplot2::aes(x = outlier_var_name, y = y, color = is_outlier_selected) |
1018 |
) + |
|
1019 | ! |
ggplot2::scale_color_manual(values = c("TRUE" = "red", "FALSE" = "black")) + |
1020 | ! |
labs + ggthemes + themes, |
1021 | ! |
env = list( |
1022 | ! |
plot_call = plot_call, |
1023 | ! |
outlier_var_name = as.name(outlier_var), |
1024 | ! |
labs = parsed_ggplot2_args$labs, |
1025 | ! |
themes = parsed_ggplot2_args$theme, |
1026 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
1027 |
) |
|
1028 |
) |
|
1029 |
) |
|
1030 |
}) |
|
1031 | ||
1032 | ! |
current_tab_r <- reactive({ |
1033 | ! |
switch(req(input$tabs), |
1034 | ! |
"Boxplot" = "box_plot", |
1035 | ! |
"Density Plot" = "density_plot", |
1036 | ! |
"Cumulative Distribution Plot" = "cumulative_plot" |
1037 |
) |
|
1038 |
}) |
|
1039 | ||
1040 | ! |
decorated_q <- mapply( |
1041 | ! |
function(obj_name, q) { |
1042 | ! |
srv_decorate_teal_data( |
1043 | ! |
id = sprintf("d_%s", obj_name), |
1044 | ! |
data = q, |
1045 | ! |
decorators = select_decorators(decorators, obj_name), |
1046 | ! |
expr = reactive({ |
1047 | ! |
substitute( |
1048 | ! |
expr = { |
1049 | ! |
columns_index <- union( |
1050 | ! |
setdiff(names(ANL_OUTLIER), c("is_outlier_selected", "order")), |
1051 | ! |
table_columns |
1052 |
) |
|
1053 | ! |
ANL_OUTLIER_EXTENDED[ANL_OUTLIER_EXTENDED$is_outlier_selected, columns_index] |
1054 | ! |
print(.plot) |
1055 |
}, |
|
1056 | ! |
env = list(table_columns = input$table_ui_columns, .plot = as.name(obj_name)) |
1057 |
) |
|
1058 |
}) |
|
1059 |
) |
|
1060 |
}, |
|
1061 | ! |
stats::setNames(nm = c("box_plot", "density_plot", "cumulative_plot")), |
1062 | ! |
c(box_plot_q, density_plot_q, cumulative_plot_q) |
1063 |
) |
|
1064 | ||
1065 | ! |
box_plot_r <- reactive({ |
1066 | ! |
teal::validate_inputs(iv_r()) |
1067 | ! |
req(decorated_q$box_plot())[["box_plot"]] |
1068 |
}) |
|
1069 | ! |
density_plot_r <- reactive({ |
1070 | ! |
teal::validate_inputs(iv_r()) |
1071 | ! |
req(decorated_q$density_plot())[["density_plot"]] |
1072 |
}) |
|
1073 | ! |
cumulative_plot_r <- reactive({ |
1074 | ! |
teal::validate_inputs(iv_r()) |
1075 | ! |
req(decorated_q$cumulative_plot())[["cumulative_plot"]] |
1076 |
}) |
|
1077 | ||
1078 | ! |
box_pws <- teal.widgets::plot_with_settings_srv( |
1079 | ! |
id = "box_plot", |
1080 | ! |
plot_r = box_plot_r, |
1081 | ! |
height = plot_height, |
1082 | ! |
width = plot_width, |
1083 | ! |
brushing = TRUE |
1084 |
) |
|
1085 | ||
1086 | ! |
density_pws <- teal.widgets::plot_with_settings_srv( |
1087 | ! |
id = "density_plot", |
1088 | ! |
plot_r = density_plot_r, |
1089 | ! |
height = plot_height, |
1090 | ! |
width = plot_width, |
1091 | ! |
brushing = TRUE |
1092 |
) |
|
1093 | ||
1094 | ! |
cum_density_pws <- teal.widgets::plot_with_settings_srv( |
1095 | ! |
id = "cum_density_plot", |
1096 | ! |
plot_r = cumulative_plot_r, |
1097 | ! |
height = plot_height, |
1098 | ! |
width = plot_width, |
1099 | ! |
brushing = TRUE |
1100 |
) |
|
1101 | ||
1102 | ! |
pws_list <- list(box_plot = box_pws, density_plot = density_pws, cumulative_plot = cum_density_pws) |
1103 | ! |
decorated_final_q <- reactive({ |
1104 | ! |
pws <- pws_list[[req(current_tab_r())]] |
1105 | ! |
req(pws$dim()) |
1106 | ! |
req(decorated_q[[current_tab_r()]]()) |
1107 | ! |
set_chunk_dims(pws, decorated_q[[current_tab_r()]])() |
1108 |
}) |
|
1109 | ||
1110 | ! |
summary_table_r <- reactive({ |
1111 | ! |
q <- req(decorated_final_q()) |
1112 | ||
1113 | ! |
DT::datatable( |
1114 | ! |
data = if (iv_r()$is_valid()) { |
1115 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
1116 | ! |
if (!is.null(categorical_var)) q[["summary_data"]] |
1117 |
}, |
|
1118 | ! |
option = list( |
1119 | ! |
dom = "t", |
1120 | ! |
autoWidth = TRUE, |
1121 | ! |
columnDefs = list(list(width = "200px", targets = "_all")) |
1122 |
) |
|
1123 |
) |
|
1124 |
}) |
|
1125 | ||
1126 | ! |
output$summary_table <- DT::renderDataTable(summary_table_r()) |
1127 | ||
1128 |
# slider text |
|
1129 | ! |
output$ui_outlier_help <- renderUI({ |
1130 | ! |
req(input$method) |
1131 | ! |
if (input$method == "IQR") { |
1132 | ! |
req(input$iqr_slider) |
1133 | ! |
tags$small( |
1134 | ! |
withMathJax( |
1135 | ! |
helpText( |
1136 | ! |
"Outlier data points (\\(x \\lt Q1 - ", input$iqr_slider, "\\times IQR\\) or \\( |
1137 | ! |
Q3 + ", input$iqr_slider, "\\times IQR \\lt x\\)) |
1138 | ! |
are displayed in red on the plot and can be visualized in the table below." |
1139 |
), |
|
1140 | ! |
if (input$split_outliers) { |
1141 | ! |
withMathJax(helpText("Note: Quantiles are calculated per group.")) |
1142 |
} |
|
1143 |
) |
|
1144 |
) |
|
1145 | ! |
} else if (input$method == "Z-score") { |
1146 | ! |
req(input$zscore_slider) |
1147 | ! |
tags$small( |
1148 | ! |
withMathJax( |
1149 | ! |
helpText( |
1150 | ! |
"Outlier data points (\\(Zscore(x) < -", input$zscore_slider, |
1151 | ! |
"\\) or \\(", input$zscore_slider, "< Zscore(x) \\)) |
1152 | ! |
are displayed in red on the plot and can be visualized in the table below." |
1153 |
), |
|
1154 | ! |
if (input$split_outliers) { |
1155 | ! |
withMathJax(helpText(" Note: Z-scores are calculated per group.")) |
1156 |
} |
|
1157 |
) |
|
1158 |
) |
|
1159 | ! |
} else if (input$method == "Percentile") { |
1160 | ! |
req(input$percentile_slider) |
1161 | ! |
tags$small( |
1162 | ! |
withMathJax( |
1163 | ! |
helpText( |
1164 | ! |
"Outlier/extreme data points (\\( Percentile(x) <", input$percentile_slider, |
1165 | ! |
"\\) or \\(", 1 - input$percentile_slider, " < Percentile(x) \\)) |
1166 | ! |
are displayed in red on the plot and can be visualized in the table below." |
1167 |
), |
|
1168 | ! |
if (input$split_outliers) { |
1169 | ! |
withMathJax(helpText("Note: Percentiles are calculated per group.")) |
1170 |
} |
|
1171 |
) |
|
1172 |
) |
|
1173 |
} |
|
1174 |
}) |
|
1175 | ||
1176 | ! |
choices <- reactive(teal.transform::variable_choices(data_obj()[[dataname_first]])) |
1177 | ||
1178 | ! |
observeEvent(common_code_q(), { |
1179 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
1180 | ! |
teal.widgets::updateOptionalSelectInput( |
1181 | ! |
session, |
1182 | ! |
inputId = "table_ui_columns", |
1183 | ! |
choices = dplyr::setdiff(choices(), names(ANL_OUTLIER)), |
1184 | ! |
selected = restoreInput(ns("table_ui_columns"), isolate(input$table_ui_columns)) |
1185 |
) |
|
1186 |
}) |
|
1187 | ||
1188 | ! |
output$table_ui <- DT::renderDataTable( |
1189 | ! |
expr = { |
1190 | ! |
tab <- input$tabs |
1191 | ! |
req(tab) # tab is NULL upon app launch, hence will crash without this statement |
1192 | ! |
req(iv_r()$is_valid()) # Same validation as output$table_ui_wrap |
1193 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
1194 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
1195 | ||
1196 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
1197 | ! |
ANL_OUTLIER_EXTENDED <- common_code_q()[["ANL_OUTLIER_EXTENDED"]] |
1198 | ! |
ANL <- common_code_q()[["ANL"]] |
1199 | ||
1200 | ! |
plot_brush <- switch(current_tab_r(), |
1201 | ! |
box_plot = { |
1202 | ! |
box_plot_r() |
1203 | ! |
box_pws$brush() |
1204 |
}, |
|
1205 | ! |
density_plot = { |
1206 | ! |
density_plot_r() |
1207 | ! |
density_pws$brush() |
1208 |
}, |
|
1209 | ! |
cumulative_plot = { |
1210 | ! |
cumulative_plot_r() |
1211 | ! |
cum_density_pws$brush() |
1212 |
} |
|
1213 |
) |
|
1214 | ||
1215 |
# removing unused column ASAP |
|
1216 | ! |
ANL_OUTLIER$order <- ANL$order <- NULL |
1217 | ||
1218 | ! |
display_table <- if (!is.null(plot_brush)) { |
1219 | ! |
if (length(categorical_var) > 0) { |
1220 |
# due to reordering, the x-axis label may be changed to something like "reorder(categorical_var, order)" |
|
1221 | ! |
if (tab == "Boxplot") { |
1222 | ! |
plot_brush$mapping$x <- categorical_var |
1223 |
} else { |
|
1224 |
# the other plots use facetting |
|
1225 |
# so it is panelvar1 that gets relabelled to "reorder(categorical_var, order)" |
|
1226 | ! |
plot_brush$mapping$panelvar1 <- categorical_var |
1227 |
} |
|
1228 |
} else { |
|
1229 | ! |
if (tab == "Boxplot") { |
1230 |
# in boxplot with no categorical variable, there is no column in ANL that would correspond to x-axis |
|
1231 |
# so a column needs to be inserted with the value "Entire dataset" because that's the label used in plot |
|
1232 | ! |
ANL[[plot_brush$mapping$x]] <- "Entire dataset" |
1233 |
} |
|
1234 |
} |
|
1235 | ||
1236 |
# in density and cumulative plots, ANL does not have a column corresponding to y-axis. |
|
1237 |
# so they need to be computed and attached to ANL |
|
1238 | ! |
if (tab == "Density Plot") { |
1239 | ! |
plot_brush$mapping$y <- "density" |
1240 | ! |
ANL$density <- plot_brush$ymin |
1241 |
# either ymin or ymax will work |
|
1242 | ! |
} else if (tab == "Cumulative Distribution Plot") { |
1243 | ! |
plot_brush$mapping$y <- "cdf" |
1244 | ! |
if (length(categorical_var) > 0) { |
1245 | ! |
ANL <- ANL %>% |
1246 | ! |
dplyr::group_by(!!as.name(plot_brush$mapping$panelvar1)) %>% |
1247 | ! |
dplyr::mutate(cdf = stats::ecdf(!!as.name(outlier_var))(!!as.name(outlier_var))) |
1248 |
} else { |
|
1249 | ! |
ANL$cdf <- stats::ecdf(ANL[[outlier_var]])(ANL[[outlier_var]]) |
1250 |
} |
|
1251 |
} |
|
1252 | ||
1253 | ! |
brushed_rows <- brushedPoints(ANL, plot_brush) |
1254 | ! |
if (nrow(brushed_rows) > 0) { |
1255 |
# now we need to remove extra column from ANL so that it will have the same columns as ANL_OUTLIER |
|
1256 |
# so that dplyr::intersect will work |
|
1257 | ! |
if (tab == "Density Plot") { |
1258 | ! |
brushed_rows$density <- NULL |
1259 | ! |
} else if (tab == "Cumulative Distribution Plot") { |
1260 | ! |
brushed_rows$cdf <- NULL |
1261 | ! |
} else if (tab == "Boxplot" && length(categorical_var) == 0) { |
1262 | ! |
brushed_rows[[plot_brush$mapping$x]] <- NULL |
1263 |
} |
|
1264 |
# is_outlier_selected is part of ANL_OUTLIER so needed here |
|
1265 | ! |
brushed_rows$is_outlier_selected <- TRUE |
1266 | ! |
dplyr::intersect(ANL_OUTLIER, brushed_rows) |
1267 |
} else { |
|
1268 | ! |
ANL_OUTLIER[0, ] |
1269 |
} |
|
1270 |
} else { |
|
1271 | ! |
ANL_OUTLIER[ANL_OUTLIER$is_outlier_selected, ] |
1272 |
} |
|
1273 | ||
1274 | ! |
display_table$is_outlier_selected <- NULL |
1275 | ||
1276 |
# Extend the brushed ANL_OUTLIER with additional columns |
|
1277 | ! |
dplyr::left_join( |
1278 | ! |
display_table, |
1279 | ! |
dplyr::select(ANL_OUTLIER_EXTENDED, -"is_outlier_selected"), |
1280 | ! |
by = names(display_table) |
1281 |
) %>% |
|
1282 | ! |
dplyr::select(union(names(display_table), input$table_ui_columns)) |
1283 |
}, |
|
1284 | ! |
options = list( |
1285 | ! |
searching = FALSE, language = list( |
1286 | ! |
zeroRecords = "The brushed area does not contain outlier observations for the currently defined threshold" |
1287 |
), |
|
1288 | ! |
pageLength = input$table_ui_rows |
1289 |
) |
|
1290 |
) |
|
1291 | ||
1292 | ! |
output$total_outliers <- renderUI({ |
1293 | ! |
req(iv_r()$is_valid()) |
1294 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
1295 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
1296 | ! |
teal::validate_has_data(ANL, 1) |
1297 | ! |
ANL_OUTLIER_SELECTED <- ANL_OUTLIER[ANL_OUTLIER$is_outlier_selected, ] |
1298 | ! |
tags$h5( |
1299 | ! |
sprintf( |
1300 | ! |
"%s %d / %d [%.02f%%]", |
1301 | ! |
"Total number of outlier(s):", |
1302 | ! |
nrow(ANL_OUTLIER_SELECTED), |
1303 | ! |
nrow(ANL), |
1304 | ! |
100 * nrow(ANL_OUTLIER_SELECTED) / nrow(ANL) |
1305 |
) |
|
1306 |
) |
|
1307 |
}) |
|
1308 | ||
1309 | ! |
output$total_missing <- renderUI({ |
1310 | ! |
if (n_outlier_missing() > 0) { |
1311 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
1312 | ! |
helpText( |
1313 | ! |
sprintf( |
1314 | ! |
"%s %d / %d [%.02f%%]", |
1315 | ! |
"Total number of row(s) with missing values:", |
1316 | ! |
n_outlier_missing(), |
1317 | ! |
nrow(ANL), |
1318 | ! |
100 * (n_outlier_missing()) / nrow(ANL) |
1319 |
) |
|
1320 |
) |
|
1321 |
} |
|
1322 |
}) |
|
1323 | ||
1324 | ! |
output$table_ui_wrap <- renderUI({ |
1325 | ! |
req(iv_r()$is_valid()) |
1326 | ! |
tagList( |
1327 | ! |
teal.widgets::optionalSelectInput( |
1328 | ! |
inputId = ns("table_ui_columns"), |
1329 | ! |
label = "Choose additional columns", |
1330 | ! |
choices = NULL, |
1331 | ! |
selected = NULL, |
1332 | ! |
multiple = TRUE |
1333 |
), |
|
1334 | ! |
tags$h4("Outlier Table"), |
1335 | ! |
teal.widgets::get_dt_rows(ns("table_ui"), ns("table_ui_rows")) |
1336 |
) |
|
1337 |
}) |
|
1338 | ||
1339 |
# Render R code. |
|
1340 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_final_q()))) |
1341 | ||
1342 | ! |
teal.widgets::verbatim_popup_srv( |
1343 | ! |
id = "rcode", |
1344 | ! |
verbatim_content = source_code_r, |
1345 | ! |
title = "Show R Code for Outlier" |
1346 |
) |
|
1347 | ! |
decorated_final_q |
1348 |
}) |
|
1349 |
} |
1 |
#' `teal` module: Univariate and bivariate visualizations |
|
2 |
#' |
|
3 |
#' Module enables the creation of univariate and bivariate plots, |
|
4 |
#' facilitating the exploration of data distributions and relationships between two variables. |
|
5 |
#' |
|
6 |
#' This is a general module to visualize 1 & 2 dimensional data. |
|
7 |
#' |
|
8 |
#' @note |
|
9 |
#' For more examples, please see the vignette "Using bivariate plot" via |
|
10 |
#' `vignette("using-bivariate-plot", package = "teal.modules.general")`. |
|
11 |
#' |
|
12 |
#' @inheritParams teal::module |
|
13 |
#' @inheritParams shared_params |
|
14 |
#' @param x (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
15 |
#' Variable names selected to plot along the x-axis by default. |
|
16 |
#' Can be numeric, factor or character. |
|
17 |
#' No empty selections are allowed. |
|
18 |
#' @param y (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
19 |
#' Variable names selected to plot along the y-axis by default. |
|
20 |
#' Can be numeric, factor or character. |
|
21 |
#' @param use_density (`logical`) optional, indicates whether to plot density (`TRUE`) or frequency (`FALSE`). |
|
22 |
#' Defaults to frequency (`FALSE`). |
|
23 |
#' @param row_facet (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
24 |
#' specification of the data variable(s) to use for faceting rows. |
|
25 |
#' @param col_facet (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
26 |
#' specification of the data variable(s) to use for faceting columns. |
|
27 |
#' @param facet (`logical`) optional, specifies whether the facet encodings `ui` elements are toggled |
|
28 |
#' on and shown to the user by default. Defaults to `TRUE` if either `row_facet` or `column_facet` |
|
29 |
#' are supplied. |
|
30 |
#' @param color_settings (`logical`) Whether coloring, filling and size should be applied |
|
31 |
#' and `UI` tool offered to the user. |
|
32 |
#' @param color (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
33 |
#' specification of the data variable(s) selected for the outline color inside the coloring settings. |
|
34 |
#' It will be applied when `color_settings` is set to `TRUE`. |
|
35 |
#' @param fill (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
36 |
#' specification of the data variable(s) selected for the fill color inside the coloring settings. |
|
37 |
#' It will be applied when `color_settings` is set to `TRUE`. |
|
38 |
#' @param size (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
39 |
#' specification of the data variable(s) selected for the size of `geom_point` plots inside the coloring settings. |
|
40 |
#' It will be applied when `color_settings` is set to `TRUE`. |
|
41 |
#' @param free_x_scales (`logical`) optional, whether X scaling shall be changeable. |
|
42 |
#' Does not allow scaling to be changed by default (`FALSE`). |
|
43 |
#' @param free_y_scales (`logical`) optional, whether Y scaling shall be changeable. |
|
44 |
#' Does not allow scaling to be changed by default (`FALSE`). |
|
45 |
#' @param swap_axes (`logical`) optional, whether to swap X and Y axes. Defaults to `FALSE`. |
|
46 |
#' |
|
47 |
#' @inherit shared_params return |
|
48 |
#' |
|
49 |
#' @section Decorating Module: |
|
50 |
#' |
|
51 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
52 |
#' - `plot` (`ggplot`) |
|
53 |
#' |
|
54 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
55 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
56 |
#' See code snippet below: |
|
57 |
#' |
|
58 |
#' ``` |
|
59 |
#' tm_g_bivariate( |
|
60 |
#' ..., # arguments for module |
|
61 |
#' decorators = list( |
|
62 |
#' plot = teal_transform_module(...) # applied to the `plot` output |
|
63 |
#' ) |
|
64 |
#' ) |
|
65 |
#' ``` |
|
66 |
#' |
|
67 |
#' For additional details and examples of decorators, refer to the vignette |
|
68 |
#' `vignette("decorate-module-output", package = "teal.modules.general")`. |
|
69 |
#' |
|
70 |
#' To learn more please refer to the vignette |
|
71 |
#' `vignette("transform-module-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
72 |
#' |
|
73 |
#' @inheritSection teal::example_module Reporting |
|
74 |
#' |
|
75 |
#' @examplesShinylive |
|
76 |
#' library(teal.modules.general) |
|
77 |
#' interactive <- function() TRUE |
|
78 |
#' {{ next_example }} |
|
79 |
#' @examples |
|
80 |
#' # general data example |
|
81 |
#' data <- teal_data() |
|
82 |
#' data <- within(data, { |
|
83 |
#' require(nestcolor) |
|
84 |
#' CO2 <- data.frame(CO2) |
|
85 |
#' }) |
|
86 |
#' |
|
87 |
#' app <- init( |
|
88 |
#' data = data, |
|
89 |
#' modules = tm_g_bivariate( |
|
90 |
#' x = data_extract_spec( |
|
91 |
#' dataname = "CO2", |
|
92 |
#' select = select_spec( |
|
93 |
#' label = "Select variable:", |
|
94 |
#' choices = variable_choices(data[["CO2"]]), |
|
95 |
#' selected = "conc", |
|
96 |
#' fixed = FALSE |
|
97 |
#' ) |
|
98 |
#' ), |
|
99 |
#' y = data_extract_spec( |
|
100 |
#' dataname = "CO2", |
|
101 |
#' select = select_spec( |
|
102 |
#' label = "Select variable:", |
|
103 |
#' choices = variable_choices(data[["CO2"]]), |
|
104 |
#' selected = "uptake", |
|
105 |
#' multiple = FALSE, |
|
106 |
#' fixed = FALSE |
|
107 |
#' ) |
|
108 |
#' ), |
|
109 |
#' row_facet = data_extract_spec( |
|
110 |
#' dataname = "CO2", |
|
111 |
#' select = select_spec( |
|
112 |
#' label = "Select variable:", |
|
113 |
#' choices = variable_choices(data[["CO2"]]), |
|
114 |
#' selected = "Type", |
|
115 |
#' fixed = FALSE |
|
116 |
#' ) |
|
117 |
#' ), |
|
118 |
#' col_facet = data_extract_spec( |
|
119 |
#' dataname = "CO2", |
|
120 |
#' select = select_spec( |
|
121 |
#' label = "Select variable:", |
|
122 |
#' choices = variable_choices(data[["CO2"]]), |
|
123 |
#' selected = "Treatment", |
|
124 |
#' fixed = FALSE |
|
125 |
#' ) |
|
126 |
#' ) |
|
127 |
#' ) |
|
128 |
#' ) |
|
129 |
#' if (interactive()) { |
|
130 |
#' shinyApp(app$ui, app$server) |
|
131 |
#' } |
|
132 |
#' |
|
133 |
#' @examplesShinylive |
|
134 |
#' library(teal.modules.general) |
|
135 |
#' interactive <- function() TRUE |
|
136 |
#' {{ next_example }} |
|
137 |
#' @examples |
|
138 |
#' # CDISC data example |
|
139 |
#' data <- teal_data() |
|
140 |
#' data <- within(data, { |
|
141 |
#' require(nestcolor) |
|
142 |
#' ADSL <- teal.data::rADSL |
|
143 |
#' }) |
|
144 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
145 |
#' |
|
146 |
#' app <- init( |
|
147 |
#' data = data, |
|
148 |
#' modules = tm_g_bivariate( |
|
149 |
#' x = data_extract_spec( |
|
150 |
#' dataname = "ADSL", |
|
151 |
#' select = select_spec( |
|
152 |
#' label = "Select variable:", |
|
153 |
#' choices = variable_choices(data[["ADSL"]]), |
|
154 |
#' selected = "AGE", |
|
155 |
#' fixed = FALSE |
|
156 |
#' ) |
|
157 |
#' ), |
|
158 |
#' y = data_extract_spec( |
|
159 |
#' dataname = "ADSL", |
|
160 |
#' select = select_spec( |
|
161 |
#' label = "Select variable:", |
|
162 |
#' choices = variable_choices(data[["ADSL"]]), |
|
163 |
#' selected = "SEX", |
|
164 |
#' multiple = FALSE, |
|
165 |
#' fixed = FALSE |
|
166 |
#' ) |
|
167 |
#' ), |
|
168 |
#' row_facet = data_extract_spec( |
|
169 |
#' dataname = "ADSL", |
|
170 |
#' select = select_spec( |
|
171 |
#' label = "Select variable:", |
|
172 |
#' choices = variable_choices(data[["ADSL"]]), |
|
173 |
#' selected = "ARM", |
|
174 |
#' fixed = FALSE |
|
175 |
#' ) |
|
176 |
#' ), |
|
177 |
#' col_facet = data_extract_spec( |
|
178 |
#' dataname = "ADSL", |
|
179 |
#' select = select_spec( |
|
180 |
#' label = "Select variable:", |
|
181 |
#' choices = variable_choices(data[["ADSL"]]), |
|
182 |
#' selected = "COUNTRY", |
|
183 |
#' fixed = FALSE |
|
184 |
#' ) |
|
185 |
#' ) |
|
186 |
#' ) |
|
187 |
#' ) |
|
188 |
#' if (interactive()) { |
|
189 |
#' shinyApp(app$ui, app$server) |
|
190 |
#' } |
|
191 |
#' |
|
192 |
#' @export |
|
193 |
#' |
|
194 |
tm_g_bivariate <- function(label = "Bivariate Plots", |
|
195 |
x, |
|
196 |
y, |
|
197 |
row_facet = NULL, |
|
198 |
col_facet = NULL, |
|
199 |
facet = !is.null(row_facet) || !is.null(col_facet), |
|
200 |
color = NULL, |
|
201 |
fill = NULL, |
|
202 |
size = NULL, |
|
203 |
use_density = FALSE, |
|
204 |
color_settings = FALSE, |
|
205 |
free_x_scales = FALSE, |
|
206 |
free_y_scales = FALSE, |
|
207 |
plot_height = c(600, 200, 2000), |
|
208 |
plot_width = NULL, |
|
209 |
rotate_xaxis_labels = FALSE, |
|
210 |
swap_axes = FALSE, |
|
211 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
212 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
213 |
pre_output = NULL, |
|
214 |
post_output = NULL, |
|
215 |
transformators = list(), |
|
216 |
decorators = list()) { |
|
217 | 18x |
message("Initializing tm_g_bivariate") |
218 | ||
219 |
# Normalize the parameters |
|
220 | 14x |
if (inherits(x, "data_extract_spec")) x <- list(x) |
221 | 13x |
if (inherits(y, "data_extract_spec")) y <- list(y) |
222 | 1x |
if (inherits(row_facet, "data_extract_spec")) row_facet <- list(row_facet) |
223 | 1x |
if (inherits(col_facet, "data_extract_spec")) col_facet <- list(col_facet) |
224 | 1x |
if (inherits(color, "data_extract_spec")) color <- list(color) |
225 | 1x |
if (inherits(fill, "data_extract_spec")) fill <- list(fill) |
226 | 1x |
if (inherits(size, "data_extract_spec")) size <- list(size) |
227 | ||
228 |
# Start of assertions |
|
229 | 18x |
checkmate::assert_string(label) |
230 | ||
231 | 18x |
checkmate::assert_list(x, types = "data_extract_spec") |
232 | 18x |
assert_single_selection(x) |
233 | ||
234 | 16x |
checkmate::assert_list(y, types = "data_extract_spec") |
235 | 16x |
assert_single_selection(y) |
236 | ||
237 | 14x |
checkmate::assert_list(row_facet, types = "data_extract_spec", null.ok = TRUE) |
238 | 14x |
assert_single_selection(row_facet) |
239 | ||
240 | 14x |
checkmate::assert_list(col_facet, types = "data_extract_spec", null.ok = TRUE) |
241 | 14x |
assert_single_selection(col_facet) |
242 | ||
243 | 14x |
checkmate::assert_flag(facet) |
244 | ||
245 | 14x |
checkmate::assert_list(color, types = "data_extract_spec", null.ok = TRUE) |
246 | 14x |
assert_single_selection(color) |
247 | ||
248 | 14x |
checkmate::assert_list(fill, types = "data_extract_spec", null.ok = TRUE) |
249 | 14x |
assert_single_selection(fill) |
250 | ||
251 | 14x |
checkmate::assert_list(size, types = "data_extract_spec", null.ok = TRUE) |
252 | 14x |
assert_single_selection(size) |
253 | ||
254 | 14x |
checkmate::assert_flag(use_density) |
255 | ||
256 |
# Determines color, fill & size if they are not explicitly set |
|
257 | 14x |
checkmate::assert_flag(color_settings) |
258 | 14x |
if (color_settings) { |
259 | 2x |
if (is.null(color)) { |
260 | 2x |
color <- x |
261 | 2x |
color[[1]]$select <- teal.transform::select_spec(choices = color[[1]]$select$choices, selected = NULL) |
262 |
} |
|
263 | 2x |
if (is.null(fill)) { |
264 | 2x |
fill <- x |
265 | 2x |
fill[[1]]$select <- teal.transform::select_spec(choices = fill[[1]]$select$choices, selected = NULL) |
266 |
} |
|
267 | 2x |
if (is.null(size)) { |
268 | 2x |
size <- x |
269 | 2x |
size[[1]]$select <- teal.transform::select_spec(choices = size[[1]]$select$choices, selected = NULL) |
270 |
} |
|
271 |
} else { |
|
272 | 12x |
if (!is.null(c(color, fill, size))) { |
273 | 3x |
stop("'color_settings' argument needs to be set to TRUE if 'color', 'fill', and/or 'size' is/are supplied.") |
274 |
} |
|
275 |
} |
|
276 | ||
277 | 11x |
checkmate::assert_flag(free_x_scales) |
278 | 11x |
checkmate::assert_flag(free_y_scales) |
279 | ||
280 | 11x |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
281 | 10x |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
282 | 8x |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
283 | 7x |
checkmate::assert_numeric( |
284 | 7x |
plot_width[1], |
285 | 7x |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
286 |
) |
|
287 | ||
288 | 5x |
checkmate::assert_flag(rotate_xaxis_labels) |
289 | 5x |
checkmate::assert_flag(swap_axes) |
290 | ||
291 | 5x |
ggtheme <- match.arg(ggtheme) |
292 | 5x |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
293 | ||
294 | 5x |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
295 | 5x |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
296 | ||
297 | 5x |
assert_decorators(decorators, "plot") |
298 |
# End of assertions |
|
299 | ||
300 |
# Make UI args |
|
301 | 5x |
args <- as.list(environment()) |
302 | ||
303 | 5x |
data_extract_list <- list( |
304 | 5x |
x = x, |
305 | 5x |
y = y, |
306 | 5x |
row_facet = row_facet, |
307 | 5x |
col_facet = col_facet, |
308 | 5x |
color_settings = color_settings, |
309 | 5x |
color = color, |
310 | 5x |
fill = fill, |
311 | 5x |
size = size |
312 |
) |
|
313 | ||
314 | 5x |
ans <- module( |
315 | 5x |
label = label, |
316 | 5x |
server = srv_g_bivariate, |
317 | 5x |
ui = ui_g_bivariate, |
318 | 5x |
ui_args = args, |
319 | 5x |
server_args = c( |
320 | 5x |
data_extract_list, |
321 | 5x |
list(plot_height = plot_height, plot_width = plot_width, ggplot2_args = ggplot2_args, decorators = decorators) |
322 |
), |
|
323 | 5x |
transformators = transformators, |
324 | 5x |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
325 |
) |
|
326 | 5x |
attr(ans, "teal_bookmarkable") <- TRUE |
327 | 5x |
ans |
328 |
} |
|
329 | ||
330 |
# UI function for the bivariate module |
|
331 |
ui_g_bivariate <- function(id, ...) { |
|
332 | ! |
args <- list(...) |
333 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset( |
334 | ! |
args$x, args$y, args$row_facet, args$col_facet, args$color, args$fill, args$size |
335 |
) |
|
336 | ||
337 | ! |
ns <- NS(id) |
338 | ! |
teal.widgets::standard_layout( |
339 | ! |
output = teal.widgets::white_small_well( |
340 | ! |
tags$div(teal.widgets::plot_with_settings_ui(id = ns("myplot"))) |
341 |
), |
|
342 | ! |
encoding = tags$div( |
343 | ! |
tags$label("Encodings", class = "text-primary"), |
344 | ! |
teal.transform::datanames_input(args[c("x", "y", "row_facet", "col_facet", "color", "fill", "size")]), |
345 | ! |
teal.transform::data_extract_ui( |
346 | ! |
id = ns("x"), |
347 | ! |
label = "X variable", |
348 | ! |
data_extract_spec = args$x, |
349 | ! |
is_single_dataset = is_single_dataset_value |
350 |
), |
|
351 | ! |
teal.transform::data_extract_ui( |
352 | ! |
id = ns("y"), |
353 | ! |
label = "Y variable", |
354 | ! |
data_extract_spec = args$y, |
355 | ! |
is_single_dataset = is_single_dataset_value |
356 |
), |
|
357 | ! |
conditionalPanel( |
358 | ! |
condition = |
359 | ! |
"$(\"button[data-id*='-x-dataset'][data-id$='-select']\").text() == '- Nothing selected - ' || |
360 | ! |
$(\"button[data-id*='-y-dataset'][data-id$='-select']\").text() == '- Nothing selected - ' ", |
361 | ! |
shinyWidgets::radioGroupButtons( |
362 | ! |
inputId = ns("use_density"), |
363 | ! |
label = NULL, |
364 | ! |
choices = c("frequency", "density"), |
365 | ! |
selected = ifelse(args$use_density, "density", "frequency"), |
366 | ! |
justified = TRUE |
367 |
) |
|
368 |
), |
|
369 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")), |
370 | ! |
if (!is.null(args$row_facet) || !is.null(args$col_facet)) { |
371 | ! |
tags$div( |
372 | ! |
class = "data-extract-box", |
373 | ! |
tags$br(), |
374 | ! |
bslib::input_switch( |
375 | ! |
id = ns("facetting"), |
376 | ! |
label = "Facetting", |
377 | ! |
value = args$facet |
378 |
), |
|
379 | ! |
conditionalPanel( |
380 | ! |
condition = paste0("input['", ns("facetting"), "']"), |
381 | ! |
tags$div( |
382 | ! |
if (!is.null(args$row_facet)) { |
383 | ! |
teal.transform::data_extract_ui( |
384 | ! |
id = ns("row_facet"), |
385 | ! |
label = "Row facetting variable", |
386 | ! |
data_extract_spec = args$row_facet, |
387 | ! |
is_single_dataset = is_single_dataset_value |
388 |
) |
|
389 |
}, |
|
390 | ! |
if (!is.null(args$col_facet)) { |
391 | ! |
teal.transform::data_extract_ui( |
392 | ! |
id = ns("col_facet"), |
393 | ! |
label = "Column facetting variable", |
394 | ! |
data_extract_spec = args$col_facet, |
395 | ! |
is_single_dataset = is_single_dataset_value |
396 |
) |
|
397 |
}, |
|
398 | ! |
checkboxInput(ns("free_x_scales"), "free x scales", value = args$free_x_scales), |
399 | ! |
checkboxInput(ns("free_y_scales"), "free y scales", value = args$free_y_scales) |
400 |
) |
|
401 |
) |
|
402 |
) |
|
403 |
}, |
|
404 | ! |
if (args$color_settings) { |
405 |
# Put a grey border around the coloring settings |
|
406 | ! |
tags$div( |
407 | ! |
class = "data-extract-box", |
408 | ! |
tags$label("Color settings"), |
409 | ! |
bslib::input_switch( |
410 | ! |
id = ns("coloring"), |
411 | ! |
label = "Color settings", |
412 | ! |
value = TRUE |
413 |
), |
|
414 | ! |
conditionalPanel( |
415 | ! |
condition = paste0("input['", ns("coloring"), "']"), |
416 | ! |
tags$div( |
417 | ! |
teal.transform::data_extract_ui( |
418 | ! |
id = ns("color"), |
419 | ! |
label = "Outline color by variable", |
420 | ! |
data_extract_spec = args$color, |
421 | ! |
is_single_dataset = is_single_dataset_value |
422 |
), |
|
423 | ! |
teal.transform::data_extract_ui( |
424 | ! |
id = ns("fill"), |
425 | ! |
label = "Fill color by variable", |
426 | ! |
data_extract_spec = args$fill, |
427 | ! |
is_single_dataset = is_single_dataset_value |
428 |
), |
|
429 | ! |
tags$div( |
430 | ! |
id = ns("size_settings"), |
431 | ! |
teal.transform::data_extract_ui( |
432 | ! |
id = ns("size"), |
433 | ! |
label = "Size of points by variable (only if x and y are numeric)", |
434 | ! |
data_extract_spec = args$size, |
435 | ! |
is_single_dataset = is_single_dataset_value |
436 |
) |
|
437 |
) |
|
438 |
) |
|
439 |
) |
|
440 |
) |
|
441 |
}, |
|
442 | ! |
bslib::accordion( |
443 | ! |
open = TRUE, |
444 | ! |
bslib::accordion_panel( |
445 | ! |
title = "Plot settings", |
446 | ! |
checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = args$rotate_xaxis_labels), |
447 | ! |
checkboxInput(ns("swap_axes"), "Swap axes", value = args$swap_axes), |
448 | ! |
selectInput( |
449 | ! |
inputId = ns("ggtheme"), |
450 | ! |
label = "Theme (by ggplot):", |
451 | ! |
choices = ggplot_themes, |
452 | ! |
selected = args$ggtheme, |
453 | ! |
multiple = FALSE |
454 |
), |
|
455 | ! |
sliderInput( |
456 | ! |
ns("alpha"), "Opacity Scatterplot:", |
457 | ! |
min = 0, max = 1, |
458 | ! |
step = .05, value = .5, ticks = FALSE |
459 |
), |
|
460 | ! |
sliderInput( |
461 | ! |
ns("fixed_size"), "Scatterplot point size:", |
462 | ! |
min = 1, max = 8, |
463 | ! |
step = 1, value = 2, ticks = FALSE |
464 |
), |
|
465 | ! |
checkboxInput(ns("add_lines"), "Add lines"), |
466 |
) |
|
467 |
) |
|
468 |
), |
|
469 | ! |
forms = tagList( |
470 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
471 |
), |
|
472 | ! |
pre_output = args$pre_output, |
473 | ! |
post_output = args$post_output |
474 |
) |
|
475 |
} |
|
476 | ||
477 |
# Server function for the bivariate module |
|
478 |
srv_g_bivariate <- function(id, |
|
479 |
data, |
|
480 |
x, |
|
481 |
y, |
|
482 |
row_facet, |
|
483 |
col_facet, |
|
484 |
color_settings = FALSE, |
|
485 |
color, |
|
486 |
fill, |
|
487 |
size, |
|
488 |
plot_height, |
|
489 |
plot_width, |
|
490 |
ggplot2_args, |
|
491 |
decorators) { |
|
492 | ! |
checkmate::assert_class(data, "reactive") |
493 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
494 | ! |
moduleServer(id, function(input, output, session) { |
495 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
496 | ||
497 | ! |
ns <- session$ns |
498 | ||
499 | ! |
data_extract <- list( |
500 | ! |
x = x, y = y, row_facet = row_facet, col_facet = col_facet, |
501 | ! |
color = color, fill = fill, size = size |
502 |
) |
|
503 | ||
504 | ! |
rule_var <- function(other) { |
505 | ! |
function(value) { |
506 | ! |
othervalue <- selector_list()[[other]]()$select |
507 | ! |
if (length(value) == 0L && length(othervalue) == 0L) { |
508 | ! |
"Please select at least one of x-variable or y-variable" |
509 |
} |
|
510 |
} |
|
511 |
} |
|
512 | ! |
rule_diff <- function(other) { |
513 | ! |
function(value) { |
514 | ! |
othervalue <- selector_list()[[other]]()[["select"]] |
515 | ! |
if (!is.null(othervalue)) { |
516 | ! |
if (identical(value, othervalue)) { |
517 | ! |
"Row and column facetting variables must be different." |
518 |
} |
|
519 |
} |
|
520 |
} |
|
521 |
} |
|
522 | ||
523 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
524 | ! |
data_extract = data_extract, |
525 | ! |
datasets = data, |
526 | ! |
select_validation_rule = list( |
527 | ! |
x = rule_var("y"), |
528 | ! |
y = rule_var("x"), |
529 | ! |
row_facet = shinyvalidate::compose_rules( |
530 | ! |
shinyvalidate::sv_optional(), |
531 | ! |
rule_diff("col_facet") |
532 |
), |
|
533 | ! |
col_facet = shinyvalidate::compose_rules( |
534 | ! |
shinyvalidate::sv_optional(), |
535 | ! |
rule_diff("row_facet") |
536 |
) |
|
537 |
) |
|
538 |
) |
|
539 | ||
540 | ! |
iv_r <- reactive({ |
541 | ! |
iv_facet <- shinyvalidate::InputValidator$new() |
542 | ! |
iv_child <- teal.transform::compose_and_enable_validators(iv_facet, selector_list, |
543 | ! |
validator_names = c("row_facet", "col_facet") |
544 |
) |
|
545 | ! |
iv_child$condition(~ isTRUE(input$facetting)) |
546 | ||
547 | ! |
iv <- shinyvalidate::InputValidator$new() |
548 | ! |
iv$add_validator(iv_child) |
549 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list, validator_names = c("x", "y")) |
550 |
}) |
|
551 | ||
552 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
553 | ! |
selector_list = selector_list, |
554 | ! |
datasets = data |
555 |
) |
|
556 | ||
557 | ! |
anl_merged_q <- reactive({ |
558 | ! |
obj <- data() |
559 | ! |
teal.reporter::teal_card(obj) <- |
560 | ! |
c( |
561 | ! |
teal.reporter::teal_card("# Bivariate Plot"), |
562 | ! |
teal.reporter::teal_card(obj), |
563 | ! |
teal.reporter::teal_card("## Module's code") |
564 |
) |
|
565 | ! |
obj %>% |
566 | ! |
teal.code::eval_code( |
567 | ! |
c( |
568 | ! |
'library("ggplot2");library("dplyr")', # nolint: quotes |
569 | ! |
as.expression(anl_merged_input()$expr) |
570 |
) |
|
571 |
) |
|
572 |
}) |
|
573 | ||
574 | ! |
merged <- list( |
575 | ! |
anl_input_r = anl_merged_input, |
576 | ! |
anl_q_r = anl_merged_q |
577 |
) |
|
578 | ||
579 | ! |
output_q <- reactive({ |
580 | ! |
teal::validate_inputs(iv_r()) |
581 | ||
582 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
583 | ! |
teal::validate_has_data(ANL, 3) |
584 | ||
585 | ! |
x_col_vec <- as.vector(merged$anl_input_r()$columns_source$x) |
586 | ! |
x_name <- `if`(is.null(x_col_vec), character(0), x_col_vec) |
587 | ! |
y_col_vec <- as.vector(merged$anl_input_r()$columns_source$y) |
588 | ! |
y_name <- `if`(is.null(y_col_vec), character(0), y_col_vec) |
589 | ||
590 | ! |
row_facet_name <- as.vector(merged$anl_input_r()$columns_source$row_facet) |
591 | ! |
col_facet_name <- as.vector(merged$anl_input_r()$columns_source$col_facet) |
592 | ! |
color_name <- if ("color" %in% names(merged$anl_input_r()$columns_source)) { |
593 | ! |
as.vector(merged$anl_input_r()$columns_source$color) |
594 |
} else { |
|
595 | ! |
character(0) |
596 |
} |
|
597 | ! |
fill_name <- if ("fill" %in% names(merged$anl_input_r()$columns_source)) { |
598 | ! |
as.vector(merged$anl_input_r()$columns_source$fill) |
599 |
} else { |
|
600 | ! |
character(0) |
601 |
} |
|
602 | ! |
size_name <- if ("size" %in% names(merged$anl_input_r()$columns_source)) { |
603 | ! |
as.vector(merged$anl_input_r()$columns_source$size) |
604 |
} else { |
|
605 | ! |
character(0) |
606 |
} |
|
607 | ||
608 | ! |
use_density <- input$use_density == "density" |
609 | ! |
free_x_scales <- input$free_x_scales |
610 | ! |
free_y_scales <- input$free_y_scales |
611 | ! |
ggtheme <- input$ggtheme |
612 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
613 | ! |
swap_axes <- input$swap_axes |
614 | ||
615 | ! |
is_scatterplot <- all(vapply(ANL[c(x_name, y_name)], is.numeric, logical(1))) && |
616 | ! |
length(x_name) > 0 && length(y_name) > 0 |
617 | ||
618 | ! |
if (is_scatterplot) { |
619 | ! |
shinyjs::show("alpha") |
620 | ! |
alpha <- input$alpha |
621 | ! |
shinyjs::show("add_lines") |
622 | ||
623 | ! |
if (color_settings && input$coloring) { |
624 | ! |
shinyjs::hide("fixed_size") |
625 | ! |
shinyjs::show("size_settings") |
626 | ! |
size <- NULL |
627 |
} else { |
|
628 | ! |
shinyjs::show("fixed_size") |
629 | ! |
size <- input$fixed_size |
630 |
} |
|
631 |
} else { |
|
632 | ! |
shinyjs::hide("add_lines") |
633 | ! |
updateCheckboxInput(session, "add_lines", value = restoreInput(ns("add_lines"), FALSE)) |
634 | ! |
shinyjs::hide("alpha") |
635 | ! |
shinyjs::hide("fixed_size") |
636 | ! |
shinyjs::hide("size_settings") |
637 | ! |
alpha <- 1 |
638 | ! |
size <- NULL |
639 |
} |
|
640 | ||
641 | ! |
teal::validate_has_data(ANL[, c(x_name, y_name), drop = FALSE], 3, complete = TRUE, allow_inf = FALSE) |
642 | ||
643 | ! |
cl <- bivariate_plot_call( |
644 | ! |
data_name = "ANL", |
645 | ! |
x = x_name, |
646 | ! |
y = y_name, |
647 | ! |
x_class = ifelse(!identical(x_name, character(0)), class(ANL[[x_name]]), "NULL"), |
648 | ! |
y_class = ifelse(!identical(y_name, character(0)), class(ANL[[y_name]]), "NULL"), |
649 | ! |
x_label = varname_w_label(x_name, ANL), |
650 | ! |
y_label = varname_w_label(y_name, ANL), |
651 | ! |
freq = !use_density, |
652 | ! |
theme = ggtheme, |
653 | ! |
rotate_xaxis_labels = rotate_xaxis_labels, |
654 | ! |
swap_axes = swap_axes, |
655 | ! |
alpha = alpha, |
656 | ! |
size = size, |
657 | ! |
ggplot2_args = ggplot2_args |
658 |
) |
|
659 | ||
660 | ! |
facetting <- (isTRUE(input$facetting) && (!is.null(row_facet_name) || !is.null(col_facet_name))) |
661 | ||
662 | ! |
if (facetting) { |
663 | ! |
facet_cl <- facet_ggplot_call(row_facet_name, col_facet_name, free_x_scales, free_y_scales) |
664 | ||
665 | ! |
if (!is.null(facet_cl)) { |
666 | ! |
cl <- call("+", cl, facet_cl) |
667 |
} |
|
668 |
} |
|
669 | ||
670 | ! |
if (input$add_lines) { |
671 | ! |
cl <- call("+", cl, quote(geom_line(size = 1))) |
672 |
} |
|
673 | ||
674 | ! |
coloring_cl <- NULL |
675 | ! |
if (color_settings) { |
676 | ! |
if (input$coloring) { |
677 | ! |
coloring_cl <- coloring_ggplot_call( |
678 | ! |
colour = color_name, |
679 | ! |
fill = fill_name, |
680 | ! |
size = size_name, |
681 | ! |
is_point = any(grepl("geom_point", cl %>% deparse())) |
682 |
) |
|
683 | ! |
legend_lbls <- substitute( |
684 | ! |
expr = labs(color = color_name, fill = fill_name, size = size_name), |
685 | ! |
env = list( |
686 | ! |
color_name = varname_w_label(color_name, ANL), |
687 | ! |
fill_name = varname_w_label(fill_name, ANL), |
688 | ! |
size_name = varname_w_label(size_name, ANL) |
689 |
) |
|
690 |
) |
|
691 |
} |
|
692 | ! |
if (!is.null(coloring_cl)) { |
693 | ! |
cl <- call("+", call("+", cl, coloring_cl), legend_lbls) |
694 |
} |
|
695 |
} |
|
696 | ||
697 | ! |
obj <- merged$anl_q_r() |
698 | ! |
teal.reporter::teal_card(obj) <- c(teal.reporter::teal_card(obj), "## Plot") |
699 | ! |
teal.code::eval_code(obj, substitute(expr = plot <- cl, env = list(cl = cl))) |
700 |
}) |
|
701 | ||
702 | ! |
decorated_output_q_facets <- srv_decorate_teal_data( |
703 | ! |
"decorator", |
704 | ! |
data = output_q, |
705 | ! |
decorators = select_decorators(decorators, "plot"), |
706 | ! |
expr = reactive({ |
707 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
708 | ! |
row_facet_name <- as.vector(merged$anl_input_r()$columns_source$row_facet) |
709 | ! |
col_facet_name <- as.vector(merged$anl_input_r()$columns_source$col_facet) |
710 | ||
711 |
# Add labels to facets |
|
712 | ! |
nulled_row_facet_name <- varname_w_label(row_facet_name, ANL) |
713 | ! |
nulled_col_facet_name <- varname_w_label(col_facet_name, ANL) |
714 | ! |
facetting <- (isTRUE(input$facetting) && (!is.null(row_facet_name) || !is.null(col_facet_name))) |
715 | ! |
without_facet <- (is.null(nulled_row_facet_name) && is.null(nulled_col_facet_name)) || !facetting |
716 | ||
717 | ! |
print_call <- if (without_facet) { |
718 | ! |
quote(plot) |
719 |
} else { |
|
720 | ! |
substitute( |
721 | ! |
expr = { |
722 | ! |
teal.modules.general::add_facet_labels( |
723 | ! |
plot, |
724 | ! |
xfacet_label = nulled_col_facet_name, |
725 | ! |
yfacet_label = nulled_row_facet_name |
726 |
) |
|
727 |
}, |
|
728 | ! |
env = list(nulled_col_facet_name = nulled_col_facet_name, nulled_row_facet_name = nulled_row_facet_name) |
729 |
) |
|
730 |
} |
|
731 | ! |
print_call |
732 |
}) |
|
733 |
) |
|
734 | ||
735 | ! |
plot_r <- reactive(req(decorated_output_q_facets())[["plot"]]) |
736 | ||
737 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
738 | ! |
id = "myplot", |
739 | ! |
plot_r = plot_r, |
740 | ! |
height = plot_height, |
741 | ! |
width = plot_width |
742 |
) |
|
743 | ||
744 | ! |
decorated_output_dims_q <- set_chunk_dims(pws, decorated_output_q_facets) |
745 | ||
746 |
# Render R code. |
|
747 | ||
748 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_output_dims_q()))) |
749 | ||
750 | ! |
teal.widgets::verbatim_popup_srv( |
751 | ! |
id = "rcode", |
752 | ! |
verbatim_content = source_code_r, |
753 | ! |
title = "Bivariate Plot" |
754 |
) |
|
755 | ! |
decorated_output_dims_q |
756 |
}) |
|
757 |
} |
|
758 | ||
759 |
# Get Substituted ggplot call |
|
760 |
bivariate_plot_call <- function(data_name, |
|
761 |
x = character(0), |
|
762 |
y = character(0), |
|
763 |
x_class = "NULL", |
|
764 |
y_class = "NULL", |
|
765 |
x_label = NULL, |
|
766 |
y_label = NULL, |
|
767 |
freq = TRUE, |
|
768 |
theme = "gray", |
|
769 |
rotate_xaxis_labels = FALSE, |
|
770 |
swap_axes = FALSE, |
|
771 |
alpha = double(0), |
|
772 |
size = 2, |
|
773 |
ggplot2_args = teal.widgets::ggplot2_args()) { |
|
774 | ! |
supported_types <- c("NULL", "numeric", "integer", "factor", "character", "logical", "ordered") |
775 | ! |
validate(need(x_class %in% supported_types, paste0("Data type '", x_class, "' is not supported."))) |
776 | ! |
validate(need(y_class %in% supported_types, paste0("Data type '", y_class, "' is not supported."))) |
777 | ||
778 | ||
779 | ! |
if (identical(x, character(0))) { |
780 | ! |
x <- x_label <- "-" |
781 |
} else { |
|
782 | ! |
x <- if (is.call(x)) x else as.name(x) |
783 |
} |
|
784 | ! |
if (identical(y, character(0))) { |
785 | ! |
y <- y_label <- "-" |
786 |
} else { |
|
787 | ! |
y <- if (is.call(y)) y else as.name(y) |
788 |
} |
|
789 | ||
790 | ! |
cl <- bivariate_ggplot_call( |
791 | ! |
x_class = x_class, |
792 | ! |
y_class = y_class, |
793 | ! |
freq = freq, |
794 | ! |
theme = theme, |
795 | ! |
rotate_xaxis_labels = rotate_xaxis_labels, |
796 | ! |
swap_axes = swap_axes, |
797 | ! |
alpha = alpha, |
798 | ! |
size = size, |
799 | ! |
ggplot2_args = ggplot2_args, |
800 | ! |
x = x, |
801 | ! |
y = y, |
802 | ! |
xlab = x_label, |
803 | ! |
ylab = y_label, |
804 | ! |
data_name = data_name |
805 |
) |
|
806 |
} |
|
807 | ||
808 |
# Create ggplot part of plot call |
|
809 |
# Due to the type of the x and y variable the plot type is chosen |
|
810 |
bivariate_ggplot_call <- function(x_class, |
|
811 |
y_class, |
|
812 |
freq = TRUE, |
|
813 |
theme = "gray", |
|
814 |
rotate_xaxis_labels = FALSE, |
|
815 |
swap_axes = FALSE, |
|
816 |
size = double(0), |
|
817 |
alpha = double(0), |
|
818 |
x = NULL, |
|
819 |
y = NULL, |
|
820 |
xlab = "-", |
|
821 |
ylab = "-", |
|
822 |
data_name = "ANL", |
|
823 |
ggplot2_args = teal.widgets::ggplot2_args()) { |
|
824 | 42x |
x_class <- switch(x_class, |
825 | 42x |
"character" = , |
826 | 42x |
"ordered" = , |
827 | 42x |
"logical" = , |
828 | 42x |
"factor" = "factor", |
829 | 42x |
"integer" = , |
830 | 42x |
"numeric" = "numeric", |
831 | 42x |
"NULL" = "NULL", |
832 | 42x |
stop("unsupported x_class: ", x_class) |
833 |
) |
|
834 | 42x |
y_class <- switch(y_class, |
835 | 42x |
"character" = , |
836 | 42x |
"ordered" = , |
837 | 42x |
"logical" = , |
838 | 42x |
"factor" = "factor", |
839 | 42x |
"integer" = , |
840 | 42x |
"numeric" = "numeric", |
841 | 42x |
"NULL" = "NULL", |
842 | 42x |
stop("unsupported y_class: ", y_class) |
843 |
) |
|
844 | ||
845 | 42x |
if (all(c(x_class, y_class) == "NULL")) { |
846 | ! |
stop("either x or y is required") |
847 |
} |
|
848 | ||
849 | 42x |
reduce_plot_call <- function(...) { |
850 | 104x |
args <- Filter(Negate(is.null), list(...)) |
851 | 104x |
Reduce(function(x, y) call("+", x, y), args) |
852 |
} |
|
853 | ||
854 | 42x |
plot_call <- substitute(ggplot2::ggplot(data_name), env = list(data_name = as.name(data_name))) |
855 | ||
856 |
# Single data plots |
|
857 | 42x |
if (x_class == "numeric" && y_class == "NULL") { |
858 | 6x |
plot_call <- reduce_plot_call(plot_call, substitute(ggplot2::aes(x = xval), env = list(xval = x))) |
859 | ||
860 | 6x |
if (freq) { |
861 | 4x |
plot_call <- reduce_plot_call( |
862 | 4x |
plot_call, |
863 | 4x |
quote(ggplot2::geom_histogram(bins = 30)), |
864 | 4x |
quote(ggplot2::ylab("Frequency")) |
865 |
) |
|
866 |
} else { |
|
867 | 2x |
plot_call <- reduce_plot_call( |
868 | 2x |
plot_call, |
869 | 2x |
quote(ggplot2::geom_histogram(bins = 30, ggplot2::aes(y = ggplot2::after_stat(density)))), |
870 | 2x |
quote(ggplot2::geom_density(ggplot2::aes(y = ggplot2::after_stat(density)))), |
871 | 2x |
quote(ggplot2::ylab("Density")) |
872 |
) |
|
873 |
} |
|
874 | 36x |
} else if (x_class == "NULL" && y_class == "numeric") { |
875 | 6x |
plot_call <- reduce_plot_call(plot_call, substitute(ggplot2::aes(x = yval), env = list(yval = y))) |
876 | ||
877 | 6x |
if (freq) { |
878 | 4x |
plot_call <- reduce_plot_call( |
879 | 4x |
plot_call, |
880 | 4x |
quote(ggplot2::geom_histogram(bins = 30)), |
881 | 4x |
quote(ggplot2::ylab("Frequency")) |
882 |
) |
|
883 |
} else { |
|
884 | 2x |
plot_call <- reduce_plot_call( |
885 | 2x |
plot_call, |
886 | 2x |
quote(ggplot2::geom_histogram(bins = 30, ggplot2::aes(y = ggplot2::after_stat(density)))), |
887 | 2x |
quote(ggplot2::geom_density(ggplot2::aes(y = ggplot2::after_stat(density)))), |
888 | 2x |
quote(ggplot2::ylab("Density")) |
889 |
) |
|
890 |
} |
|
891 | 30x |
} else if (x_class == "factor" && y_class == "NULL") { |
892 | 4x |
plot_call <- reduce_plot_call(plot_call, substitute(ggplot2::aes(x = xval), env = list(xval = x))) |
893 | ||
894 | 4x |
if (freq) { |
895 | 2x |
plot_call <- reduce_plot_call( |
896 | 2x |
plot_call, |
897 | 2x |
quote(ggplot2::geom_bar()), |
898 | 2x |
quote(ggplot2::ylab("Frequency")) |
899 |
) |
|
900 |
} else { |
|
901 | 2x |
plot_call <- reduce_plot_call( |
902 | 2x |
plot_call, |
903 | 2x |
quote(ggplot2::geom_bar(ggplot2::aes(y = ggplot2::after_stat(prop), group = 1))), |
904 | 2x |
quote(ggplot2::ylab("Fraction")) |
905 |
) |
|
906 |
} |
|
907 | 26x |
} else if (x_class == "NULL" && y_class == "factor") { |
908 | 4x |
plot_call <- reduce_plot_call(plot_call, substitute(ggplot2::aes(x = yval), env = list(yval = y))) |
909 | ||
910 | 4x |
if (freq) { |
911 | 2x |
plot_call <- reduce_plot_call( |
912 | 2x |
plot_call, |
913 | 2x |
quote(ggplot2::geom_bar()), |
914 | 2x |
quote(ggplot2::ylab("Frequency")) |
915 |
) |
|
916 |
} else { |
|
917 | 2x |
plot_call <- reduce_plot_call( |
918 | 2x |
plot_call, |
919 | 2x |
quote(ggplot2::geom_bar(ggplot2::aes(y = ggplot2::after_stat(prop), group = 1))), |
920 | 2x |
quote(ggplot2::ylab("Fraction")) |
921 |
) |
|
922 |
} |
|
923 |
# Numeric Plots |
|
924 | 22x |
} else if (x_class == "numeric" && y_class == "numeric") { |
925 | 2x |
plot_call <- reduce_plot_call( |
926 | 2x |
plot_call, |
927 | 2x |
substitute(ggplot2::aes(x = xval, y = yval), env = list(xval = x, yval = y)), |
928 |
# pch = 21 for consistent coloring behaviour b/w all geoms (outline and fill properties) |
|
929 | 2x |
`if`( |
930 | 2x |
!is.null(size), |
931 | 2x |
substitute( |
932 | 2x |
ggplot2::geom_point(alpha = alphaval, size = sizeval, pch = 21), |
933 | 2x |
env = list(alphaval = alpha, sizeval = size) |
934 |
), |
|
935 | 2x |
substitute( |
936 | 2x |
ggplot2::geom_point(alpha = alphaval, pch = 21), |
937 | 2x |
env = list(alphaval = alpha) |
938 |
) |
|
939 |
) |
|
940 |
) |
|
941 | 20x |
} else if ((x_class == "numeric" && y_class == "factor") || (x_class == "factor" && y_class == "numeric")) { |
942 | 6x |
plot_call <- reduce_plot_call( |
943 | 6x |
plot_call, |
944 | 6x |
substitute(ggplot2::aes(x = xval, y = yval), env = list(xval = x, yval = y)), |
945 | 6x |
quote(ggplot2::geom_boxplot()) |
946 |
) |
|
947 |
# Factor and character plots |
|
948 | 14x |
} else if (x_class == "factor" && y_class == "factor") { |
949 | 14x |
plot_call <- reduce_plot_call( |
950 | 14x |
plot_call, |
951 | 14x |
substitute( |
952 | 14x |
ggmosaic::geom_mosaic(aes(x = ggmosaic::product(xval), fill = yval), na.rm = TRUE), |
953 | 14x |
env = list(xval = x, yval = y) |
954 |
) |
|
955 |
) |
|
956 |
} else { |
|
957 | ! |
stop("x y type combination not allowed") |
958 |
} |
|
959 | ||
960 | 42x |
labs_base <- if (x_class == "NULL") { |
961 | 10x |
list(x = substitute(ylab, list(ylab = ylab))) |
962 | 42x |
} else if (y_class == "NULL") { |
963 | 10x |
list(x = substitute(xlab, list(xlab = xlab))) |
964 |
} else { |
|
965 | 22x |
list( |
966 | 22x |
x = substitute(xlab, list(xlab = xlab)), |
967 | 22x |
y = substitute(ylab, list(ylab = ylab)) |
968 |
) |
|
969 |
} |
|
970 | ||
971 | 42x |
dev_ggplot2_args <- teal.widgets::ggplot2_args(labs = labs_base) |
972 | ||
973 | 42x |
if (rotate_xaxis_labels) { |
974 | ! |
dev_ggplot2_args$theme <- list(axis.text.x = quote(ggplot2::element_text(angle = 45, hjust = 1))) |
975 |
} |
|
976 | ||
977 | 42x |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
978 | 42x |
user_plot = ggplot2_args, |
979 | 42x |
module_plot = dev_ggplot2_args |
980 |
) |
|
981 | ||
982 | 42x |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args(all_ggplot2_args, ggtheme = theme) |
983 | ||
984 | 42x |
plot_call <- reduce_plot_call( |
985 | 42x |
plot_call, |
986 | 42x |
parsed_ggplot2_args$labs, |
987 | 42x |
parsed_ggplot2_args$ggtheme, |
988 | 42x |
parsed_ggplot2_args$theme |
989 |
) |
|
990 | ||
991 | 42x |
if (swap_axes) { |
992 | ! |
plot_call <- reduce_plot_call(plot_call, quote(coord_flip())) |
993 |
} |
|
994 | ||
995 | 42x |
plot_call |
996 |
} |
|
997 | ||
998 |
# Create facet call |
|
999 |
facet_ggplot_call <- function(row_facet = character(0), |
|
1000 |
col_facet = character(0), |
|
1001 |
free_x_scales = FALSE, |
|
1002 |
free_y_scales = FALSE) { |
|
1003 | ! |
scales <- if (free_x_scales && free_y_scales) { |
1004 | ! |
"free" |
1005 | ! |
} else if (free_x_scales) { |
1006 | ! |
"free_x" |
1007 | ! |
} else if (free_y_scales) { |
1008 | ! |
"free_y" |
1009 |
} else { |
|
1010 | ! |
"fixed" |
1011 |
} |
|
1012 | ||
1013 | ! |
if (identical(row_facet, character(0)) && identical(col_facet, character(0))) { |
1014 | ! |
NULL |
1015 | ! |
} else if (!identical(row_facet, character(0)) && !identical(col_facet, character(0))) { |
1016 | ! |
call( |
1017 | ! |
"facet_grid", |
1018 | ! |
rows = call_fun_dots("vars", row_facet), |
1019 | ! |
cols = call_fun_dots("vars", col_facet), |
1020 | ! |
scales = scales |
1021 |
) |
|
1022 | ! |
} else if (identical(row_facet, character(0)) && !identical(col_facet, character(0))) { |
1023 | ! |
call("facet_grid", cols = call_fun_dots("vars", col_facet), scales = scales) |
1024 | ! |
} else if (!identical(row_facet, character(0)) && identical(col_facet, character(0))) { |
1025 | ! |
call("facet_grid", rows = call_fun_dots("vars", row_facet), scales = scales) |
1026 |
} |
|
1027 |
} |
|
1028 | ||
1029 |
coloring_ggplot_call <- function(colour, |
|
1030 |
fill, |
|
1031 |
size, |
|
1032 |
is_point = FALSE) { |
|
1033 |
if ( |
|
1034 | 15x |
!identical(colour, character(0)) && |
1035 | 15x |
!identical(fill, character(0)) && |
1036 | 15x |
is_point && |
1037 | 15x |
!identical(size, character(0)) |
1038 |
) { |
|
1039 | 1x |
substitute( |
1040 | 1x |
expr = ggplot2::aes(colour = colour_name, fill = fill_name, size = size_name), |
1041 | 1x |
env = list(colour_name = as.name(colour), fill_name = as.name(fill), size_name = as.name(size)) |
1042 |
) |
|
1043 |
} else if ( |
|
1044 | 14x |
identical(colour, character(0)) && |
1045 | 14x |
!identical(fill, character(0)) && |
1046 | 14x |
is_point && |
1047 | 14x |
identical(size, character(0)) |
1048 |
) { |
|
1049 | 1x |
substitute(expr = ggplot2::aes(fill = fill_name), env = list(fill_name = as.name(fill))) |
1050 |
} else if ( |
|
1051 | 13x |
!identical(colour, character(0)) && |
1052 | 13x |
!identical(fill, character(0)) && |
1053 | 13x |
(!is_point || identical(size, character(0))) |
1054 |
) { |
|
1055 | 3x |
substitute( |
1056 | 3x |
expr = ggplot2::aes(colour = colour_name, fill = fill_name), |
1057 | 3x |
env = list(colour_name = as.name(colour), fill_name = as.name(fill)) |
1058 |
) |
|
1059 |
} else if ( |
|
1060 | 10x |
!identical(colour, character(0)) && |
1061 | 10x |
identical(fill, character(0)) && |
1062 | 10x |
(!is_point || identical(size, character(0))) |
1063 |
) { |
|
1064 | 1x |
substitute(expr = ggplot2::aes(colour = colour_name), env = list(colour_name = as.name(colour))) |
1065 |
} else if ( |
|
1066 | 9x |
identical(colour, character(0)) && |
1067 | 9x |
!identical(fill, character(0)) && |
1068 | 9x |
(!is_point || identical(size, character(0))) |
1069 |
) { |
|
1070 | 2x |
substitute(expr = ggplot2::aes(fill = fill_name), env = list(fill_name = as.name(fill))) |
1071 |
} else if ( |
|
1072 | 7x |
identical(colour, character(0)) && |
1073 | 7x |
identical(fill, character(0)) && |
1074 | 7x |
is_point && |
1075 | 7x |
!identical(size, character(0)) |
1076 |
) { |
|
1077 | 1x |
substitute(expr = ggplot2::aes(size = size_name), env = list(size_name = as.name(size))) |
1078 |
} else if ( |
|
1079 | 6x |
!identical(colour, character(0)) && |
1080 | 6x |
identical(fill, character(0)) && |
1081 | 6x |
is_point && |
1082 | 6x |
!identical(size, character(0)) |
1083 |
) { |
|
1084 | 1x |
substitute( |
1085 | 1x |
expr = ggplot2::aes(colour = colour_name, size = size_name), |
1086 | 1x |
env = list(colour_name = as.name(colour), size_name = as.name(size)) |
1087 |
) |
|
1088 |
} else if ( |
|
1089 | 5x |
identical(colour, character(0)) && |
1090 | 5x |
!identical(fill, character(0)) && |
1091 | 5x |
is_point && |
1092 | 5x |
!identical(size, character(0)) |
1093 |
) { |
|
1094 | 1x |
substitute( |
1095 | 1x |
expr = ggplot2::aes(colour = colour_name, fill = fill_name, size = size_name), |
1096 | 1x |
env = list(colour_name = as.name(fill), fill_name = as.name(fill), size_name = as.name(size)) |
1097 |
) |
|
1098 |
} else { |
|
1099 | 4x |
NULL |
1100 |
} |
|
1101 |
} |
1 |
#' `teal` module: Variable browser |
|
2 |
#' |
|
3 |
#' Module provides provides a detailed summary and visualization of variable distributions |
|
4 |
#' for `data.frame` objects, with interactive features to customize analysis. |
|
5 |
#' |
|
6 |
#' Numeric columns with fewer than 30 distinct values can be treated as either discrete |
|
7 |
#' or continuous with a checkbox allowing users to switch how they are treated(if < 6 unique values |
|
8 |
#' then the default is discrete, otherwise it is continuous). |
|
9 |
#' |
|
10 |
#' @inheritParams teal::module |
|
11 |
#' @inheritParams shared_params |
|
12 |
#' @param parent_dataname (`character(1)`) string specifying a parent dataset. |
|
13 |
#' If it exists in `datanames` then an extra checkbox will be shown to |
|
14 |
#' allow users to not show variables in other datasets which exist in this `dataname`. |
|
15 |
#' This is typically used to remove `ADSL` columns in `CDISC` data. |
|
16 |
#' In non `CDISC` data this can be ignored. Defaults to `"ADSL"`. |
|
17 |
#' @param datasets_selected (`character`) `r lifecycle::badge("deprecated")` vector of datasets to show, please |
|
18 |
#' use the `datanames` argument. |
|
19 |
#' |
|
20 |
#' @inherit shared_params return |
|
21 |
#' |
|
22 |
#' @examplesShinylive |
|
23 |
#' library(teal.modules.general) |
|
24 |
#' interactive <- function() TRUE |
|
25 |
#' {{ next_example }} |
|
26 |
# nolint start: line_length_linter. |
|
27 |
#' @examples |
|
28 |
# nolint end: line_length_linter. |
|
29 |
#' # general data example |
|
30 |
#' data <- teal_data() |
|
31 |
#' data <- within(data, { |
|
32 |
#' iris <- iris |
|
33 |
#' mtcars <- mtcars |
|
34 |
#' women <- women |
|
35 |
#' faithful <- faithful |
|
36 |
#' CO2 <- CO2 |
|
37 |
#' }) |
|
38 |
#' |
|
39 |
#' app <- init( |
|
40 |
#' data = data, |
|
41 |
#' modules = modules( |
|
42 |
#' tm_variable_browser( |
|
43 |
#' label = "Variable browser" |
|
44 |
#' ) |
|
45 |
#' ) |
|
46 |
#' ) |
|
47 |
#' if (interactive()) { |
|
48 |
#' shinyApp(app$ui, app$server) |
|
49 |
#' } |
|
50 |
#' |
|
51 |
#' @examplesShinylive |
|
52 |
#' library(teal.modules.general) |
|
53 |
#' interactive <- function() TRUE |
|
54 |
#' {{ next_example }} |
|
55 |
# nolint start: line_length_linter. |
|
56 |
#' @examples |
|
57 |
# nolint end: line_length_linter. |
|
58 |
#' # CDISC example data |
|
59 |
#' library(sparkline) |
|
60 |
#' data <- teal_data() |
|
61 |
#' data <- within(data, { |
|
62 |
#' ADSL <- teal.data::rADSL |
|
63 |
#' ADTTE <- teal.data::rADTTE |
|
64 |
#' }) |
|
65 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
66 |
#' |
|
67 |
#' app <- init( |
|
68 |
#' data = data, |
|
69 |
#' modules = modules( |
|
70 |
#' tm_variable_browser( |
|
71 |
#' label = "Variable browser" |
|
72 |
#' ) |
|
73 |
#' ) |
|
74 |
#' ) |
|
75 |
#' if (interactive()) { |
|
76 |
#' shinyApp(app$ui, app$server) |
|
77 |
#' } |
|
78 |
#' |
|
79 |
#' @export |
|
80 |
#' |
|
81 |
tm_variable_browser <- function(label = "Variable Browser", |
|
82 |
datasets_selected = deprecated(), |
|
83 |
datanames = if (missing(datasets_selected)) "all" else datasets_selected, |
|
84 |
parent_dataname = "ADSL", |
|
85 |
pre_output = NULL, |
|
86 |
post_output = NULL, |
|
87 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
88 |
transformators = list()) { |
|
89 | ! |
message("Initializing tm_variable_browser") |
90 | ||
91 |
# Start of assertions |
|
92 | ! |
checkmate::assert_string(label) |
93 | ! |
if (!missing(datasets_selected)) { |
94 | ! |
lifecycle::deprecate_stop( |
95 | ! |
when = "0.4.0", |
96 | ! |
what = "tm_variable_browser(datasets_selected)", |
97 | ! |
with = "tm_variable_browser(datanames)", |
98 | ! |
details = c( |
99 | ! |
"If both `datasets_selected` and `datanames` are set `datasets_selected` will be silently ignored.", |
100 | ! |
i = 'Use `tm_variable_browser(datanames = "all")` to keep the previous behavior and avoid this warning.' |
101 |
) |
|
102 |
) |
|
103 |
} |
|
104 | ! |
checkmate::assert_character(datanames, min.len = 0, min.chars = 1, null.ok = TRUE) |
105 | ! |
checkmate::assert_character(parent_dataname, min.len = 0, max.len = 1) |
106 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
107 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
108 | ! |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
109 |
# End of assertions |
|
110 | ||
111 | ! |
datanames_module <- if (identical(datanames, "all") || is.null(datanames)) { |
112 | ! |
datanames |
113 |
} else { |
|
114 | ! |
union(datanames, parent_dataname) |
115 |
} |
|
116 | ||
117 | ! |
ans <- module( |
118 | ! |
label, |
119 | ! |
server = srv_variable_browser, |
120 | ! |
ui = ui_variable_browser, |
121 | ! |
datanames = datanames_module, |
122 | ! |
server_args = list( |
123 | ! |
datanames = if (is.null(datanames)) "all" else datanames, |
124 | ! |
parent_dataname = parent_dataname, |
125 | ! |
ggplot2_args = ggplot2_args |
126 |
), |
|
127 | ! |
ui_args = list( |
128 | ! |
pre_output = pre_output, |
129 | ! |
post_output = post_output |
130 |
), |
|
131 | ! |
transformators = transformators |
132 |
) |
|
133 |
# `shiny` inputs are stored properly but the majority of the module is state of `datatable` which is not stored. |
|
134 | ! |
attr(ans, "teal_bookmarkable") <- NULL |
135 | ! |
ans |
136 |
} |
|
137 | ||
138 |
# UI function for the variable browser module |
|
139 |
ui_variable_browser <- function(id, |
|
140 |
pre_output = NULL, |
|
141 |
post_output = NULL) { |
|
142 | ! |
ns <- NS(id) |
143 | ||
144 | ! |
tags$div( |
145 | ! |
shinyjs::useShinyjs(), |
146 | ! |
teal.widgets::standard_layout( |
147 | ! |
output = tags$div( |
148 | ! |
htmlwidgets::getDependency("sparkline"), # needed for sparklines to work |
149 | ! |
bslib::layout_column_wrap( |
150 | ! |
width = 0.5, |
151 | ! |
teal.widgets::white_small_well( |
152 | ! |
uiOutput(ns("ui_variable_browser")), |
153 | ! |
shinyjs::hidden({ |
154 | ! |
checkboxInput(ns("show_parent_vars"), "Show parent dataset variables", value = FALSE) |
155 |
}) |
|
156 |
), |
|
157 | ! |
teal.widgets::white_small_well( |
158 | ! |
uiOutput(ns("ui_histogram_display")), |
159 | ! |
uiOutput(ns("ui_numeric_display")), |
160 | ! |
teal.widgets::plot_with_settings_ui(ns("variable_plot")), |
161 | ! |
tags$br(), |
162 | ! |
bslib::accordion( |
163 | ! |
open = TRUE, |
164 | ! |
bslib::accordion_panel( |
165 | ! |
title = "Plot settings", |
166 | ! |
collapsed = TRUE, |
167 | ! |
selectInput( |
168 | ! |
inputId = ns("ggplot_theme"), label = "ggplot2 theme", |
169 | ! |
choices = ggplot_themes, |
170 | ! |
selected = "grey" |
171 |
), |
|
172 | ! |
bslib::layout_columns( |
173 | ! |
col_widths = c(6, 6), |
174 | ! |
sliderInput( |
175 | ! |
inputId = ns("font_size"), label = "font size", |
176 | ! |
min = 5L, max = 30L, value = 15L, step = 1L, ticks = FALSE |
177 |
), |
|
178 | ! |
sliderInput( |
179 | ! |
inputId = ns("label_rotation"), label = "rotate x labels", |
180 | ! |
min = 0L, max = 90L, value = 45L, step = 1, ticks = FALSE |
181 |
) |
|
182 |
) |
|
183 |
) |
|
184 |
), |
|
185 | ! |
tags$br(), |
186 | ! |
teal.widgets::get_dt_rows(ns("variable_summary_table"), ns("variable_summary_table_rows")), |
187 | ! |
DT::dataTableOutput(ns("variable_summary_table")) |
188 |
) |
|
189 |
) |
|
190 |
), |
|
191 | ! |
pre_output = pre_output, |
192 | ! |
post_output = post_output |
193 |
) |
|
194 |
) |
|
195 |
} |
|
196 | ||
197 |
# Server function for the variable browser module |
|
198 |
srv_variable_browser <- function(id, |
|
199 |
data, |
|
200 |
datanames, parent_dataname, ggplot2_args) { |
|
201 | ! |
checkmate::assert_class(data, "reactive") |
202 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
203 | ! |
moduleServer(id, function(input, output, session) { |
204 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
205 | ||
206 |
# if there are < this number of unique records then a numeric |
|
207 |
# variable can be treated as a factor and all factors with < this groups |
|
208 |
# have their values plotted |
|
209 | ! |
.unique_records_for_factor <- 30 |
210 |
# if there are < this number of unique records then a numeric |
|
211 |
# variable is by default treated as a factor |
|
212 | ! |
.unique_records_default_as_factor <- 6 # nolint: object_length. |
213 | ||
214 | ! |
varname_numeric_as_factor <- reactiveValues() |
215 | ||
216 | ! |
datanames <- Filter(function(name) { |
217 | ! |
is.data.frame(isolate(data())[[name]]) |
218 | ! |
}, if (identical(datanames, "all")) names(isolate(data())) else datanames) |
219 | ||
220 | ! |
output$ui_variable_browser <- renderUI({ |
221 | ! |
ns <- session$ns |
222 | ! |
do.call( |
223 | ! |
tabsetPanel, |
224 | ! |
c( |
225 | ! |
id = ns("tabset_panel"), |
226 | ! |
do.call( |
227 | ! |
tagList, |
228 | ! |
lapply(datanames, function(dataname) { |
229 | ! |
tabPanel( |
230 | ! |
dataname, |
231 | ! |
tags$div( |
232 | ! |
style = "margin-top: 1rem;", |
233 | ! |
textOutput(ns(paste0("dataset_summary_", dataname))) |
234 |
), |
|
235 | ! |
tags$div( |
236 | ! |
style = "margin-top: 1rem;", |
237 | ! |
teal.widgets::get_dt_rows( |
238 | ! |
ns(paste0("variable_browser_", dataname)), |
239 | ! |
ns(paste0("variable_browser_", dataname, "_rows")) |
240 |
), |
|
241 | ! |
DT::dataTableOutput(ns(paste0("variable_browser_", dataname)), width = "100%") |
242 |
) |
|
243 |
) |
|
244 |
}) |
|
245 |
) |
|
246 |
) |
|
247 |
) |
|
248 |
}) |
|
249 | ||
250 |
# conditionally display checkbox |
|
251 | ! |
shinyjs::toggle( |
252 | ! |
id = "show_parent_vars", |
253 | ! |
condition = length(parent_dataname) > 0 && parent_dataname %in% datanames |
254 |
) |
|
255 | ||
256 | ! |
columns_names <- new.env() |
257 | ||
258 |
# plot_var$data holds the name of the currently selected dataset |
|
259 |
# plot_var$variable[[<dataset_name>]] holds the name of the currently selected |
|
260 |
# variable for dataset <dataset_name> |
|
261 | ! |
plot_var <- reactiveValues(data = NULL, variable = list()) |
262 | ||
263 | ! |
establish_updating_selection(datanames, input, plot_var, columns_names) |
264 | ||
265 |
# validations |
|
266 | ! |
validation_checks <- validate_input(input, plot_var, data) |
267 | ||
268 |
# data_for_analysis is a list with two elements: a column from a dataset and the column label |
|
269 | ! |
plotted_data <- reactive({ |
270 | ! |
validation_checks() |
271 | ||
272 | ! |
get_plotted_data(input, plot_var, data) |
273 |
}) |
|
274 | ||
275 | ! |
treat_numeric_as_factor <- reactive({ |
276 | ! |
if (is_num_var_short(.unique_records_for_factor, input, plotted_data)) { |
277 | ! |
input$numeric_as_factor |
278 |
} else { |
|
279 | ! |
FALSE |
280 |
} |
|
281 |
}) |
|
282 | ||
283 | ! |
render_tabset_panel_content( |
284 | ! |
input = input, |
285 | ! |
output = output, |
286 | ! |
data = data, |
287 | ! |
datanames = datanames, |
288 | ! |
parent_dataname = parent_dataname, |
289 | ! |
columns_names = columns_names, |
290 | ! |
plot_var = plot_var |
291 |
) |
|
292 |
# add used-defined text size to ggplot arguments passed from caller frame |
|
293 | ! |
all_ggplot2_args <- reactive({ |
294 | ! |
user_text <- teal.widgets::ggplot2_args( |
295 | ! |
theme = list( |
296 | ! |
"text" = ggplot2::element_text(size = input[["font_size"]]), |
297 | ! |
"axis.text.x" = ggplot2::element_text(angle = input[["label_rotation"]], hjust = 1) |
298 |
) |
|
299 |
) |
|
300 | ! |
user_theme <- utils::getFromNamespace(sprintf("theme_%s", input[["ggplot_theme"]]), ns = "ggplot2") |
301 | ! |
user_theme <- user_theme() |
302 |
# temporary fix to circumvent assertion issue with resolve_ggplot2_args |
|
303 |
# drop problematic elements |
|
304 | ! |
user_theme <- user_theme[grep("strip.text.y.left", names(user_theme), fixed = TRUE, invert = TRUE)] |
305 | ||
306 | ! |
teal.widgets::resolve_ggplot2_args( |
307 | ! |
user_plot = user_text, |
308 | ! |
user_default = teal.widgets::ggplot2_args(theme = user_theme), |
309 | ! |
module_plot = ggplot2_args |
310 |
) |
|
311 |
}) |
|
312 | ||
313 | ! |
output$ui_numeric_display <- renderUI({ |
314 | ! |
validation_checks() |
315 | ! |
dataname <- input$tabset_panel |
316 | ! |
varname <- plot_var$variable[[dataname]] |
317 | ! |
df <- data()[[dataname]] |
318 | ||
319 | ! |
numeric_ui <- bslib::page_fluid( |
320 | ! |
bslib::layout_columns( |
321 | ! |
col_widths = c(8, 4), |
322 | ! |
bslib::layout_columns( |
323 | ! |
col_widths = c(6, 6, 12), |
324 | ! |
style = bslib::css(grid_row_gap = 0), |
325 | ! |
bslib::input_switch( |
326 | ! |
id = session$ns("display_density"), |
327 | ! |
label = tags$div( |
328 | ! |
"Show density:", |
329 | ! |
bslib::tooltip( |
330 | ! |
trigger = icon("circle-info"), |
331 | ! |
tags$span( |
332 | ! |
"Show kernel density estimation with gaussian kernel and bandwidth function bw.nrd0 (R default)" |
333 |
) |
|
334 |
) |
|
335 |
), |
|
336 | ! |
value = `if`(is.null(isolate(input$display_density)), TRUE, isolate(input$display_density)), |
337 | ! |
width = "100%" |
338 |
), |
|
339 | ! |
bslib::input_switch( |
340 | ! |
id = session$ns("remove_outliers"), |
341 | ! |
label = "Remove outliers", |
342 | ! |
value = `if`(is.null(isolate(input$remove_outliers)), FALSE, isolate(input$remove_outliers)), |
343 | ! |
width = "100%" |
344 |
), |
|
345 | ! |
uiOutput(session$ns("ui_outlier_help")) |
346 |
), |
|
347 | ! |
uiOutput(session$ns("outlier_definition_slider_ui")) |
348 |
) |
|
349 |
) |
|
350 | ||
351 | ! |
observeEvent(input$numeric_as_factor, ignoreInit = TRUE, { |
352 | ! |
varname_numeric_as_factor[[plot_var$variable[[dataname]]]] <- input$numeric_as_factor |
353 |
}) |
|
354 | ||
355 | ! |
if (is.numeric(df[[varname]])) { |
356 | ! |
unique_entries <- length(unique(df[[varname]])) |
357 | ! |
if (unique_entries < .unique_records_for_factor && unique_entries > 0) { |
358 | ! |
list( |
359 | ! |
checkboxInput( |
360 | ! |
session$ns("numeric_as_factor"), |
361 | ! |
"Treat variable as factor", |
362 | ! |
value = `if`( |
363 | ! |
is.null(varname_numeric_as_factor[[varname]]), |
364 | ! |
unique_entries < .unique_records_default_as_factor, |
365 | ! |
varname_numeric_as_factor[[varname]] |
366 |
) |
|
367 |
), |
|
368 | ! |
conditionalPanel("!input.numeric_as_factor", ns = session$ns, numeric_ui) |
369 |
) |
|
370 | ! |
} else if (unique_entries > 0) { |
371 | ! |
numeric_ui |
372 |
} |
|
373 |
} else { |
|
374 | ! |
NULL |
375 |
} |
|
376 |
}) |
|
377 | ||
378 | ! |
output$ui_histogram_display <- renderUI({ |
379 | ! |
validation_checks() |
380 | ! |
dataname <- input$tabset_panel |
381 | ! |
varname <- plot_var$variable[[dataname]] |
382 | ! |
df <- data()[[dataname]] |
383 | ||
384 | ! |
numeric_ui <- bslib::input_switch( |
385 | ! |
id = session$ns("remove_NA_hist"), |
386 | ! |
label = "Remove NA values", |
387 | ! |
value = FALSE, |
388 | ! |
width = "100%" |
389 |
) |
|
390 | ||
391 | ! |
var <- df[[varname]] |
392 | ! |
if (anyNA(var) && (is.factor(var) || is.character(var) || is.logical(var))) { |
393 | ! |
groups <- unique(as.character(var)) |
394 | ! |
len_groups <- length(groups) |
395 | ! |
if (len_groups >= .unique_records_for_factor) { |
396 | ! |
NULL |
397 |
} else { |
|
398 | ! |
numeric_ui |
399 |
} |
|
400 |
} else { |
|
401 | ! |
NULL |
402 |
} |
|
403 |
}) |
|
404 | ||
405 | ! |
output$outlier_definition_slider_ui <- renderUI({ |
406 | ! |
req(input$remove_outliers) |
407 | ! |
sliderInput( |
408 | ! |
inputId = session$ns("outlier_definition_slider"), |
409 | ! |
tags$div( |
410 | ! |
tagList( |
411 | ! |
"Outlier definition:", |
412 | ! |
bslib::tooltip( |
413 | ! |
icon("circle-info"), |
414 | ! |
tags$span( |
415 | ! |
paste( |
416 | ! |
"Use the slider to choose the cut-off value to define outliers; the larger the value the", |
417 | ! |
"further below Q1/above Q3 points have to be in order to be classed as outliers" |
418 |
) |
|
419 |
) |
|
420 |
) |
|
421 |
) |
|
422 |
), |
|
423 | ! |
min = 1, |
424 | ! |
max = 5, |
425 | ! |
value = 3, |
426 | ! |
step = 0.5 |
427 |
) |
|
428 |
}) |
|
429 | ||
430 | ! |
output$ui_outlier_help <- renderUI({ |
431 | ! |
req(is.logical(input$remove_outliers), input$outlier_definition_slider) |
432 | ! |
if (input$remove_outliers) { |
433 | ! |
tags$small( |
434 | ! |
helpText( |
435 | ! |
withMathJax(paste0( |
436 | ! |
"Outlier data points (\\( X \\lt Q1 - ", input$outlier_definition_slider, "\\times IQR \\) or |
437 | ! |
\\(Q3 + ", input$outlier_definition_slider, "\\times IQR \\lt X\\)) |
438 | ! |
have not been displayed on the graph and will not be used for any kernel density estimations, ", |
439 | ! |
"although their values remain in the statisics table below." |
440 |
)) |
|
441 |
) |
|
442 |
) |
|
443 |
} else { |
|
444 | ! |
NULL |
445 |
} |
|
446 |
}) |
|
447 | ||
448 | ||
449 | ! |
variable_plot_r <- reactive({ |
450 | ! |
display_density <- `if`(is.null(input$display_density), FALSE, input$display_density) |
451 | ! |
remove_outliers <- `if`(is.null(input$remove_outliers), FALSE, input$remove_outliers) |
452 | ||
453 | ! |
if (remove_outliers) { |
454 | ! |
req(input$outlier_definition_slider) |
455 | ! |
outlier_definition <- as.numeric(input$outlier_definition_slider) |
456 |
} else { |
|
457 | ! |
outlier_definition <- 0 |
458 |
} |
|
459 | ||
460 | ! |
plot_var_summary( |
461 | ! |
var = plotted_data()$data, |
462 | ! |
var_lab = plotted_data()$var_description, |
463 | ! |
wrap_character = 15, |
464 | ! |
numeric_as_factor = treat_numeric_as_factor(), |
465 | ! |
remove_NA_hist = input$remove_NA_hist, |
466 | ! |
display_density = display_density, |
467 | ! |
outlier_definition = outlier_definition, |
468 | ! |
records_for_factor = .unique_records_for_factor, |
469 | ! |
ggplot2_args = all_ggplot2_args() |
470 |
) |
|
471 |
}) |
|
472 | ||
473 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
474 | ! |
id = "variable_plot", |
475 | ! |
plot_r = variable_plot_r, |
476 | ! |
height = c(500, 200, 2000) |
477 |
) |
|
478 | ||
479 | ! |
output$variable_summary_table <- DT::renderDataTable({ |
480 | ! |
var_summary_table( |
481 | ! |
plotted_data()$data, |
482 | ! |
treat_numeric_as_factor(), |
483 | ! |
input$variable_summary_table_rows, |
484 | ! |
if (!is.null(input$remove_outliers) && input$remove_outliers) { |
485 | ! |
req(input$outlier_definition_slider) |
486 | ! |
as.numeric(input$outlier_definition_slider) |
487 |
} else { |
|
488 | ! |
0 |
489 |
} |
|
490 |
) |
|
491 |
}) |
|
492 | ||
493 | ! |
reactive({ |
494 | ! |
validation_checks() |
495 | ! |
qenv <- teal.data::teal_data(plot = variable_plot_r()) |> teal.code::eval_code("plot") |
496 | ! |
teal.reporter::teal_card(qenv)[length(teal.reporter::teal_card(qenv))] |
497 |
}) |
|
498 |
}) |
|
499 |
} |
|
500 | ||
501 |
#' Summarize NAs. |
|
502 |
#' |
|
503 |
#' Summarizes occurrence of missing values in vector. |
|
504 |
#' @param x vector of any type and length |
|
505 |
#' @return Character string describing `NA` occurrence. |
|
506 |
#' @keywords internal |
|
507 |
var_missings_info <- function(x) { |
|
508 | ! |
sprintf("%s [%s%%]", sum(is.na(x)), round(mean(is.na(x) * 100), 2)) |
509 |
} |
|
510 | ||
511 |
#' Summarizes variable |
|
512 |
#' |
|
513 |
#' Creates html summary with statistics relevant to data type. For numeric values it returns central |
|
514 |
#' tendency measures, for factor returns level counts, for Date date range, for other just |
|
515 |
#' number of levels. |
|
516 |
#' |
|
517 |
#' @param x vector of any type |
|
518 |
#' @param numeric_as_factor `logical` should the numeric variable be treated as a factor |
|
519 |
#' @param dt_rows `numeric` current/latest `DT` page length |
|
520 |
#' @param outlier_definition If 0 no outliers are removed, otherwise |
|
521 |
#' outliers (those more than `outlier_definition*IQR below/above Q1/Q3` be removed) |
|
522 |
#' @return text with simple statistics. |
|
523 |
#' @keywords internal |
|
524 |
var_summary_table <- function(x, numeric_as_factor, dt_rows, outlier_definition) { |
|
525 | ! |
if (is.null(dt_rows)) { |
526 | ! |
dt_rows <- 10 |
527 |
} |
|
528 | ! |
if (is.numeric(x) && !numeric_as_factor) { |
529 | ! |
req(!any(is.infinite(x))) |
530 | ||
531 | ! |
x <- remove_outliers_from(x, outlier_definition) |
532 | ||
533 | ! |
qvals <- round(stats::quantile(x, na.rm = TRUE, probs = c(0.25, 0.5, 0.75), type = 2), 2) |
534 |
# classical central tendency measures |
|
535 | ||
536 | ! |
summary <- |
537 | ! |
data.frame( |
538 | ! |
Statistic = c("min", "Q1", "median", "mean", "Q3", "max", "sd", "n"), |
539 | ! |
Value = c( |
540 | ! |
round(min(x, na.rm = TRUE), 2), |
541 | ! |
qvals[1], |
542 | ! |
qvals[2], |
543 | ! |
round(mean(x, na.rm = TRUE), 2), |
544 | ! |
qvals[3], |
545 | ! |
round(max(x, na.rm = TRUE), 2), |
546 | ! |
round(stats::sd(x, na.rm = TRUE), 2), |
547 | ! |
length(x[!is.na(x)]) |
548 |
) |
|
549 |
) |
|
550 | ||
551 | ! |
DT::datatable(summary, rownames = FALSE, options = list(dom = "<t>", pageLength = dt_rows)) |
552 | ! |
} else if (is.factor(x) || is.character(x) || (is.numeric(x) && numeric_as_factor) || is.logical(x)) { |
553 |
# make sure factor is ordered numeric |
|
554 | ! |
if (is.numeric(x)) { |
555 | ! |
x <- factor(x, levels = sort(unique(x))) |
556 |
} |
|
557 | ||
558 | ! |
level_counts <- table(x) |
559 | ! |
max_levels_signif <- nchar(level_counts) |
560 | ||
561 | ! |
if (!all(is.na(x))) { |
562 | ! |
levels <- names(level_counts) |
563 | ! |
counts <- sprintf( |
564 | ! |
"%s [%.2f%%]", |
565 | ! |
format(level_counts, width = max_levels_signif), prop.table(level_counts) * 100 |
566 |
) |
|
567 |
} else { |
|
568 | ! |
levels <- character(0) |
569 | ! |
counts <- numeric(0) |
570 |
} |
|
571 | ||
572 | ! |
summary <- data.frame( |
573 | ! |
Level = levels, |
574 | ! |
Count = counts, |
575 | ! |
stringsAsFactors = FALSE |
576 |
) |
|
577 | ||
578 |
# sort the dataset in decreasing order of counts (needed as character variables default to alphabetical) |
|
579 | ! |
summary <- summary[order(summary$Count, decreasing = TRUE), ] |
580 | ||
581 | ! |
dom_opts <- if (nrow(summary) <= 10) { |
582 | ! |
"<t>" |
583 |
} else { |
|
584 | ! |
"<lf<t>ip>" |
585 |
} |
|
586 | ! |
DT::datatable(summary, rownames = FALSE, options = list(dom = dom_opts, pageLength = dt_rows)) |
587 | ! |
} else if (inherits(x, "Date") || inherits(x, "POSIXct") || inherits(x, "POSIXlt")) { |
588 | ! |
summary <- |
589 | ! |
data.frame( |
590 | ! |
Statistic = c("min", "median", "max"), |
591 | ! |
Value = c( |
592 | ! |
min(x, na.rm = TRUE), |
593 | ! |
stats::median(x, na.rm = TRUE), |
594 | ! |
max(x, na.rm = TRUE) |
595 |
) |
|
596 |
) |
|
597 | ! |
DT::datatable(summary, rownames = FALSE, options = list(dom = "<t>", pageLength = dt_rows)) |
598 |
} else { |
|
599 | ! |
NULL |
600 |
} |
|
601 |
} |
|
602 | ||
603 |
#' Plot variable |
|
604 |
#' |
|
605 |
#' Creates summary plot with statistics relevant to data type. |
|
606 |
#' |
|
607 |
#' @inheritParams shared_params |
|
608 |
#' @param var vector of any type to be plotted. For numeric variables it produces histogram with |
|
609 |
#' density line, for factors it creates frequency plot |
|
610 |
#' @param var_lab text describing selected variable to be displayed on the plot |
|
611 |
#' @param wrap_character (`numeric`) number of characters at which to wrap text values of `var` |
|
612 |
#' @param numeric_as_factor (`logical`) should the numeric variable be treated as a factor |
|
613 |
#' @param display_density (`logical`) should density estimation be displayed for numeric values |
|
614 |
#' @param remove_NA_hist (`logical`) should `NA` values be removed for histogram of factor like variables |
|
615 |
#' @param outlier_definition if 0 no outliers are removed, otherwise |
|
616 |
#' outliers (those more than outlier_definition*IQR below/above Q1/Q3 be removed) |
|
617 |
#' @param records_for_factor (`numeric`) if the number of factor levels is >= than this value then |
|
618 |
#' a graph of the factors isn't shown, only a list of values |
|
619 |
#' |
|
620 |
#' @return plot |
|
621 |
#' @keywords internal |
|
622 |
plot_var_summary <- function(var, |
|
623 |
var_lab, |
|
624 |
wrap_character = NULL, |
|
625 |
numeric_as_factor, |
|
626 |
display_density = is.numeric(var), |
|
627 |
remove_NA_hist = FALSE, # nolint: object_name. |
|
628 |
outlier_definition, |
|
629 |
records_for_factor, |
|
630 |
ggplot2_args) { |
|
631 | ! |
checkmate::assert_character(var_lab) |
632 | ! |
checkmate::assert_numeric(wrap_character, null.ok = TRUE) |
633 | ! |
checkmate::assert_flag(numeric_as_factor) |
634 | ! |
checkmate::assert_flag(display_density) |
635 | ! |
checkmate::assert_logical(remove_NA_hist, null.ok = TRUE) |
636 | ! |
checkmate::assert_number(outlier_definition, lower = 0, finite = TRUE) |
637 | ! |
checkmate::assert_integerish(records_for_factor, lower = 0, len = 1, any.missing = FALSE) |
638 | ! |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
639 | ||
640 | ! |
grid::grid.newpage() |
641 | ||
642 | ! |
plot_main <- if (is.factor(var) || is.character(var) || is.logical(var)) { |
643 | ! |
groups <- unique(as.character(var)) |
644 | ! |
len_groups <- length(groups) |
645 | ! |
if (len_groups >= records_for_factor) { |
646 | ! |
grid::textGrob( |
647 | ! |
sprintf( |
648 | ! |
"%s unique values\n%s:\n %s\n ...\n %s", |
649 | ! |
len_groups, |
650 | ! |
var_lab, |
651 | ! |
paste(utils::head(groups), collapse = ",\n "), |
652 | ! |
paste(utils::tail(groups), collapse = ",\n ") |
653 |
), |
|
654 | ! |
x = grid::unit(1, "line"), |
655 | ! |
y = grid::unit(1, "npc") - grid::unit(1, "line"), |
656 | ! |
just = c("left", "top") |
657 |
) |
|
658 |
} else { |
|
659 | ! |
if (!is.null(wrap_character)) { |
660 | ! |
var <- stringr::str_wrap(var, width = wrap_character) |
661 |
} |
|
662 | ! |
var <- if (isTRUE(remove_NA_hist)) as.vector(stats::na.omit(var)) else var |
663 | ! |
ggplot2::ggplot(data.frame(var), ggplot2::aes(x = forcats::fct_infreq(as.factor(var)))) + |
664 | ! |
ggplot2::geom_bar( |
665 | ! |
stat = "count", ggplot2::aes(fill = ifelse(is.na(var), "withcolor", "")), show.legend = FALSE |
666 |
) + |
|
667 | ! |
ggplot2::scale_fill_manual(values = c("gray50", "tan")) |
668 |
} |
|
669 | ! |
} else if (is.numeric(var)) { |
670 | ! |
validate(need(any(!is.na(var)), "No data left to visualize.")) |
671 | ||
672 |
# Filter out NA |
|
673 | ! |
var <- var[which(!is.na(var))] |
674 | ||
675 | ! |
validate(need(!any(is.infinite(var)), "Cannot display graph when data includes infinite values")) |
676 | ||
677 | ! |
if (numeric_as_factor) { |
678 | ! |
var <- factor(var) |
679 | ! |
ggplot2::ggplot(NULL, ggplot2::aes(x = var)) + |
680 | ! |
ggplot2::geom_histogram(stat = "count") |
681 |
} else { |
|
682 |
# remove outliers |
|
683 | ! |
if (outlier_definition != 0) { |
684 | ! |
number_records <- length(var) |
685 | ! |
var <- remove_outliers_from(var, outlier_definition) |
686 | ! |
number_outliers <- number_records - length(var) |
687 | ! |
outlier_text <- paste0( |
688 | ! |
number_outliers, " outliers (", |
689 | ! |
round(number_outliers / number_records * 100, 2), |
690 | ! |
"% of non-missing records) not shown" |
691 |
) |
|
692 | ! |
validate(need( |
693 | ! |
length(var) > 1, |
694 | ! |
"At least two data points must remain after removing outliers for this graph to be displayed" |
695 |
)) |
|
696 |
} |
|
697 |
## histogram |
|
698 | ! |
binwidth <- get_bin_width(var) |
699 | ! |
p <- ggplot2::ggplot(data = data.frame(var = var), ggplot2::aes(x = var, y = ggplot2::after_stat(count))) + |
700 | ! |
ggplot2::geom_histogram(binwidth = binwidth) + |
701 | ! |
ggplot2::scale_y_continuous( |
702 | ! |
sec.axis = ggplot2::sec_axis( |
703 | ! |
trans = ~ . / nrow(data.frame(var = var)), |
704 | ! |
labels = scales::percent, |
705 | ! |
name = "proportion (in %)" |
706 |
) |
|
707 |
) |
|
708 | ||
709 | ! |
if (display_density) { |
710 | ! |
p <- p + ggplot2::geom_density(ggplot2::aes(y = ggplot2::after_stat(count * binwidth))) |
711 |
} |
|
712 | ||
713 | ! |
if (outlier_definition != 0) { |
714 | ! |
p <- p + ggplot2::annotate( |
715 | ! |
geom = "text", |
716 | ! |
label = outlier_text, |
717 | ! |
x = Inf, y = Inf, |
718 | ! |
hjust = 1.02, vjust = 1.2, |
719 | ! |
color = "black", |
720 |
# explicitly modify geom text size according |
|
721 | ! |
size = ggplot2_args[["theme"]][["text"]][["size"]] / 3.5 |
722 |
) |
|
723 |
} |
|
724 | ! |
p |
725 |
} |
|
726 | ! |
} else if (inherits(var, "Date") || inherits(var, "POSIXct") || inherits(var, "POSIXlt")) { |
727 | ! |
var_num <- as.numeric(var) |
728 | ! |
binwidth <- get_bin_width(var_num, 1) |
729 | ! |
p <- ggplot2::ggplot(data = data.frame(var = var), ggplot2::aes(x = var, y = ggplot2::after_stat(count))) + |
730 | ! |
ggplot2::geom_histogram(binwidth = binwidth) |
731 |
} else { |
|
732 | ! |
grid::textGrob( |
733 | ! |
paste(strwrap( |
734 | ! |
utils::capture.output(utils::str(var)), |
735 | ! |
width = .9 * grid::convertWidth(grid::unit(1, "npc"), "char", TRUE) |
736 | ! |
), collapse = "\n"), |
737 | ! |
x = grid::unit(1, "line"), y = grid::unit(1, "npc") - grid::unit(1, "line"), just = c("left", "top") |
738 |
) |
|
739 |
} |
|
740 | ||
741 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
742 | ! |
labs = list(x = var_lab) |
743 |
) |
|
744 |
### |
|
745 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
746 | ! |
ggplot2_args, |
747 | ! |
module_plot = dev_ggplot2_args |
748 |
) |
|
749 | ||
750 | ! |
if (is.ggplot(plot_main)) { |
751 | ! |
if (is.numeric(var) && !numeric_as_factor) { |
752 |
# numeric not as factor |
|
753 | ! |
plot_main <- plot_main + |
754 | ! |
theme_light() + |
755 | ! |
list( |
756 | ! |
labs = do.call("labs", all_ggplot2_args$labs), |
757 | ! |
theme = do.call("theme", all_ggplot2_args$theme) |
758 |
) |
|
759 |
} else { |
|
760 |
# factor low number of levels OR numeric as factor OR Date |
|
761 | ! |
plot_main <- plot_main + |
762 | ! |
theme_light() + |
763 | ! |
list( |
764 | ! |
labs = do.call("labs", all_ggplot2_args$labs), |
765 | ! |
theme = do.call("theme", all_ggplot2_args$theme) |
766 |
) |
|
767 |
} |
|
768 | ! |
plot_main <- ggplot2::ggplotGrob(plot_main) |
769 |
} |
|
770 | ||
771 | ! |
grid::grid.draw(plot_main) |
772 | ! |
plot_main |
773 |
} |
|
774 | ||
775 |
is_num_var_short <- function(.unique_records_for_factor, input, data_for_analysis) { |
|
776 | ! |
length(unique(data_for_analysis()$data)) < .unique_records_for_factor && !is.null(input$numeric_as_factor) |
777 |
} |
|
778 | ||
779 |
#' Validates the variable browser inputs |
|
780 |
#' |
|
781 |
#' @param input (`session$input`) the `shiny` session input |
|
782 |
#' @param plot_var (`list`) list of a data frame and an array of variable names |
|
783 |
#' @param data (`teal_data`) the datasets passed to the module |
|
784 |
#' |
|
785 |
#' @returns `logical` TRUE if validations pass; a `shiny` validation error otherwise |
|
786 |
#' @keywords internal |
|
787 |
validate_input <- function(input, plot_var, data) { |
|
788 | ! |
reactive({ |
789 | ! |
dataset_name <- req(input$tabset_panel) |
790 | ! |
varname <- plot_var$variable[[dataset_name]] |
791 | ||
792 | ! |
validate(need(dataset_name, "No data selected")) |
793 | ! |
validate(need(varname, "No variable selected")) |
794 | ! |
df <- data()[[dataset_name]] |
795 | ! |
teal::validate_has_data(df, 1) |
796 | ! |
teal::validate_has_variable(varname = varname, data = df, "Variable not available") |
797 | ||
798 | ! |
TRUE |
799 |
}) |
|
800 |
} |
|
801 | ||
802 |
get_plotted_data <- function(input, plot_var, data) { |
|
803 | ! |
dataset_name <- input$tabset_panel |
804 | ! |
varname <- plot_var$variable[[dataset_name]] |
805 | ! |
df <- data()[[dataset_name]] |
806 | ||
807 | ! |
var_description <- teal.data::col_labels(df)[[varname]] |
808 | ! |
list(data = df[[varname]], var_description = var_description) |
809 |
} |
|
810 | ||
811 |
#' Renders the left-hand side `tabset` panel of the module |
|
812 |
#' |
|
813 |
#' @param datanames (`character`) the name of the dataset |
|
814 |
#' @param parent_dataname (`character`) the name of a parent `dataname` to filter out variables from |
|
815 |
#' @param data (`teal_data`) the object containing all datasets |
|
816 |
#' @param input (`session$input`) the `shiny` session input |
|
817 |
#' @param output (`session$output`) the `shiny` session output |
|
818 |
#' @param columns_names (`environment`) the environment containing bindings for each dataset |
|
819 |
#' @param plot_var (`list`) the list containing the currently selected dataset (tab) and its column names |
|
820 |
#' @keywords internal |
|
821 |
render_tabset_panel_content <- function(datanames, parent_dataname, output, data, input, columns_names, plot_var) { |
|
822 | ! |
lapply(datanames, render_single_tab, |
823 | ! |
input = input, |
824 | ! |
output = output, |
825 | ! |
data = data, |
826 | ! |
parent_dataname = parent_dataname, |
827 | ! |
columns_names = columns_names, |
828 | ! |
plot_var = plot_var |
829 |
) |
|
830 |
} |
|
831 | ||
832 |
#' Renders a single tab in the left-hand side tabset panel |
|
833 |
#' |
|
834 |
#' Renders a single tab in the left-hand side tabset panel. The rendered tab contains |
|
835 |
#' information about one dataset out of many presented in the module. |
|
836 |
#' |
|
837 |
#' @param dataset_name (`character`) the name of the dataset contained in the rendered tab |
|
838 |
#' @param parent_dataname (`character`) the name of a parent `dataname` to filter out variables from |
|
839 |
#' @inheritParams render_tabset_panel_content |
|
840 |
#' @keywords internal |
|
841 |
render_single_tab <- function(dataset_name, parent_dataname, output, data, input, columns_names, plot_var) { |
|
842 | ! |
render_tab_header(dataset_name, output, data) |
843 | ||
844 | ! |
render_tab_table( |
845 | ! |
dataset_name = dataset_name, |
846 | ! |
parent_dataname = parent_dataname, |
847 | ! |
output = output, |
848 | ! |
data = data, |
849 | ! |
input = input, |
850 | ! |
columns_names = columns_names, |
851 | ! |
plot_var = plot_var |
852 |
) |
|
853 |
} |
|
854 | ||
855 |
#' Renders the text headlining a single tab in the left-hand side tabset panel |
|
856 |
#' |
|
857 |
#' @param dataset_name (`character`) the name of the dataset of the tab |
|
858 |
#' @inheritParams render_tabset_panel_content |
|
859 |
#' @keywords internal |
|
860 |
render_tab_header <- function(dataset_name, output, data) { |
|
861 | ! |
dataset_ui_id <- paste0("dataset_summary_", dataset_name) |
862 | ! |
output[[dataset_ui_id]] <- renderText({ |
863 | ! |
df <- data()[[dataset_name]] |
864 | ! |
join_keys <- teal.data::join_keys(data()) |
865 | ! |
if (!is.null(join_keys)) { |
866 | ! |
key <- teal.data::join_keys(data())[dataset_name, dataset_name] |
867 |
} else { |
|
868 | ! |
key <- NULL |
869 |
} |
|
870 | ! |
sprintf( |
871 | ! |
"Dataset with %s unique key rows and %s variables", |
872 | ! |
nrow(unique(`if`(length(key) > 0, df[, key, drop = FALSE], df))), |
873 | ! |
ncol(df) |
874 |
) |
|
875 |
}) |
|
876 |
} |
|
877 | ||
878 |
#' Renders the table for a single dataset in the left-hand side tabset panel |
|
879 |
#' |
|
880 |
#' The table contains column names, column labels, |
|
881 |
#' small summary about NA values and `sparkline` (if appropriate). |
|
882 |
#' |
|
883 |
#' @param dataset_name (`character`) the name of the dataset |
|
884 |
#' @param parent_dataname (`character`) the name of a parent `dataname` to filter out variables from |
|
885 |
#' @inheritParams render_tabset_panel_content |
|
886 |
#' @keywords internal |
|
887 |
render_tab_table <- function(dataset_name, parent_dataname, output, data, input, columns_names, plot_var) { |
|
888 | ! |
table_ui_id <- paste0("variable_browser_", dataset_name) |
889 | ||
890 | ! |
output[[table_ui_id]] <- DT::renderDataTable({ |
891 | ! |
df <- data()[[dataset_name]] |
892 | ||
893 | ! |
get_vars_df <- function(input, dataset_name, parent_name, data) { |
894 | ! |
data_cols <- colnames(df) |
895 | ! |
if (isTRUE(input$show_parent_vars)) { |
896 | ! |
data_cols |
897 | ! |
} else if (dataset_name != parent_name && parent_name %in% names(data)) { |
898 | ! |
setdiff(data_cols, colnames(data()[[parent_name]])) |
899 |
} else { |
|
900 | ! |
data_cols |
901 |
} |
|
902 |
} |
|
903 | ||
904 | ! |
if (length(parent_dataname) > 0) { |
905 | ! |
df_vars <- get_vars_df(input, dataset_name, parent_dataname, data) |
906 | ! |
df <- df[df_vars] |
907 |
} |
|
908 | ||
909 | ! |
if (is.null(df) || ncol(df) == 0) { |
910 | ! |
columns_names[[dataset_name]] <- character(0) |
911 | ! |
df_output <- data.frame( |
912 | ! |
Type = character(0), |
913 | ! |
Variable = character(0), |
914 | ! |
Label = character(0), |
915 | ! |
Missings = character(0), |
916 | ! |
Sparklines = character(0), |
917 | ! |
stringsAsFactors = FALSE |
918 |
) |
|
919 |
} else { |
|
920 |
# extract data variable labels |
|
921 | ! |
labels <- teal.data::col_labels(df) |
922 | ||
923 | ! |
columns_names[[dataset_name]] <- names(labels) |
924 | ||
925 |
# calculate number of missing values |
|
926 | ! |
missings <- vapply( |
927 | ! |
df, |
928 | ! |
var_missings_info, |
929 | ! |
FUN.VALUE = character(1), |
930 | ! |
USE.NAMES = FALSE |
931 |
) |
|
932 | ||
933 |
# get icons proper for the data types |
|
934 | ! |
icons <- vapply(df, function(x) class(x)[1L], character(1L)) |
935 | ||
936 | ! |
join_keys <- teal.data::join_keys(data()) |
937 | ! |
if (!is.null(join_keys)) { |
938 | ! |
icons[intersect(join_keys[dataset_name, dataset_name], colnames(df))] <- "primary_key" |
939 |
} |
|
940 | ! |
icons <- variable_type_icons(icons) |
941 | ||
942 |
# generate sparklines |
|
943 | ! |
sparklines_html <- vapply( |
944 | ! |
df, |
945 | ! |
create_sparklines, |
946 | ! |
FUN.VALUE = character(1), |
947 | ! |
USE.NAMES = FALSE |
948 |
) |
|
949 | ||
950 | ! |
df_output <- data.frame( |
951 | ! |
Type = icons, |
952 | ! |
Variable = names(labels), |
953 | ! |
Label = labels, |
954 | ! |
Missings = missings, |
955 | ! |
Sparklines = sparklines_html, |
956 | ! |
stringsAsFactors = FALSE |
957 |
) |
|
958 |
} |
|
959 | ||
960 |
# Select row 1 as default / fallback |
|
961 | ! |
selected_ix <- 1 |
962 |
# Define starting page index (base-0 index of the first item on page |
|
963 |
# note: in many cases it's not the item itself |
|
964 | ! |
selected_page_ix <- 0 |
965 | ||
966 |
# Retrieve current selected variable if any |
|
967 | ! |
isolated_variable <- isolate(plot_var$variable[[dataset_name]]) |
968 | ||
969 | ! |
if (!is.null(isolated_variable)) { |
970 | ! |
index <- which(columns_names[[dataset_name]] == isolated_variable)[1] |
971 | ! |
if (!is.null(index) && !is.na(index) && length(index) > 0) selected_ix <- index |
972 |
} |
|
973 | ||
974 |
# Retrieve the index of the first item of the current page |
|
975 |
# it works with varying number of entries on the page (10, 25, ...) |
|
976 | ! |
table_id_sel <- paste0("variable_browser_", dataset_name, "_state") |
977 | ! |
dt_state <- isolate(input[[table_id_sel]]) |
978 | ! |
if (selected_ix != 1 && !is.null(dt_state)) { |
979 | ! |
selected_page_ix <- floor(selected_ix / dt_state$length) * dt_state$length |
980 |
} |
|
981 | ||
982 | ! |
DT::datatable( |
983 | ! |
df_output, |
984 | ! |
escape = FALSE, |
985 | ! |
rownames = FALSE, |
986 | ! |
selection = list(mode = "single", target = "row", selected = selected_ix), |
987 | ! |
options = list( |
988 | ! |
fnDrawCallback = htmlwidgets::JS("function() { HTMLWidgets.staticRender(); }"), |
989 | ! |
pageLength = input[[paste0(table_ui_id, "_rows")]], |
990 | ! |
displayStart = selected_page_ix |
991 |
) |
|
992 |
) |
|
993 |
}) |
|
994 |
} |
|
995 | ||
996 |
#' Creates observers updating the currently selected column |
|
997 |
#' |
|
998 |
#' The created observers update the column currently selected in the left-hand side |
|
999 |
#' tabset panel. |
|
1000 |
#' |
|
1001 |
#' @note |
|
1002 |
#' Creates an observer for each dataset (each tab in the tabset panel). |
|
1003 |
#' |
|
1004 |
#' @inheritParams render_tabset_panel_content |
|
1005 |
#' @keywords internal |
|
1006 |
establish_updating_selection <- function(datanames, input, plot_var, columns_names) { |
|
1007 | ! |
lapply(datanames, function(dataset_name) { |
1008 | ! |
table_ui_id <- paste0("variable_browser_", dataset_name) |
1009 | ! |
table_id_sel <- paste0(table_ui_id, "_rows_selected") |
1010 | ! |
observeEvent(input[[table_id_sel]], { |
1011 | ! |
plot_var$data <- dataset_name |
1012 | ! |
plot_var$variable[[dataset_name]] <- columns_names[[dataset_name]][input[[table_id_sel]]] |
1013 |
}) |
|
1014 |
}) |
|
1015 |
} |
|
1016 | ||
1017 |
get_bin_width <- function(x_vec, scaling_factor = 2) { |
|
1018 | ! |
x_vec <- x_vec[!is.na(x_vec)] |
1019 | ! |
qntls <- stats::quantile(x_vec, probs = c(0.1, 0.25, 0.75, 0.9), type = 2) |
1020 | ! |
iqr <- qntls[3] - qntls[2] |
1021 | ! |
binwidth <- max(scaling_factor * iqr / length(x_vec) ^ (1 / 3), sqrt(qntls[4] - qntls[1])) # styler: off |
1022 | ! |
binwidth <- ifelse(binwidth == 0, 1, binwidth) |
1023 |
# to ensure at least two bins when variable span is very small |
|
1024 | ! |
x_span <- diff(range(x_vec)) |
1025 | ! |
if (isTRUE(x_span / binwidth >= 2)) binwidth else x_span / 2 |
1026 |
} |
|
1027 | ||
1028 |
#' Removes the outlier observation from an array |
|
1029 |
#' |
|
1030 |
#' @param var (`numeric`) a numeric vector |
|
1031 |
#' @param outlier_definition (`numeric`) if `0` then no outliers are removed, otherwise |
|
1032 |
#' outliers (those more than `outlier_definition*IQR below/above Q1/Q3`) are removed |
|
1033 |
#' @returns (`numeric`) vector without the outlier values |
|
1034 |
#' @keywords internal |
|
1035 |
remove_outliers_from <- function(var, outlier_definition) { |
|
1036 | 3x |
if (outlier_definition == 0) { |
1037 | 1x |
return(var) |
1038 |
} |
|
1039 | 2x |
q1_q3 <- stats::quantile(var, probs = c(0.25, 0.75), type = 2, na.rm = TRUE) |
1040 | 2x |
iqr <- q1_q3[2] - q1_q3[1] |
1041 | 2x |
var[var >= q1_q3[1] - outlier_definition * iqr & var <= q1_q3[2] + outlier_definition * iqr] |
1042 |
} |
|
1043 | ||
1044 | ||
1045 |
# sparklines ---- |
|
1046 | ||
1047 |
#' S3 generic for `sparkline` widget HTML |
|
1048 |
#' |
|
1049 |
#' Generates the `sparkline` HTML code corresponding to the input array. |
|
1050 |
#' For numeric variables creates a box plot, for character and factors - bar plot. |
|
1051 |
#' Produces an empty string for variables of other types. |
|
1052 |
#' |
|
1053 |
#' @param arr vector of any type and length |
|
1054 |
#' @param width `numeric` the width of the `sparkline` widget (pixels) |
|
1055 |
#' @param bar_spacing `numeric` the spacing between the bars (in pixels) |
|
1056 |
#' @param bar_width `numeric` the width of the bars (in pixels) |
|
1057 |
#' @param ... `list` additional options passed to bar plots of `jquery.sparkline`; |
|
1058 |
#' see [`jquery.sparkline docs`](https://omnipotent.net/jquery.sparkline/#common) |
|
1059 |
#' |
|
1060 |
#' @return Character string containing HTML code of the `sparkline` HTML widget. |
|
1061 |
#' @keywords internal |
|
1062 |
create_sparklines <- function(arr, width = 150, ...) { |
|
1063 | ! |
if (all(is.null(arr))) { |
1064 | ! |
return("") |
1065 |
} |
|
1066 | ! |
UseMethod("create_sparklines") |
1067 |
} |
|
1068 | ||
1069 |
#' @rdname create_sparklines |
|
1070 |
#' @keywords internal |
|
1071 |
#' @export |
|
1072 |
create_sparklines.logical <- function(arr, ...) { |
|
1073 | ! |
create_sparklines(as.factor(arr)) |
1074 |
} |
|
1075 | ||
1076 |
#' @rdname create_sparklines |
|
1077 |
#' @keywords internal |
|
1078 |
#' @export |
|
1079 |
create_sparklines.numeric <- function(arr, width = 150, ...) { |
|
1080 | ! |
if (any(is.infinite(arr))) { |
1081 | ! |
return(as.character(tags$code("infinite values", class = "text-blue"))) |
1082 |
} |
|
1083 | ! |
if (length(arr) > 100000) { |
1084 | ! |
return(as.character(tags$code("Too many rows (>100000)", class = "text-blue"))) |
1085 |
} |
|
1086 | ||
1087 | ! |
arr <- arr[!is.na(arr)] |
1088 | ! |
sparkline::spk_chr(unname(arr), type = "box", width = width, ...) |
1089 |
} |
|
1090 | ||
1091 |
#' @rdname create_sparklines |
|
1092 |
#' @keywords internal |
|
1093 |
#' @export |
|
1094 |
create_sparklines.character <- function(arr, ...) { |
|
1095 | ! |
create_sparklines(as.factor(arr)) |
1096 |
} |
|
1097 | ||
1098 | ||
1099 |
#' @rdname create_sparklines |
|
1100 |
#' @keywords internal |
|
1101 |
#' @export |
|
1102 |
create_sparklines.factor <- function(arr, width = 150, bar_spacing = 5, bar_width = 20, ...) { |
|
1103 | ! |
decreasing_order <- TRUE |
1104 | ||
1105 | ! |
counts <- table(arr) |
1106 | ! |
if (length(counts) >= 100) { |
1107 | ! |
return(as.character(tags$code("> 99 levels", class = "text-blue"))) |
1108 | ! |
} else if (length(counts) == 0) { |
1109 | ! |
return(as.character(tags$code("no levels", class = "text-blue"))) |
1110 | ! |
} else if (length(counts) == 1) { |
1111 | ! |
return(as.character(tags$code("one level", class = "text-blue"))) |
1112 |
} |
|
1113 | ||
1114 |
# Summarize the occurences of different levels |
|
1115 |
# and get the maximum and minimum number of occurences |
|
1116 |
# This is needed for the sparkline to correctly display the bar plots |
|
1117 |
# Otherwise they are cropped |
|
1118 | ! |
counts <- sort(counts, decreasing = decreasing_order, method = "radix") |
1119 | ! |
max_value <- if (decreasing_order) counts[1] else counts[length[counts]] |
1120 | ! |
max_value <- unname(max_value) |
1121 | ||
1122 | ! |
sparkline::spk_chr( |
1123 | ! |
unname(counts), |
1124 | ! |
type = "bar", |
1125 | ! |
chartRangeMin = 0, |
1126 | ! |
chartRangeMax = max_value, |
1127 | ! |
width = width, |
1128 | ! |
barWidth = bar_width, |
1129 | ! |
barSpacing = bar_spacing, |
1130 | ! |
tooltipFormatter = custom_sparkline_formatter(names(counts), as.vector(counts)) |
1131 |
) |
|
1132 |
} |
|
1133 | ||
1134 |
#' @rdname create_sparklines |
|
1135 |
#' @keywords internal |
|
1136 |
#' @export |
|
1137 |
create_sparklines.Date <- function(arr, width = 150, bar_spacing = 5, bar_width = 20, ...) { |
|
1138 | ! |
arr_num <- as.numeric(arr) |
1139 | ! |
arr_num <- sort(arr_num, decreasing = FALSE, method = "radix") |
1140 | ! |
binwidth <- get_bin_width(arr_num, 1) |
1141 | ! |
bins <- floor(diff(range(arr_num)) / binwidth) + 1 |
1142 | ! |
if (all(is.na(bins))) { |
1143 | ! |
return(as.character(tags$code("only NA", class = "text-blue"))) |
1144 | ! |
} else if (bins == 1) { |
1145 | ! |
return(as.character(tags$code("one date", class = "text-blue"))) |
1146 |
} |
|
1147 | ! |
counts <- as.vector(unname(base::table(cut(arr_num, breaks = bins)))) |
1148 | ! |
max_value <- max(counts) |
1149 | ||
1150 | ! |
start_bins <- as.integer(seq(1, length(arr_num), length.out = bins)) |
1151 | ! |
labels_start <- as.character(as.Date(arr_num[start_bins], origin = as.Date("1970-01-01"))) |
1152 | ! |
labels <- paste("Start:", labels_start) |
1153 | ||
1154 | ! |
sparkline::spk_chr( |
1155 | ! |
unname(counts), |
1156 | ! |
type = "bar", |
1157 | ! |
chartRangeMin = 0, |
1158 | ! |
chartRangeMax = max_value, |
1159 | ! |
width = width, |
1160 | ! |
barWidth = bar_width, |
1161 | ! |
barSpacing = bar_spacing, |
1162 | ! |
tooltipFormatter = custom_sparkline_formatter(labels, counts) |
1163 |
) |
|
1164 |
} |
|
1165 | ||
1166 |
#' @rdname create_sparklines |
|
1167 |
#' @keywords internal |
|
1168 |
#' @export |
|
1169 |
create_sparklines.POSIXct <- function(arr, width = 150, bar_spacing = 5, bar_width = 20, ...) { |
|
1170 | ! |
arr_num <- as.numeric(arr) |
1171 | ! |
arr_num <- sort(arr_num, decreasing = FALSE, method = "radix") |
1172 | ! |
binwidth <- get_bin_width(arr_num, 1) |
1173 | ! |
bins <- floor(diff(range(arr_num)) / binwidth) + 1 |
1174 | ! |
if (all(is.na(bins))) { |
1175 | ! |
return(as.character(tags$code("only NA", class = "text-blue"))) |
1176 | ! |
} else if (bins == 1) { |
1177 | ! |
return(as.character(tags$code("one date-time", class = "text-blue"))) |
1178 |
} |
|
1179 | ! |
counts <- as.vector(unname(base::table(cut(arr_num, breaks = bins)))) |
1180 | ! |
max_value <- max(counts) |
1181 | ||
1182 | ! |
start_bins <- as.integer(seq(1, length(arr_num), length.out = bins)) |
1183 | ! |
labels_start <- as.character(format(as.POSIXct(arr_num[start_bins], origin = as.Date("1970-01-01")), "%Y-%m-%d")) |
1184 | ! |
labels <- paste("Start:", labels_start) |
1185 | ||
1186 | ! |
sparkline::spk_chr( |
1187 | ! |
unname(counts), |
1188 | ! |
type = "bar", |
1189 | ! |
chartRangeMin = 0, |
1190 | ! |
chartRangeMax = max_value, |
1191 | ! |
width = width, |
1192 | ! |
barWidth = bar_width, |
1193 | ! |
barSpacing = bar_spacing, |
1194 | ! |
tooltipFormatter = custom_sparkline_formatter(labels, counts) |
1195 |
) |
|
1196 |
} |
|
1197 | ||
1198 |
#' @rdname create_sparklines |
|
1199 |
#' @keywords internal |
|
1200 |
#' @export |
|
1201 |
create_sparklines.POSIXlt <- function(arr, width = 150, bar_spacing = 5, bar_width = 20, ...) { |
|
1202 | ! |
arr_num <- as.numeric(arr) |
1203 | ! |
arr_num <- sort(arr_num, decreasing = FALSE, method = "radix") |
1204 | ! |
binwidth <- get_bin_width(arr_num, 1) |
1205 | ! |
bins <- floor(diff(range(arr_num)) / binwidth) + 1 |
1206 | ! |
if (all(is.na(bins))) { |
1207 | ! |
return(as.character(tags$code("only NA", class = "text-blue"))) |
1208 | ! |
} else if (bins == 1) { |
1209 | ! |
return(as.character(tags$code("one date-time", class = "text-blue"))) |
1210 |
} |
|
1211 | ! |
counts <- as.vector(unname(base::table(cut(arr_num, breaks = bins)))) |
1212 | ! |
max_value <- max(counts) |
1213 | ||
1214 | ! |
start_bins <- as.integer(seq(1, length(arr_num), length.out = bins)) |
1215 | ! |
labels_start <- as.character(format(as.POSIXct(arr_num[start_bins], origin = as.Date("1970-01-01")), "%Y-%m-%d")) |
1216 | ! |
labels <- paste("Start:", labels_start) |
1217 | ||
1218 | ! |
sparkline::spk_chr( |
1219 | ! |
unname(counts), |
1220 | ! |
type = "bar", |
1221 | ! |
chartRangeMin = 0, |
1222 | ! |
chartRangeMax = max_value, |
1223 | ! |
width = width, |
1224 | ! |
barWidth = bar_width, |
1225 | ! |
barSpacing = bar_spacing, |
1226 | ! |
tooltipFormatter = custom_sparkline_formatter(labels, counts) |
1227 |
) |
|
1228 |
} |
|
1229 | ||
1230 |
#' @rdname create_sparklines |
|
1231 |
#' @keywords internal |
|
1232 |
#' @export |
|
1233 |
create_sparklines.default <- function(arr, width = 150, ...) { |
|
1234 | ! |
as.character(tags$code("unsupported variable type", class = "text-blue")) |
1235 |
} |
|
1236 | ||
1237 |
custom_sparkline_formatter <- function(labels, counts) { |
|
1238 | ! |
htmlwidgets::JS( |
1239 | ! |
sprintf( |
1240 | ! |
"function(sparkline, options, field) { |
1241 | ! |
return 'ID: ' + %s[field[0].offset] + '<br>' + 'Count: ' + %s[field[0].offset]; |
1242 |
}", |
|
1243 | ! |
jsonlite::toJSON(labels), |
1244 | ! |
jsonlite::toJSON(counts) |
1245 |
) |
|
1246 |
) |
|
1247 |
} |
1 |
#' `teal` module: Missing data analysis |
|
2 |
#' |
|
3 |
#' This module analyzes missing data in `data.frame`s to help users explore missing observations and |
|
4 |
#' gain insights into the completeness of their data. |
|
5 |
#' It is useful for clinical data analysis within the context of `CDISC` standards and |
|
6 |
#' adaptable for general data analysis purposes. |
|
7 |
#' |
|
8 |
#' @inheritParams teal::module |
|
9 |
#' @inheritParams shared_params |
|
10 |
#' @param parent_dataname (`character(1)`) Specifies the parent dataset name. Default is `ADSL` for `CDISC` data. |
|
11 |
#' If provided and exists, enables additional analysis "by subject". For non-`CDISC` data, this parameter can be |
|
12 |
#' ignored. |
|
13 |
# nolint start: line_length. |
|
14 |
#' @param ggtheme (`character`) optional, specifies the default `ggplot2` theme for plots. Defaults to `classic`. |
|
15 |
#' @param ggplot2_args `r roxygen_ggplot2_args_param("Summary Obs", "Summary Patients", "Combinations Main", "Combinations Hist", "By Subject")` |
|
16 |
# nolint end: line_length. |
|
17 |
#' |
|
18 |
#' @inherit shared_params return |
|
19 |
#' |
|
20 |
#' @section Decorating Module: |
|
21 |
#' |
|
22 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
23 |
#' - `summary_plot` (`ggplot`) |
|
24 |
#' - `combination_plot` (`grob` created with [ggplot2::ggplotGrob()]) |
|
25 |
#' - `by_subject_plot` (`ggplot`) |
|
26 |
#' |
|
27 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
28 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
29 |
#' See code snippet below: |
|
30 |
#' |
|
31 |
#' ``` |
|
32 |
#' tm_missing_data( |
|
33 |
#' ..., # arguments for module |
|
34 |
#' decorators = list( |
|
35 |
#' summary_plot = teal_transform_module(...), # applied only to `summary_plot` output |
|
36 |
#' combination_plot = teal_transform_module(...), # applied only to `combination_plot` output |
|
37 |
#' by_subject_plot = teal_transform_module(...) # applied only to `by_subject_plot` output |
|
38 |
#' ) |
|
39 |
#' ) |
|
40 |
#' ``` |
|
41 |
#' |
|
42 |
#' For additional details and examples of decorators, refer to the vignette |
|
43 |
#' `vignette("decorate-module-output", package = "teal.modules.general")`. |
|
44 |
#' |
|
45 |
#' To learn more please refer to the vignette |
|
46 |
#' `vignette("transform-module-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
47 |
#' |
|
48 |
#' @inheritSection teal::example_module Reporting |
|
49 |
#' |
|
50 |
#' @examplesShinylive |
|
51 |
#' library(teal.modules.general) |
|
52 |
#' interactive <- function() TRUE |
|
53 |
#' {{ next_example }} |
|
54 |
#' @examples |
|
55 |
#' # general example data |
|
56 |
#' data <- teal_data() |
|
57 |
#' data <- within(data, { |
|
58 |
#' require(nestcolor) |
|
59 |
#' |
|
60 |
#' add_nas <- function(x) { |
|
61 |
#' x[sample(seq_along(x), floor(length(x) * runif(1, .05, .17)))] <- NA |
|
62 |
#' x |
|
63 |
#' } |
|
64 |
#' |
|
65 |
#' iris <- iris |
|
66 |
#' mtcars <- mtcars |
|
67 |
#' |
|
68 |
#' iris[] <- lapply(iris, add_nas) |
|
69 |
#' mtcars[] <- lapply(mtcars, add_nas) |
|
70 |
#' mtcars[["cyl"]] <- as.factor(mtcars[["cyl"]]) |
|
71 |
#' mtcars[["gear"]] <- as.factor(mtcars[["gear"]]) |
|
72 |
#' }) |
|
73 |
#' |
|
74 |
#' app <- init( |
|
75 |
#' data = data, |
|
76 |
#' modules = modules( |
|
77 |
#' tm_missing_data(parent_dataname = "mtcars") |
|
78 |
#' ) |
|
79 |
#' ) |
|
80 |
#' if (interactive()) { |
|
81 |
#' shinyApp(app$ui, app$server) |
|
82 |
#' } |
|
83 |
#' |
|
84 |
#' @examplesShinylive |
|
85 |
#' library(teal.modules.general) |
|
86 |
#' interactive <- function() TRUE |
|
87 |
#' {{ next_example }} |
|
88 |
#' @examples |
|
89 |
#' # CDISC example data |
|
90 |
#' data <- teal_data() |
|
91 |
#' data <- within(data, { |
|
92 |
#' require(nestcolor) |
|
93 |
#' ADSL <- teal.data::rADSL |
|
94 |
#' ADRS <- rADRS |
|
95 |
#' }) |
|
96 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
97 |
#' |
|
98 |
#' app <- init( |
|
99 |
#' data = data, |
|
100 |
#' modules = modules( |
|
101 |
#' tm_missing_data() |
|
102 |
#' ) |
|
103 |
#' ) |
|
104 |
#' if (interactive()) { |
|
105 |
#' shinyApp(app$ui, app$server) |
|
106 |
#' } |
|
107 |
#' |
|
108 |
#' @export |
|
109 |
#' |
|
110 |
tm_missing_data <- function(label = "Missing data", |
|
111 |
plot_height = c(600, 400, 5000), |
|
112 |
plot_width = NULL, |
|
113 |
datanames = "all", |
|
114 |
parent_dataname = "ADSL", |
|
115 |
ggtheme = c("classic", "gray", "bw", "linedraw", "light", "dark", "minimal", "void"), |
|
116 |
ggplot2_args = list( |
|
117 |
"Combinations Hist" = teal.widgets::ggplot2_args(labs = list(caption = NULL)), |
|
118 |
"Combinations Main" = teal.widgets::ggplot2_args(labs = list(title = NULL)) |
|
119 |
), |
|
120 |
pre_output = NULL, |
|
121 |
post_output = NULL, |
|
122 |
transformators = list(), |
|
123 |
decorators = list()) { |
|
124 | ! |
message("Initializing tm_missing_data") |
125 | ||
126 |
# Normalize the parameters |
|
127 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
128 | ||
129 |
# Start of assertions |
|
130 | ! |
checkmate::assert_string(label) |
131 | ||
132 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
133 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
134 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
135 | ! |
checkmate::assert_numeric( |
136 | ! |
plot_width[1], |
137 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
138 |
) |
|
139 | ||
140 | ! |
checkmate::assert_character(datanames, min.len = 0, min.chars = 1, null.ok = TRUE) |
141 | ! |
checkmate::assert_character(parent_dataname, min.len = 0, max.len = 1) |
142 | ! |
ggtheme <- match.arg(ggtheme) |
143 | ||
144 | ! |
plot_choices <- c("Summary Obs", "Summary Patients", "Combinations Main", "Combinations Hist", "By Subject") |
145 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
146 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
147 | ||
148 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
149 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
150 | ||
151 | ! |
assert_decorators(decorators, names = c("summary_plot", "combination_plot", "by_subject_plot")) |
152 |
# End of assertions |
|
153 | ||
154 | ! |
datanames_module <- if (identical(datanames, "all") || is.null(datanames)) { |
155 | ! |
datanames |
156 |
} else { |
|
157 | ! |
union(datanames, parent_dataname) |
158 |
} |
|
159 | ||
160 | ! |
ans <- module( |
161 | ! |
label, |
162 | ! |
server = srv_page_missing_data, |
163 | ! |
datanames = datanames_module, |
164 | ! |
server_args = list( |
165 | ! |
datanames = if (is.null(datanames)) "all" else datanames, |
166 | ! |
parent_dataname = parent_dataname, |
167 | ! |
plot_height = plot_height, |
168 | ! |
plot_width = plot_width, |
169 | ! |
ggplot2_args = ggplot2_args, |
170 | ! |
ggtheme = ggtheme, |
171 | ! |
decorators = decorators |
172 |
), |
|
173 | ! |
ui = ui_page_missing_data, |
174 | ! |
transformators = transformators, |
175 | ! |
ui_args = list(pre_output = pre_output, post_output = post_output) |
176 |
) |
|
177 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
178 | ! |
ans |
179 |
} |
|
180 | ||
181 |
# UI function for the missing data module (all datasets) |
|
182 |
ui_page_missing_data <- function(id, pre_output = NULL, post_output = NULL) { |
|
183 | ! |
ns <- NS(id) |
184 | ! |
tagList( |
185 | ! |
teal.widgets::standard_layout( |
186 | ! |
output = teal.widgets::white_small_well( |
187 | ! |
uiOutput(ns("dataset_tabs")) |
188 |
), |
|
189 | ! |
encoding = tags$div( |
190 | ! |
uiOutput(ns("dataset_encodings")) |
191 |
), |
|
192 | ! |
uiOutput(ns("dataset_reporter")), |
193 | ! |
pre_output = pre_output, |
194 | ! |
post_output = post_output |
195 |
) |
|
196 |
) |
|
197 |
} |
|
198 | ||
199 |
# Server function for the missing data module (all datasets) |
|
200 |
srv_page_missing_data <- function(id, data, datanames, parent_dataname, |
|
201 |
plot_height, plot_width, ggplot2_args, ggtheme, decorators) { |
|
202 | ! |
moduleServer(id, function(input, output, session) { |
203 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
204 | ||
205 | ! |
datanames <- Filter(function(name) { |
206 | ! |
is.data.frame(isolate(data())[[name]]) |
207 | ! |
}, if (identical(datanames, "all")) names(isolate(data())) else datanames) |
208 | ||
209 | ! |
if_subject_plot <- length(parent_dataname) > 0 && parent_dataname %in% datanames |
210 | ||
211 | ! |
ns <- session$ns |
212 | ||
213 | ! |
output$dataset_tabs <- renderUI({ |
214 | ! |
do.call( |
215 | ! |
tabsetPanel, |
216 | ! |
c( |
217 | ! |
id = ns("dataname_tab"), |
218 | ! |
lapply( |
219 | ! |
datanames, |
220 | ! |
function(x) { |
221 | ! |
tabPanel( |
222 | ! |
title = x, |
223 | ! |
ui_missing_data(id = ns(x), by_subject_plot = if_subject_plot) |
224 |
) |
|
225 |
} |
|
226 |
) |
|
227 |
) |
|
228 |
) |
|
229 |
}) |
|
230 | ||
231 | ! |
output$dataset_encodings <- renderUI({ |
232 | ! |
tagList( |
233 | ! |
lapply( |
234 | ! |
datanames, |
235 | ! |
function(x) { |
236 | ! |
conditionalPanel( |
237 | ! |
is_tab_active_js(ns("dataname_tab"), x), |
238 | ! |
encoding_missing_data( |
239 | ! |
id = ns(x), |
240 | ! |
summary_per_patient = if_subject_plot, |
241 | ! |
ggtheme = ggtheme, |
242 | ! |
datanames = datanames, |
243 | ! |
decorators = decorators |
244 |
) |
|
245 |
) |
|
246 |
} |
|
247 |
) |
|
248 |
) |
|
249 |
}) |
|
250 | ||
251 | ! |
output$dataset_reporter <- renderUI({ |
252 | ! |
lapply(datanames, function(x) { |
253 | ! |
dataname_ns <- NS(ns(x)) |
254 | ||
255 | ! |
conditionalPanel( |
256 | ! |
is_tab_active_js(ns("dataname_tab"), x), |
257 | ! |
tagList( |
258 | ! |
teal.widgets::verbatim_popup_ui(dataname_ns("rcode"), "Show R code") |
259 |
) |
|
260 |
) |
|
261 |
}) |
|
262 |
}) |
|
263 | ||
264 | ! |
result <- sapply( |
265 | ! |
datanames, |
266 | ! |
function(x) { |
267 | ! |
srv_missing_data( |
268 | ! |
id = x, |
269 | ! |
data = data, |
270 | ! |
dataname = x, |
271 | ! |
parent_dataname = parent_dataname, |
272 | ! |
plot_height = plot_height, |
273 | ! |
plot_width = plot_width, |
274 | ! |
ggplot2_args = ggplot2_args, |
275 | ! |
decorators = decorators |
276 |
) |
|
277 |
}, |
|
278 | ! |
USE.NAMES = TRUE, |
279 | ! |
simplify = FALSE |
280 |
) |
|
281 | ||
282 | ! |
reactive({ |
283 | ! |
if (is.null(input$dataname_tab)) { |
284 | ! |
teal.data::teal_data() |
285 |
} else { |
|
286 | ! |
result[[input$dataname_tab]]() |
287 |
} |
|
288 |
}) |
|
289 |
}) |
|
290 |
} |
|
291 | ||
292 |
# UI function for the missing data module (single dataset) |
|
293 |
ui_missing_data <- function(id, by_subject_plot = FALSE) { |
|
294 | ! |
ns <- NS(id) |
295 | ||
296 | ! |
tab_list <- list( |
297 | ! |
tabPanel( |
298 | ! |
"Summary", |
299 | ! |
teal.widgets::plot_with_settings_ui(id = ns("summary_plot")), |
300 | ! |
helpText( |
301 | ! |
tags$p(paste( |
302 | ! |
'The "Summary" graph shows the number of missing values per variable (both absolute and percentage),', |
303 | ! |
"sorted by magnitude." |
304 |
)), |
|
305 | ! |
tags$p( |
306 | ! |
'The "summary per patients" graph is showing how many subjects have at least one missing observation', |
307 | ! |
"for each variable. It will be most useful for panel datasets." |
308 |
) |
|
309 |
) |
|
310 |
), |
|
311 | ! |
tabPanel( |
312 | ! |
"Combinations", |
313 | ! |
teal.widgets::plot_with_settings_ui(id = ns("combination_plot")), |
314 | ! |
helpText( |
315 | ! |
tags$p(paste( |
316 | ! |
'The "Combinations" graph is used to explore the relationship between the missing data within', |
317 | ! |
"different columns of the dataset.", |
318 | ! |
"It shows the different patterns of missingness in the rows of the data.", |
319 | ! |
'For example, suppose that 70 rows of the data have exactly columns "A" and "B" missing.', |
320 | ! |
"In this case there would be a bar of height 70 in the top graph and", |
321 | ! |
'the column below this in the second graph would have rows "A" and "B" cells shaded red.' |
322 |
)), |
|
323 | ! |
tags$p(paste( |
324 | ! |
"Due to the large number of missing data patterns possible, only those with a large set of observations", |
325 | ! |
'are shown in the graph and the "Combination cut-off" slider can be used to adjust the number shown.' |
326 |
)) |
|
327 |
) |
|
328 |
), |
|
329 | ! |
tabPanel( |
330 | ! |
"By Variable Levels", |
331 | ! |
teal.widgets::get_dt_rows(ns("levels_table"), ns("levels_table_rows")), |
332 | ! |
DT::dataTableOutput(ns("levels_table")) |
333 |
) |
|
334 |
) |
|
335 | ! |
if (isTRUE(by_subject_plot)) { |
336 | ! |
tab_list <- append( |
337 | ! |
tab_list, |
338 | ! |
list(tabPanel( |
339 | ! |
"Grouped by Subject", |
340 | ! |
teal.widgets::plot_with_settings_ui(id = ns("by_subject_plot")), |
341 | ! |
helpText( |
342 | ! |
tags$p(paste( |
343 | ! |
"This graph shows the missingness with respect to subjects rather than individual rows of the", |
344 | ! |
"dataset. Each row represents one dataset variable and each column a single subject. Only subjects", |
345 | ! |
"with at least one record in this dataset are shown. For a given subject, if they have any missing", |
346 | ! |
"values of a specific variable then the appropriate cell in the graph is marked as missing." |
347 |
)) |
|
348 |
) |
|
349 |
)) |
|
350 |
) |
|
351 |
} |
|
352 | ||
353 | ! |
do.call( |
354 | ! |
tabsetPanel, |
355 | ! |
c( |
356 | ! |
id = ns("summary_type"), |
357 | ! |
tab_list |
358 |
) |
|
359 |
) |
|
360 |
} |
|
361 | ||
362 |
# UI encoding for the missing data module (all datasets) |
|
363 |
encoding_missing_data <- function(id, summary_per_patient = FALSE, ggtheme, datanames, decorators) { |
|
364 | ! |
ns <- NS(id) |
365 | ||
366 | ! |
tagList( |
367 | ! |
tags$label("Encodings", class = "text-primary"), |
368 | ! |
helpText( |
369 | ! |
paste0("Dataset", `if`(length(datanames) > 1, "s", ""), ":"), |
370 | ! |
tags$code(paste(datanames, collapse = ", ")) |
371 |
), |
|
372 | ! |
uiOutput(ns("variables")), |
373 | ! |
actionButton( |
374 | ! |
ns("filter_na"), |
375 | ! |
tags$span("Select only vars with missings", style = "white-space: normal;"), |
376 | ! |
width = "100%", |
377 | ! |
style = "margin-bottom: 1rem;" |
378 |
), |
|
379 | ! |
conditionalPanel( |
380 | ! |
is_tab_active_js(ns("summary_type"), "Summary"), |
381 | ! |
bslib::input_switch( |
382 | ! |
id = ns("any_na"), |
383 | ! |
label = tags$div( |
384 | ! |
HTML("Add <b>anyna</b> variable"), |
385 | ! |
bslib::tooltip( |
386 | ! |
icon("circle-info"), |
387 | ! |
tags$span( |
388 | ! |
"Describes the number of observations with at least one missing value in any variable." |
389 |
) |
|
390 |
) |
|
391 |
), |
|
392 | ! |
value = FALSE |
393 |
), |
|
394 | ! |
if (summary_per_patient) { |
395 | ! |
bslib::input_switch( |
396 | ! |
id = ns("if_patients_plot"), |
397 | ! |
label = tags$div( |
398 | ! |
"Add summary per patients", |
399 | ! |
bslib::tooltip( |
400 | ! |
icon("circle-info"), |
401 | ! |
tags$span( |
402 | ! |
paste( |
403 | ! |
"Displays the number of missing values per observation,", |
404 | ! |
"where the x-axis is sorted by observation appearance in the table." |
405 |
) |
|
406 |
) |
|
407 |
) |
|
408 |
), |
|
409 | ! |
value = FALSE |
410 |
) |
|
411 |
}, |
|
412 | ! |
ui_decorate_teal_data(ns("dec_summary_plot"), decorators = select_decorators(decorators, "summary_plot")) |
413 |
), |
|
414 | ! |
conditionalPanel( |
415 | ! |
is_tab_active_js(ns("summary_type"), "Combinations"), |
416 | ! |
uiOutput(ns("cutoff")), |
417 | ! |
ui_decorate_teal_data(ns("dec_combination_plot"), decorators = select_decorators(decorators, "combination_plot")) |
418 |
), |
|
419 | ! |
conditionalPanel( |
420 | ! |
is_tab_active_js(ns("summary_type"), "Grouped by Subject"), |
421 | ! |
ui_decorate_teal_data(ns("dec_by_subject_plot"), decorators = select_decorators(decorators, "by_subject_plot")) |
422 |
), |
|
423 | ! |
conditionalPanel( |
424 | ! |
is_tab_active_js(ns("summary_type"), "By Variable Levels"), |
425 | ! |
uiOutput(ns("group_by_var_ui")), |
426 | ! |
uiOutput(ns("group_by_vals_ui")), |
427 | ! |
radioButtons( |
428 | ! |
ns("count_type"), |
429 | ! |
label = "Display missing as", |
430 | ! |
choices = c("counts", "proportions"), |
431 | ! |
selected = "counts", |
432 | ! |
inline = TRUE |
433 |
) |
|
434 |
), |
|
435 | ! |
bslib::accordion( |
436 | ! |
bslib::accordion_panel( |
437 | ! |
title = "Plot settings", |
438 | ! |
selectInput( |
439 | ! |
inputId = ns("ggtheme"), |
440 | ! |
label = "Theme (by ggplot):", |
441 | ! |
choices = ggplot_themes, |
442 | ! |
selected = ggtheme, |
443 | ! |
multiple = FALSE |
444 |
) |
|
445 |
) |
|
446 |
) |
|
447 |
) |
|
448 |
} |
|
449 | ||
450 |
# Server function for the missing data (single dataset) |
|
451 |
srv_missing_data <- function(id, |
|
452 |
data, |
|
453 |
dataname, |
|
454 |
parent_dataname, |
|
455 |
plot_height, |
|
456 |
plot_width, |
|
457 |
ggplot2_args, |
|
458 |
decorators) { |
|
459 | ! |
checkmate::assert_class(data, "reactive") |
460 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
461 | ! |
moduleServer(id, function(input, output, session) { |
462 | ! |
ns <- session$ns |
463 | ||
464 | ! |
prev_group_by_var <- reactiveVal("") |
465 | ! |
data_r <- reactive(data()[[dataname]]) |
466 | ! |
data_keys <- reactive(unlist(teal.data::join_keys(data())[[dataname]])) |
467 | ||
468 | ! |
iv_r <- reactive({ |
469 | ! |
iv <- shinyvalidate::InputValidator$new() |
470 | ! |
iv$add_rule( |
471 | ! |
"variables_select", |
472 | ! |
shinyvalidate::sv_required("At least one reference variable needs to be selected.") |
473 |
) |
|
474 | ! |
iv$add_rule( |
475 | ! |
"variables_select", |
476 | ! |
~ if (length(setdiff((.), data_keys())) < 1) "Please also select non-key columns." |
477 |
) |
|
478 | ! |
iv_summary_table <- shinyvalidate::InputValidator$new() |
479 | ! |
iv_summary_table$condition(~ isTRUE(input$summary_type == "By Variable Levels")) |
480 | ! |
iv_summary_table$add_rule("count_type", shinyvalidate::sv_required("Please select type of counts")) |
481 | ! |
iv_summary_table$add_rule( |
482 | ! |
"group_by_vals", |
483 | ! |
shinyvalidate::sv_required("Please select both group-by variable and values") |
484 |
) |
|
485 | ! |
iv_summary_table$add_rule( |
486 | ! |
"group_by_var", |
487 | ! |
~ if (length(.) > 0 && length(input$variables_select) == 1 && (.) == input$variables_select) { |
488 | ! |
"If only one reference variable is selected it must not be the grouping variable." |
489 |
} |
|
490 |
) |
|
491 | ! |
iv_summary_table$add_rule( |
492 | ! |
"variables_select", |
493 | ! |
~ if (length(input$group_by_var) > 0 && length(.) == 1 && (.) == input$group_by_var) { |
494 | ! |
"If only one reference variable is selected it must not be the grouping variable." |
495 |
} |
|
496 |
) |
|
497 | ! |
iv$add_validator(iv_summary_table) |
498 | ! |
iv$enable() |
499 | ! |
iv |
500 |
}) |
|
501 | ||
502 | ! |
data_parent_keys <- reactive({ |
503 | ! |
if (length(parent_dataname) > 0 && parent_dataname %in% names(data())) { |
504 | ! |
keys <- teal.data::join_keys(data())[[dataname]] |
505 | ! |
if (parent_dataname %in% names(keys)) { |
506 | ! |
keys[[parent_dataname]] |
507 |
} else { |
|
508 | ! |
keys[[dataname]] |
509 |
} |
|
510 |
} else { |
|
511 | ! |
NULL |
512 |
} |
|
513 |
}) |
|
514 | ||
515 | ! |
common_code_q <- reactive({ |
516 | ! |
teal::validate_inputs(iv_r()) |
517 | ||
518 | ! |
group_var <- input$group_by_var |
519 | ! |
anl <- data_r() |
520 | ! |
obj <- data() |
521 | ! |
teal.reporter::teal_card(obj) <- c( |
522 | ! |
teal.reporter::teal_card("# Missing Data"), |
523 | ! |
teal.reporter::teal_card(obj), |
524 | ! |
teal.reporter::teal_card("## Module's code") |
525 |
) |
|
526 | ||
527 | ! |
qenv <- teal.code::eval_code(obj, { |
528 | ! |
'library("dplyr");library("ggplot2");library("tidyr");library("gridExtra")' # nolint quotes |
529 |
}) |
|
530 | ||
531 | ! |
qenv <- if (!is.null(selected_vars()) && length(selected_vars()) != ncol(anl)) { |
532 | ! |
teal.code::eval_code( |
533 | ! |
qenv, |
534 | ! |
substitute( |
535 | ! |
expr = ANL <- anl_name[, selected_vars, drop = FALSE], |
536 | ! |
env = list(anl_name = as.name(dataname), selected_vars = selected_vars()) |
537 |
) |
|
538 |
) |
|
539 |
} else { |
|
540 | ! |
teal.code::eval_code( |
541 | ! |
qenv, |
542 | ! |
substitute(expr = ANL <- anl_name, env = list(anl_name = as.name(dataname))) |
543 |
) |
|
544 |
} |
|
545 | ||
546 | ! |
if (input$summary_type == "By Variable Levels" && !is.null(group_var) && !(group_var %in% selected_vars())) { |
547 | ! |
qenv <- teal.code::eval_code( |
548 | ! |
qenv, |
549 | ! |
substitute( |
550 | ! |
expr = ANL[[group_var]] <- anl_name[[group_var]], |
551 | ! |
env = list(group_var = group_var, anl_name = as.name(dataname)) |
552 |
) |
|
553 |
) |
|
554 |
} |
|
555 | ||
556 | ! |
new_col_name <- "**anyna**" |
557 | ||
558 | ! |
qenv <- teal.code::eval_code( |
559 | ! |
qenv, |
560 | ! |
substitute( |
561 | ! |
expr = |
562 | ! |
create_cols_labels <- function(cols, just_label = FALSE) { |
563 | ! |
column_labels <- column_labels_value |
564 | ! |
column_labels[is.na(column_labels) | length(column_labels) == 0] <- "" |
565 | ! |
if (just_label) { |
566 | ! |
labels <- column_labels[cols] |
567 |
} else { |
|
568 | ! |
labels <- ifelse(cols == new_col_name | cols == "", cols, paste0(column_labels[cols], " [", cols, "]")) |
569 |
} |
|
570 | ! |
labels |
571 |
}, |
|
572 | ! |
env = list( |
573 | ! |
new_col_name = new_col_name, |
574 | ! |
column_labels_value = c(teal.data::col_labels(data_r())[selected_vars()], |
575 | ! |
new_col_name = new_col_name |
576 |
) |
|
577 |
) |
|
578 |
) |
|
579 |
) |
|
580 | ! |
qenv |
581 |
}) |
|
582 | ||
583 | ! |
selected_vars <- reactive({ |
584 | ! |
req(input$variables_select) |
585 | ! |
keys <- data_keys() |
586 | ! |
vars <- unique(c(keys, input$variables_select)) |
587 | ! |
vars |
588 |
}) |
|
589 | ||
590 | ! |
vars_summary <- reactive({ |
591 | ! |
na_count <- data_r() %>% |
592 | ! |
sapply(function(x) mean(is.na(x)), USE.NAMES = TRUE) %>% |
593 | ! |
sort(decreasing = TRUE) |
594 | ||
595 | ! |
tibble::tibble( |
596 | ! |
key = names(na_count), |
597 | ! |
value = unname(na_count), |
598 | ! |
label = cut(na_count, breaks = seq(from = 0, to = 1, by = 0.1), include.lowest = TRUE) |
599 |
) |
|
600 |
}) |
|
601 | ||
602 |
# Keep encoding panel up-to-date |
|
603 | ! |
output$variables <- renderUI({ |
604 | ! |
choices <- split(x = vars_summary()$key, f = vars_summary()$label, drop = TRUE) %>% rev() |
605 | ! |
selected <- choices <- unname(unlist(choices)) |
606 | ||
607 | ! |
teal.widgets::optionalSelectInput( |
608 | ! |
ns("variables_select"), |
609 | ! |
label = "Select variables", |
610 | ! |
label_help = HTML(paste0("Dataset: ", tags$code(dataname))), |
611 | ! |
choices = teal.transform::variable_choices(data_r(), choices), |
612 | ! |
selected = selected, |
613 | ! |
multiple = TRUE |
614 |
) |
|
615 |
}) |
|
616 | ||
617 | ! |
observeEvent(input$filter_na, { |
618 | ! |
choices <- vars_summary() %>% |
619 | ! |
dplyr::select(!!as.name("key")) %>% |
620 | ! |
getElement(name = 1) |
621 | ||
622 | ! |
selected <- vars_summary() %>% |
623 | ! |
dplyr::filter(!!as.name("value") > 0) %>% |
624 | ! |
dplyr::select(!!as.name("key")) %>% |
625 | ! |
getElement(name = 1) |
626 | ||
627 | ! |
teal.widgets::updateOptionalSelectInput( |
628 | ! |
session = session, |
629 | ! |
inputId = "variables_select", |
630 | ! |
choices = teal.transform::variable_choices(data_r()), |
631 | ! |
selected = restoreInput(ns("variables_select"), selected) |
632 |
) |
|
633 |
}) |
|
634 | ||
635 | ! |
output$group_by_var_ui <- renderUI({ |
636 | ! |
all_choices <- teal.transform::variable_choices(data_r()) |
637 | ! |
cat_choices <- all_choices[!sapply(data_r(), function(x) is.numeric(x) || inherits(x, "POSIXct"))] |
638 | ! |
validate( |
639 | ! |
need(cat_choices, "Dataset does not have any non-numeric or non-datetime variables to use to group data with") |
640 |
) |
|
641 | ! |
teal.widgets::optionalSelectInput( |
642 | ! |
ns("group_by_var"), |
643 | ! |
label = "Group by variable", |
644 | ! |
choices = cat_choices, |
645 | ! |
selected = `if`( |
646 | ! |
is.null(isolate(input$group_by_var)), |
647 | ! |
cat_choices[1], |
648 | ! |
isolate(input$group_by_var) |
649 |
), |
|
650 | ! |
multiple = FALSE, |
651 | ! |
label_help = paste0("Dataset: ", dataname) |
652 |
) |
|
653 |
}) |
|
654 | ||
655 | ! |
output$group_by_vals_ui <- renderUI({ |
656 | ! |
req(input$group_by_var) |
657 | ||
658 | ! |
choices <- teal.transform::value_choices(data_r(), input$group_by_var, input$group_by_var) |
659 | ! |
prev_choices <- isolate(input$group_by_vals) |
660 | ||
661 |
# determine selected value based on filtered data |
|
662 |
# display those previously selected values that are still available |
|
663 | ! |
selected <- if (!is.null(prev_choices) && any(prev_choices %in% choices)) { |
664 | ! |
prev_choices[match(choices[choices %in% prev_choices], prev_choices)] |
665 | ! |
} else if ( |
666 | ! |
!is.null(prev_choices) && |
667 | ! |
!any(prev_choices %in% choices) && |
668 | ! |
isolate(prev_group_by_var()) == input$group_by_var |
669 |
) { |
|
670 |
# if not any previously selected value is available and the grouping variable is the same, |
|
671 |
# then display NULL |
|
672 | ! |
NULL |
673 |
} else { |
|
674 |
# if new grouping variable (i.e. not any previously selected value is available), |
|
675 |
# then display all choices |
|
676 | ! |
choices |
677 |
} |
|
678 | ||
679 | ! |
prev_group_by_var(input$group_by_var) # set current group_by_var |
680 | ! |
validate(need(length(choices) < 100, "Please select group-by variable with fewer than 100 unique values")) |
681 | ! |
teal.widgets::optionalSelectInput( |
682 | ! |
ns("group_by_vals"), |
683 | ! |
label = "Filter levels", |
684 | ! |
choices = choices, |
685 | ! |
selected = selected, |
686 | ! |
multiple = TRUE, |
687 | ! |
label_help = paste0("Dataset: ", dataname) |
688 |
) |
|
689 |
}) |
|
690 | ||
691 | ! |
combination_cutoff_q <- reactive({ |
692 | ! |
req(common_code_q()) |
693 | ! |
qenv <- common_code_q() |
694 | ! |
teal.reporter::teal_card(qenv) <- c(teal.reporter::teal_card(qenv), "## Combination Plot") |
695 | ! |
teal.code::eval_code( |
696 | ! |
qenv, |
697 | ! |
quote( |
698 | ! |
combination_cutoff <- ANL %>% |
699 | ! |
dplyr::mutate_all(is.na) %>% |
700 | ! |
dplyr::group_by_all() %>% |
701 | ! |
dplyr::tally() %>% |
702 | ! |
dplyr::ungroup() |
703 |
) |
|
704 |
) |
|
705 |
}) |
|
706 | ||
707 | ! |
output$cutoff <- renderUI({ |
708 | ! |
x <- combination_cutoff_q()[["combination_cutoff"]]$n |
709 | ||
710 |
# select 10-th from the top |
|
711 | ! |
n <- length(x) |
712 | ! |
idx <- max(1, n - 10) |
713 | ! |
prev_value <- isolate(input$combination_cutoff) |
714 | ! |
value <- if (is.null(prev_value) || prev_value > max(x) || prev_value < min(x)) { |
715 | ! |
sort(x, partial = idx)[idx] |
716 |
} else { |
|
717 | ! |
prev_value |
718 |
} |
|
719 | ||
720 | ! |
teal.widgets::optionalSliderInputValMinMax( |
721 | ! |
ns("combination_cutoff"), |
722 | ! |
"Combination cut-off", |
723 | ! |
c(value, range(x)) |
724 |
) |
|
725 |
}) |
|
726 | ||
727 |
# Prepare qenvs for output objects |
|
728 | ||
729 | ! |
summary_plot_q <- reactive({ |
730 | ! |
req(input$summary_type == "Summary") # needed to trigger show r code update on tab change |
731 | ! |
teal::validate_has_data(data_r(), 1) |
732 | ||
733 | ! |
qenv <- common_code_q() |
734 | ! |
if (input$any_na) { |
735 | ! |
new_col_name <- "**anyna**" |
736 | ! |
qenv <- teal.code::eval_code( |
737 | ! |
qenv, |
738 | ! |
substitute( |
739 | ! |
expr = ANL[[new_col_name]] <- ifelse(rowSums(is.na(ANL)) > 0, NA, FALSE), |
740 | ! |
env = list(new_col_name = new_col_name) |
741 |
) |
|
742 |
) |
|
743 |
} |
|
744 | ||
745 | ! |
qenv <- teal.code::eval_code( |
746 | ! |
qenv, |
747 | ! |
substitute( |
748 | ! |
expr = analysis_vars <- setdiff(colnames(ANL), data_keys), |
749 | ! |
env = list(data_keys = data_keys()) |
750 |
) |
|
751 |
) |
|
752 | ||
753 | ! |
teal.reporter::teal_card(qenv) <- c(teal.reporter::teal_card(qenv), "## Summary Plot") |
754 | ||
755 | ! |
qenv <- teal.code::eval_code( |
756 | ! |
qenv, |
757 | ! |
substitute( |
758 | ! |
expr = summary_plot_obs <- data_frame_call[, analysis_vars] %>% |
759 | ! |
dplyr::summarise_all(list(function(x) sum(is.na(x)))) %>% |
760 | ! |
tidyr::pivot_longer(dplyr::everything(), names_to = "col", values_to = "n_na") %>% |
761 | ! |
dplyr::mutate(n_not_na = nrow(ANL) - n_na) %>% |
762 | ! |
tidyr::pivot_longer(-col, names_to = "isna", values_to = "n") %>% |
763 | ! |
dplyr::mutate(isna = isna == "n_na", n_pct = n / nrow(ANL) * 100), |
764 | ! |
env = list(data_frame_call = if (!inherits(data_r(), "tbl_df")) { |
765 | ! |
quote(tibble::as_tibble(ANL)) |
766 |
} else { |
|
767 | ! |
quote(ANL) |
768 |
}) |
|
769 |
) |
|
770 |
) %>% |
|
771 |
# x axis ordering according to number of missing values and alphabet |
|
772 | ! |
teal.code::eval_code( |
773 | ! |
quote( |
774 | ! |
expr = x_levels <- dplyr::filter(summary_plot_obs, isna) %>% |
775 | ! |
dplyr::arrange(n_pct, dplyr::desc(col)) %>% |
776 | ! |
dplyr::pull(col) %>% |
777 | ! |
create_cols_labels() |
778 |
) |
|
779 |
) |
|
780 | ||
781 |
# always set "**anyna**" level as the last one |
|
782 | ! |
if (isolate(input$any_na)) { |
783 | ! |
qenv <- teal.code::eval_code( |
784 | ! |
qenv, |
785 | ! |
quote(x_levels <- c(setdiff(x_levels, "**anyna**"), "**anyna**")) |
786 |
) |
|
787 |
} |
|
788 | ||
789 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
790 | ! |
labs = list(x = "Variable", y = "Missing observations"), |
791 | ! |
theme = list(legend.position = "bottom", axis.text.x = quote(ggplot2::element_text(angle = 45, hjust = 1))) |
792 |
) |
|
793 | ||
794 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
795 | ! |
user_plot = ggplot2_args[["Summary Obs"]], |
796 | ! |
user_default = ggplot2_args$default, |
797 | ! |
module_plot = dev_ggplot2_args |
798 |
) |
|
799 | ||
800 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
801 | ! |
all_ggplot2_args, |
802 | ! |
ggtheme = input$ggtheme |
803 |
) |
|
804 | ||
805 | ! |
qenv <- teal.code::eval_code( |
806 | ! |
qenv, |
807 | ! |
substitute( |
808 | ! |
summary_plot_top <- summary_plot_obs %>% |
809 | ! |
ggplot2::ggplot() + |
810 | ! |
ggplot2::aes( |
811 | ! |
x = factor(create_cols_labels(col), levels = x_levels), |
812 | ! |
y = n_pct, |
813 | ! |
fill = isna |
814 |
) + |
|
815 | ! |
ggplot2::geom_bar(position = "fill", stat = "identity") + |
816 | ! |
ggplot2::scale_fill_manual( |
817 | ! |
name = "", |
818 | ! |
values = c("grey90", c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]), |
819 | ! |
labels = c("Present", "Missing") |
820 |
) + |
|
821 | ! |
ggplot2::scale_y_continuous( |
822 | ! |
labels = scales::percent_format(), |
823 | ! |
breaks = seq(0, 1, by = 0.1), |
824 | ! |
expand = c(0, 0) |
825 |
) + |
|
826 | ! |
ggplot2::geom_text( |
827 | ! |
ggplot2::aes(label = ifelse(isna == TRUE, sprintf("%d [%.02f%%]", n, n_pct), ""), y = 1), |
828 | ! |
hjust = 1, |
829 | ! |
color = "black" |
830 |
) + |
|
831 | ! |
labs + |
832 | ! |
ggthemes + |
833 | ! |
themes + |
834 | ! |
ggplot2::coord_flip(), |
835 | ! |
env = list( |
836 | ! |
labs = parsed_ggplot2_args$labs, |
837 | ! |
themes = parsed_ggplot2_args$theme, |
838 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
839 |
) |
|
840 |
) |
|
841 |
) |
|
842 | ||
843 | ! |
if (isTRUE(input$if_patients_plot)) { |
844 | ! |
qenv <- teal.code::eval_code( |
845 | ! |
qenv, |
846 | ! |
substitute( |
847 | ! |
expr = parent_keys <- keys, |
848 | ! |
env = list(keys = data_parent_keys()) |
849 |
) |
|
850 |
) %>% |
|
851 | ! |
teal.code::eval_code(quote(ndistinct_subjects <- dplyr::n_distinct(ANL[, parent_keys]))) %>% |
852 | ! |
teal.code::eval_code( |
853 | ! |
quote( |
854 | ! |
summary_plot_patients <- ANL[, c(parent_keys, analysis_vars)] %>% |
855 | ! |
dplyr::group_by_at(parent_keys) %>% |
856 | ! |
dplyr::summarise_all(anyNA) %>% |
857 | ! |
tidyr::pivot_longer(cols = !dplyr::all_of(parent_keys), names_to = "col", values_to = "anyna") %>% |
858 | ! |
dplyr::group_by_at(c("col")) %>% |
859 | ! |
dplyr::summarise(count_na = sum(anyna)) %>% |
860 | ! |
dplyr::mutate(count_not_na = ndistinct_subjects - count_na) %>% |
861 | ! |
tidyr::pivot_longer(-c(col), names_to = "isna", values_to = "n") %>% |
862 | ! |
dplyr::mutate(isna = isna == "count_na", n_pct = n / ndistinct_subjects * 100) %>% |
863 | ! |
dplyr::arrange_at(c("isna", "n"), .funs = dplyr::desc) |
864 |
) |
|
865 |
) |
|
866 | ||
867 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
868 | ! |
labs = list(x = "", y = "Missing patients"), |
869 | ! |
theme = list( |
870 | ! |
legend.position = "bottom", |
871 | ! |
axis.text.x = quote(ggplot2::element_text(angle = 45, hjust = 1)), |
872 | ! |
axis.text.y = quote(ggplot2::element_blank()) |
873 |
) |
|
874 |
) |
|
875 | ||
876 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
877 | ! |
user_plot = ggplot2_args[["Summary Patients"]], |
878 | ! |
user_default = ggplot2_args$default, |
879 | ! |
module_plot = dev_ggplot2_args |
880 |
) |
|
881 | ||
882 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
883 | ! |
all_ggplot2_args, |
884 | ! |
ggtheme = input$ggtheme |
885 |
) |
|
886 | ||
887 | ! |
qenv <- teal.code::eval_code( |
888 | ! |
qenv, |
889 | ! |
substitute( |
890 | ! |
summary_plot_bottom <- summary_plot_patients %>% |
891 | ! |
ggplot2::ggplot() + |
892 | ! |
ggplot2::aes_( |
893 | ! |
x = ~ factor(create_cols_labels(col), levels = x_levels), |
894 | ! |
y = ~n_pct, |
895 | ! |
fill = ~isna |
896 |
) + |
|
897 | ! |
ggplot2::geom_bar(alpha = 1, stat = "identity", position = "fill") + |
898 | ! |
ggplot2::scale_y_continuous( |
899 | ! |
labels = scales::percent_format(), |
900 | ! |
breaks = seq(0, 1, by = 0.1), |
901 | ! |
expand = c(0, 0) |
902 |
) + |
|
903 | ! |
ggplot2::scale_fill_manual( |
904 | ! |
name = "", |
905 | ! |
values = c("grey90", c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]), |
906 | ! |
labels = c("Present", "Missing") |
907 |
) + |
|
908 | ! |
ggplot2::geom_text( |
909 | ! |
ggplot2::aes(label = ifelse(isna == TRUE, sprintf("%d [%.02f%%]", n, n_pct), ""), y = 1), |
910 | ! |
hjust = 1, |
911 | ! |
color = "black" |
912 |
) + |
|
913 | ! |
labs + |
914 | ! |
ggthemes + |
915 | ! |
themes + |
916 | ! |
ggplot2::coord_flip(), |
917 | ! |
env = list( |
918 | ! |
labs = parsed_ggplot2_args$labs, |
919 | ! |
themes = parsed_ggplot2_args$theme, |
920 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
921 |
) |
|
922 |
) |
|
923 |
) |
|
924 |
} |
|
925 | ||
926 | ! |
if (isTRUE(input$if_patients_plot)) { |
927 | ! |
within(qenv, { |
928 | ! |
summary_plot <- gridExtra::grid.arrange(summary_plot_top, summary_plot_bottom, ncol = 2) |
929 |
}) |
|
930 |
} else { |
|
931 | ! |
within(qenv, { |
932 | ! |
summary_plot <- summary_plot_top |
933 |
}) |
|
934 |
} |
|
935 |
}) |
|
936 | ||
937 | ! |
combination_plot_q <- reactive({ |
938 | ! |
req(input$summary_type == "Combinations", input$combination_cutoff, combination_cutoff_q()) |
939 | ! |
teal::validate_has_data(data_r(), 1) |
940 | ||
941 | ! |
qenv <- teal.code::eval_code( |
942 | ! |
combination_cutoff_q(), |
943 | ! |
substitute( |
944 | ! |
expr = data_combination_plot_cutoff <- combination_cutoff %>% |
945 | ! |
dplyr::filter(n >= combination_cutoff_value) %>% |
946 | ! |
dplyr::mutate(id = rank(-n, ties.method = "first")) %>% |
947 | ! |
tidyr::pivot_longer(-c(n, id), names_to = "key", values_to = "value") %>% |
948 | ! |
dplyr::arrange(n), |
949 | ! |
env = list(combination_cutoff_value = input$combination_cutoff) |
950 |
) |
|
951 |
) |
|
952 | ||
953 |
# find keys in dataset not selected in the UI and remove them from dataset |
|
954 | ! |
keys_not_selected <- setdiff(data_keys(), input$variables_select) |
955 | ! |
if (length(keys_not_selected) > 0) { |
956 | ! |
qenv <- teal.code::eval_code( |
957 | ! |
qenv, |
958 | ! |
substitute( |
959 | ! |
expr = data_combination_plot_cutoff <- data_combination_plot_cutoff %>% |
960 | ! |
dplyr::filter(!key %in% keys_not_selected), |
961 | ! |
env = list(keys_not_selected = keys_not_selected) |
962 |
) |
|
963 |
) |
|
964 |
} |
|
965 | ||
966 | ! |
qenv <- teal.code::eval_code( |
967 | ! |
qenv, |
968 | ! |
quote( |
969 | ! |
labels <- data_combination_plot_cutoff %>% |
970 | ! |
dplyr::filter(key == key[[1]]) %>% |
971 | ! |
getElement(name = 1) |
972 |
) |
|
973 |
) |
|
974 | ||
975 | ! |
dev_ggplot2_args1 <- teal.widgets::ggplot2_args( |
976 | ! |
labs = list(x = "", y = ""), |
977 | ! |
theme = list( |
978 | ! |
legend.position = "bottom", |
979 | ! |
axis.text.x = quote(ggplot2::element_blank()) |
980 |
) |
|
981 |
) |
|
982 | ||
983 | ! |
all_ggplot2_args1 <- teal.widgets::resolve_ggplot2_args( |
984 | ! |
user_plot = ggplot2_args[["Combinations Hist"]], |
985 | ! |
user_default = ggplot2_args$default, |
986 | ! |
module_plot = dev_ggplot2_args1 |
987 |
) |
|
988 | ||
989 | ! |
parsed_ggplot2_args1 <- teal.widgets::parse_ggplot2_args( |
990 | ! |
all_ggplot2_args1, |
991 | ! |
ggtheme = "void" |
992 |
) |
|
993 | ||
994 | ! |
dev_ggplot2_args2 <- teal.widgets::ggplot2_args( |
995 | ! |
labs = list(x = "", y = ""), |
996 | ! |
theme = list( |
997 | ! |
legend.position = "bottom", |
998 | ! |
axis.text.x = quote(ggplot2::element_blank()), |
999 | ! |
axis.ticks = quote(ggplot2::element_blank()), |
1000 | ! |
panel.grid.major = quote(ggplot2::element_blank()) |
1001 |
) |
|
1002 |
) |
|
1003 | ||
1004 | ! |
all_ggplot2_args2 <- teal.widgets::resolve_ggplot2_args( |
1005 | ! |
user_plot = ggplot2_args[["Combinations Main"]], |
1006 | ! |
user_default = ggplot2_args$default, |
1007 | ! |
module_plot = dev_ggplot2_args2 |
1008 |
) |
|
1009 | ||
1010 | ! |
parsed_ggplot2_args2 <- teal.widgets::parse_ggplot2_args( |
1011 | ! |
all_ggplot2_args2, |
1012 | ! |
ggtheme = input$ggtheme |
1013 |
) |
|
1014 | ||
1015 | ! |
qenv <- teal.code::eval_code( |
1016 | ! |
qenv, |
1017 | ! |
substitute( |
1018 | ! |
expr = { |
1019 | ! |
combination_plot_top <- data_combination_plot_cutoff %>% |
1020 | ! |
dplyr::select(id, n) %>% |
1021 | ! |
dplyr::distinct() %>% |
1022 | ! |
ggplot2::ggplot(ggplot2::aes(x = id, y = n)) + |
1023 | ! |
ggplot2::geom_bar(stat = "identity", fill = c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]) + |
1024 | ! |
ggplot2::geom_text( |
1025 | ! |
ggplot2::aes(label = n), |
1026 | ! |
position = ggplot2::position_dodge(width = 0.9), |
1027 | ! |
vjust = -0.25 |
1028 |
) + |
|
1029 | ! |
ggplot2::ylim(c(0, max(data_combination_plot_cutoff$n) * 1.5)) + |
1030 | ! |
labs1 + |
1031 | ! |
ggthemes1 + |
1032 | ! |
themes1 |
1033 | ||
1034 | ! |
graph_number_rows <- length(unique(data_combination_plot_cutoff$id)) |
1035 | ! |
graph_number_cols <- nrow(data_combination_plot_cutoff) / graph_number_rows |
1036 | ||
1037 | ! |
combination_plot_bottom <- data_combination_plot_cutoff %>% ggplot2::ggplot() + |
1038 | ! |
ggplot2::aes(x = create_cols_labels(key), y = id - 0.5, fill = value) + |
1039 | ! |
ggplot2::geom_tile(alpha = 0.85, height = 0.95) + |
1040 | ! |
ggplot2::scale_fill_manual( |
1041 | ! |
name = "", |
1042 | ! |
values = c("grey90", c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]), |
1043 | ! |
labels = c("Present", "Missing") |
1044 |
) + |
|
1045 | ! |
ggplot2::geom_hline(yintercept = seq_len(1 + graph_number_rows) - 1) + |
1046 | ! |
ggplot2::geom_vline(xintercept = seq_len(1 + graph_number_cols) - 0.5, linetype = "dotted") + |
1047 | ! |
ggplot2::coord_flip() + |
1048 | ! |
labs2 + |
1049 | ! |
ggthemes2 + |
1050 | ! |
themes2 |
1051 |
}, |
|
1052 | ! |
env = list( |
1053 | ! |
labs1 = parsed_ggplot2_args1$labs, |
1054 | ! |
themes1 = parsed_ggplot2_args1$theme, |
1055 | ! |
ggthemes1 = parsed_ggplot2_args1$ggtheme, |
1056 | ! |
labs2 = parsed_ggplot2_args2$labs, |
1057 | ! |
themes2 = parsed_ggplot2_args2$theme, |
1058 | ! |
ggthemes2 = parsed_ggplot2_args2$ggtheme |
1059 |
) |
|
1060 |
) |
|
1061 |
) |
|
1062 | ||
1063 | ! |
within(qenv, { |
1064 | ! |
g1 <- ggplot2::ggplotGrob(combination_plot_top) |
1065 | ! |
g2 <- ggplot2::ggplotGrob(combination_plot_bottom) |
1066 | ||
1067 | ! |
combination_plot <- gridExtra::gtable_rbind(g1, g2, size = "last") |
1068 | ! |
combination_plot$heights[7] <- grid::unit(0.2, "null") # rescale to get the bar chart smaller |
1069 |
}) |
|
1070 |
}) |
|
1071 | ||
1072 | ! |
summary_table_q <- reactive({ |
1073 | ! |
req( |
1074 | ! |
input$summary_type == "By Variable Levels", # needed to trigger show r code update on tab change |
1075 | ! |
common_code_q() |
1076 |
) |
|
1077 | ! |
teal::validate_has_data(data_r(), 1) |
1078 | ||
1079 |
# extract the ANL dataset for use in further validation |
|
1080 | ! |
anl <- common_code_q()[["ANL"]] |
1081 | ||
1082 | ! |
group_var <- input$group_by_var |
1083 | ! |
validate( |
1084 | ! |
need( |
1085 | ! |
is.null(group_var) || |
1086 | ! |
length(unique(anl[[group_var]])) < 100, |
1087 | ! |
"Please select group-by variable with fewer than 100 unique values" |
1088 |
) |
|
1089 |
) |
|
1090 | ||
1091 | ! |
group_vals <- input$group_by_vals |
1092 | ! |
variables_select <- input$variables_select |
1093 | ! |
vars <- unique(variables_select, group_var) |
1094 | ! |
count_type <- input$count_type |
1095 | ||
1096 | ! |
if (!is.null(selected_vars()) && length(selected_vars()) != ncol(anl)) { |
1097 | ! |
variables <- selected_vars() |
1098 |
} else { |
|
1099 | ! |
variables <- colnames(anl) |
1100 |
} |
|
1101 | ||
1102 | ! |
summ_fn <- if (input$count_type == "counts") { |
1103 | ! |
function(x) sum(is.na(x)) |
1104 |
} else { |
|
1105 | ! |
function(x) round(sum(is.na(x)) / length(x), 4) |
1106 |
} |
|
1107 | ||
1108 | ! |
qenv <- common_code_q() |
1109 | ! |
teal.reporter::teal_card(qenv) <- c(teal.reporter::teal_card(qenv), "## Summary Table") |
1110 | ||
1111 | ! |
qenv <- if (!is.null(group_var)) { |
1112 | ! |
common_code_libraries_q <- teal.code::eval_code( |
1113 | ! |
qenv, |
1114 | ! |
'library("forcats");library("glue")' # nolint |
1115 |
) |
|
1116 | ! |
teal.code::eval_code( |
1117 | ! |
common_code_libraries_q, |
1118 | ! |
substitute( |
1119 | ! |
expr = { |
1120 | ! |
summary_data <- ANL %>% |
1121 | ! |
dplyr::mutate(group_var_name := forcats::fct_na_value_to_level(as.factor(group_var_name), "NA")) %>% |
1122 | ! |
dplyr::group_by_at(group_var) %>% |
1123 | ! |
dplyr::filter(group_var_name %in% group_vals) |
1124 | ||
1125 | ! |
count_data <- dplyr::summarise(summary_data, n = dplyr::n()) |
1126 | ||
1127 | ! |
summary_data <- dplyr::summarise_all(summary_data, summ_fn) %>% |
1128 | ! |
dplyr::mutate(group_var_name := paste0(group_var, ":", group_var_name, "(N=", count_data$n, ")")) %>% |
1129 | ! |
tidyr::pivot_longer(!dplyr::all_of(group_var), names_to = "Variable", values_to = "out") %>% |
1130 | ! |
tidyr::pivot_wider(names_from = group_var, values_from = "out") %>% |
1131 | ! |
dplyr::mutate(`Variable label` = create_cols_labels(Variable, just_label = TRUE), .after = Variable) |
1132 |
}, |
|
1133 | ! |
env = list( |
1134 | ! |
group_var = group_var, group_var_name = as.name(group_var), group_vals = group_vals, summ_fn = summ_fn |
1135 |
) |
|
1136 |
) |
|
1137 |
) |
|
1138 |
} else { |
|
1139 | ! |
teal.code::eval_code( |
1140 | ! |
qenv, |
1141 | ! |
substitute( |
1142 | ! |
expr = summary_data <- ANL %>% |
1143 | ! |
dplyr::summarise_all(summ_fn) %>% |
1144 | ! |
tidyr::pivot_longer(dplyr::everything(), |
1145 | ! |
names_to = "Variable", |
1146 | ! |
values_to = paste0("Missing (N=", nrow(ANL), ")") |
1147 |
) %>% |
|
1148 | ! |
dplyr::mutate(`Variable label` = create_cols_labels(Variable), .after = Variable), |
1149 | ! |
env = list(summ_fn = summ_fn) |
1150 |
) |
|
1151 |
) |
|
1152 |
} |
|
1153 | ||
1154 | ! |
within(qenv, { |
1155 | ! |
table <- rtables::df_to_tt(summary_data) |
1156 | ! |
table |
1157 |
}) |
|
1158 |
}) |
|
1159 | ||
1160 | ! |
by_subject_plot_q <- reactive({ |
1161 |
# needed to trigger show r code update on tab change |
|
1162 | ! |
req(input$summary_type == "Grouped by Subject", common_code_q()) |
1163 | ||
1164 | ! |
teal::validate_has_data(data_r(), 1) |
1165 | ||
1166 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
1167 | ! |
labs = list(x = "", y = ""), |
1168 | ! |
theme = list(legend.position = "bottom", axis.text.x = quote(ggplot2::element_blank())) |
1169 |
) |
|
1170 | ||
1171 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
1172 | ! |
user_plot = ggplot2_args[["By Subject"]], |
1173 | ! |
user_default = ggplot2_args$default, |
1174 | ! |
module_plot = dev_ggplot2_args |
1175 |
) |
|
1176 | ||
1177 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
1178 | ! |
all_ggplot2_args, |
1179 | ! |
ggtheme = input$ggtheme |
1180 |
) |
|
1181 | ||
1182 |
# Unlikely that `rlang` is not available, new hashing may be expensive |
|
1183 | ! |
hashing_function <- if (requireNamespace("rlang", quietly = TRUE)) { |
1184 | ! |
quote(rlang::hash) |
1185 |
} else { |
|
1186 | ! |
function(x) paste(as.integer(x), collapse = "") |
1187 |
} |
|
1188 | ||
1189 | ! |
qenv <- common_code_q() |
1190 | ! |
teal.reporter::teal_card(qenv) <- c(teal.reporter::teal_card(qenv), "## By Subject Plot") |
1191 | ||
1192 | ! |
qenv <- teal.code::eval_code( |
1193 | ! |
qenv, |
1194 | ! |
substitute( |
1195 | ! |
expr = parent_keys <- keys, |
1196 | ! |
env = list(keys = data_parent_keys()) |
1197 |
) |
|
1198 |
) %>% |
|
1199 | ! |
teal.code::eval_code( |
1200 | ! |
substitute( |
1201 | ! |
expr = analysis_vars <- setdiff(colnames(ANL), data_keys), |
1202 | ! |
env = list(data_keys = data_keys()) |
1203 |
) |
|
1204 |
) %>% |
|
1205 | ! |
teal.code::eval_code( |
1206 | ! |
substitute( |
1207 | ! |
expr = { |
1208 | ! |
summary_plot_patients <- ANL[, c(parent_keys, analysis_vars)] %>% |
1209 | ! |
dplyr::group_by_at(parent_keys) %>% |
1210 | ! |
dplyr::mutate(id = dplyr::cur_group_id()) %>% |
1211 | ! |
dplyr::ungroup() %>% |
1212 | ! |
dplyr::group_by_at(c(parent_keys, "id")) %>% |
1213 | ! |
dplyr::summarise_all(anyNA) %>% |
1214 | ! |
dplyr::ungroup() |
1215 | ||
1216 |
# order subjects by decreasing number of missing and then by |
|
1217 |
# missingness pattern (defined using sha1) |
|
1218 | ! |
order_subjects <- summary_plot_patients %>% |
1219 | ! |
dplyr::select(-"id", -dplyr::all_of(parent_keys)) %>% |
1220 | ! |
dplyr::transmute( |
1221 | ! |
id = dplyr::row_number(), |
1222 | ! |
number_NA = apply(., 1, sum), |
1223 | ! |
sha = apply(., 1, hashing_function) |
1224 |
) %>% |
|
1225 | ! |
dplyr::arrange(dplyr::desc(number_NA), sha) %>% |
1226 | ! |
getElement(name = "id") |
1227 | ||
1228 |
# order columns by decreasing percent of missing values |
|
1229 | ! |
ordered_columns <- summary_plot_patients %>% |
1230 | ! |
dplyr::select(-"id", -dplyr::all_of(parent_keys)) %>% |
1231 | ! |
dplyr::summarise( |
1232 | ! |
column = create_cols_labels(colnames(.)), |
1233 | ! |
na_count = apply(., MARGIN = 2, FUN = sum), |
1234 | ! |
na_percent = na_count / nrow(.) * 100 |
1235 |
) %>% |
|
1236 | ! |
dplyr::arrange(na_percent, dplyr::desc(column)) |
1237 | ||
1238 | ! |
summary_plot_patients <- summary_plot_patients %>% |
1239 | ! |
tidyr::gather("col", "isna", -"id", -dplyr::all_of(parent_keys)) %>% |
1240 | ! |
dplyr::mutate(col = create_cols_labels(col)) |
1241 |
}, |
|
1242 | ! |
env = list(hashing_function = hashing_function) |
1243 |
) |
|
1244 |
) |
|
1245 | ||
1246 | ! |
qenv <- teal.code::eval_code( |
1247 | ! |
qenv, |
1248 | ! |
substitute( |
1249 | ! |
expr = { |
1250 | ! |
by_subject_plot <- ggplot2::ggplot(summary_plot_patients, ggplot2::aes( |
1251 | ! |
x = factor(id, levels = order_subjects), |
1252 | ! |
y = factor(col, levels = ordered_columns[["column"]]), |
1253 | ! |
fill = isna |
1254 |
)) + |
|
1255 | ! |
ggplot2::geom_raster() + |
1256 | ! |
ggplot2::annotate( |
1257 | ! |
"text", |
1258 | ! |
x = length(order_subjects), |
1259 | ! |
y = seq_len(nrow(ordered_columns)), |
1260 | ! |
hjust = 1, |
1261 | ! |
label = sprintf("%d [%.02f%%]", ordered_columns[["na_count"]], ordered_columns[["na_percent"]]) |
1262 |
) + |
|
1263 | ! |
ggplot2::scale_fill_manual( |
1264 | ! |
name = "", |
1265 | ! |
values = c("grey90", c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]), |
1266 | ! |
labels = c("Present", "Missing (at least one)") |
1267 |
) + |
|
1268 | ! |
labs + |
1269 | ! |
ggthemes + |
1270 | ! |
themes |
1271 |
}, |
|
1272 | ! |
env = list( |
1273 | ! |
labs = parsed_ggplot2_args$labs, |
1274 | ! |
themes = parsed_ggplot2_args$theme, |
1275 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
1276 |
) |
|
1277 |
) |
|
1278 |
) |
|
1279 |
}) |
|
1280 | ||
1281 |
# Decorated outputs |
|
1282 | ||
1283 |
# Summary_plot_q |
|
1284 | ! |
decorated_summary_plot_q <- srv_decorate_teal_data( |
1285 | ! |
id = "dec_summary_plot", |
1286 | ! |
data = summary_plot_q, |
1287 | ! |
decorators = select_decorators(decorators, "summary_plot"), |
1288 | ! |
expr = quote({ |
1289 | ! |
summary_plot |
1290 |
}) |
|
1291 |
) |
|
1292 | ||
1293 | ! |
decorated_combination_plot_q <- srv_decorate_teal_data( |
1294 | ! |
id = "dec_combination_plot", |
1295 | ! |
data = combination_plot_q, |
1296 | ! |
decorators = select_decorators(decorators, "combination_plot"), |
1297 | ! |
expr = quote({ |
1298 | ! |
grid::grid.newpage() |
1299 | ! |
grid::grid.draw(combination_plot) |
1300 |
}) |
|
1301 |
) |
|
1302 | ||
1303 | ! |
decorated_summary_table_q <- srv_decorate_teal_data( |
1304 | ! |
id = "dec_summary_table", |
1305 | ! |
data = summary_table_q, |
1306 | ! |
decorators = select_decorators(decorators, "table"), |
1307 | ! |
expr = quote(table) |
1308 |
) |
|
1309 | ||
1310 | ! |
decorated_by_subject_plot_q <- srv_decorate_teal_data( |
1311 | ! |
id = "dec_by_subject_plot", |
1312 | ! |
data = by_subject_plot_q, |
1313 | ! |
decorators = select_decorators(decorators, "by_subject_plot"), |
1314 | ! |
expr = quote(by_subject_plot) |
1315 |
) |
|
1316 | ||
1317 |
# Plots & tables reactives |
|
1318 | ||
1319 | ! |
summary_plot_r <- reactive({ |
1320 | ! |
req(decorated_summary_plot_q())[["summary_plot"]] |
1321 |
}) |
|
1322 | ||
1323 | ! |
combination_plot_r <- reactive({ |
1324 | ! |
req(decorated_combination_plot_q())[["combination_plot"]] |
1325 |
}) |
|
1326 | ||
1327 | ! |
summary_table_r <- reactive({ |
1328 | ! |
q <- req(decorated_summary_table_q()) |
1329 | ||
1330 | ! |
if (length(input$variables_select) == 0) { |
1331 |
# so that zeroRecords message gets printed |
|
1332 |
# using tibble as it supports weird column names, such as " " |
|
1333 | ! |
DT::datatable( |
1334 | ! |
tibble::tibble(` ` = logical(0)), |
1335 | ! |
options = list( |
1336 | ! |
language = list(zeroRecords = "No variable selected."), |
1337 | ! |
pageLength = input$levels_table_rows |
1338 |
) |
|
1339 |
) |
|
1340 |
} else { |
|
1341 | ! |
DT::datatable(q[["summary_data"]]) |
1342 |
} |
|
1343 |
}) |
|
1344 | ||
1345 | ! |
by_subject_plot_r <- reactive({ |
1346 | ! |
req(decorated_by_subject_plot_q()[["by_subject_plot"]]) |
1347 |
}) |
|
1348 | ||
1349 |
# Generate output |
|
1350 | ! |
pws1 <- teal.widgets::plot_with_settings_srv( |
1351 | ! |
id = "summary_plot", |
1352 | ! |
plot_r = summary_plot_r, |
1353 | ! |
height = plot_height, |
1354 | ! |
width = plot_width |
1355 |
) |
|
1356 | ||
1357 | ! |
pws2 <- teal.widgets::plot_with_settings_srv( |
1358 | ! |
id = "combination_plot", |
1359 | ! |
plot_r = combination_plot_r, |
1360 | ! |
height = plot_height, |
1361 | ! |
width = plot_width |
1362 |
) |
|
1363 | ||
1364 | ! |
output$levels_table <- DT::renderDataTable(summary_table_r()) |
1365 | ||
1366 | ! |
pws3 <- teal.widgets::plot_with_settings_srv( |
1367 | ! |
id = "by_subject_plot", |
1368 | ! |
plot_r = by_subject_plot_r, |
1369 | ! |
height = plot_height, |
1370 | ! |
width = plot_width |
1371 |
) |
|
1372 | ||
1373 | ! |
decorated_summary_plot_dims_q <- set_chunk_dims(pws1, decorated_summary_plot_q) |
1374 | ||
1375 | ! |
decorated_combination_plot_dims_q <- # nolint: object_length_linter. |
1376 | ! |
set_chunk_dims(pws2, decorated_combination_plot_q) |
1377 | ||
1378 | ! |
decorated_by_subject_plot_dims_q <- # nolint: object_length_linter. |
1379 | ! |
set_chunk_dims(pws3, decorated_by_subject_plot_q) |
1380 | ||
1381 | ! |
decorated_final_q <- reactive({ |
1382 | ! |
sum_type <- req(input$summary_type) |
1383 | ! |
if (sum_type == "Summary") { |
1384 | ! |
decorated_summary_plot_dims_q() |
1385 | ! |
} else if (sum_type == "Combinations") { |
1386 | ! |
decorated_combination_plot_dims_q() |
1387 | ! |
} else if (sum_type == "By Variable Levels") { |
1388 | ! |
decorated_summary_table_q() |
1389 | ! |
} else if (sum_type == "Grouped by Subject") { |
1390 | ! |
decorated_by_subject_plot_dims_q() |
1391 |
} |
|
1392 |
}) |
|
1393 | ||
1394 |
# Render R code. |
|
1395 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_final_q()))) |
1396 | ||
1397 | ! |
teal.widgets::verbatim_popup_srv( |
1398 | ! |
id = "rcode", |
1399 | ! |
verbatim_content = source_code_r, |
1400 | ! |
title = "Show R Code for Missing Data" |
1401 |
) |
|
1402 | ! |
decorated_final_q |
1403 |
}) |
|
1404 |
} |
1 |
#' `teal` module: Stack plots of variables and show association with reference variable |
|
2 |
#' |
|
3 |
#' Module provides functionality for visualizing the distribution of variables and |
|
4 |
#' their association with a reference variable. |
|
5 |
#' It supports configuring the appearance of the plots, including themes and whether to show associations. |
|
6 |
#' |
|
7 |
#' |
|
8 |
#' @note For more examples, please see the vignette "Using association plot" via |
|
9 |
#' `vignette("using-association-plot", package = "teal.modules.general")`. |
|
10 |
#' |
|
11 |
#' @inheritParams teal::module |
|
12 |
#' @inheritParams shared_params |
|
13 |
#' @param ref (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
14 |
#' Reference variable, must accepts a `data_extract_spec` with `select_spec(multiple = FALSE)` |
|
15 |
#' to ensure single selection option. |
|
16 |
#' @param vars (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
17 |
#' Variables to be associated with the reference variable. |
|
18 |
#' @param show_association (`logical`) optional, whether show association of `vars` |
|
19 |
#' with reference variable. Defaults to `TRUE`. |
|
20 |
#' @param distribution_theme,association_theme (`character`) optional, `ggplot2` themes to be used by default. |
|
21 |
#' Default to `"gray"`. |
|
22 |
#' |
|
23 |
#' @param ggplot2_args `r roxygen_ggplot2_args_param("Bivariate1", "Bivariate2")` |
|
24 |
#' |
|
25 |
#' @inherit shared_params return |
|
26 |
#' |
|
27 |
#' @section Decorating Module: |
|
28 |
#' |
|
29 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
30 |
#' - `plot` (`grob` created with [ggplot2::ggplotGrob()]) |
|
31 |
#' |
|
32 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
33 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
34 |
#' See code snippet below: |
|
35 |
#' |
|
36 |
#' ``` |
|
37 |
#' tm_g_association( |
|
38 |
#' ..., # arguments for module |
|
39 |
#' decorators = list( |
|
40 |
#' plot = teal_transform_module(...) # applied to the `plot` output |
|
41 |
#' ) |
|
42 |
#' ) |
|
43 |
#' ``` |
|
44 |
#' |
|
45 |
#' For additional details and examples of decorators, refer to the vignette |
|
46 |
#' `vignette("decorate-module-output", package = "teal.modules.general")`. |
|
47 |
#' |
|
48 |
#' To learn more please refer to the vignette |
|
49 |
#' `vignette("transform-module-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
50 |
#' |
|
51 |
#' @inheritSection teal::example_module Reporting |
|
52 |
#' |
|
53 |
#' @examplesShinylive |
|
54 |
#' library(teal.modules.general) |
|
55 |
#' interactive <- function() TRUE |
|
56 |
#' {{ next_example }} |
|
57 |
#' @examples |
|
58 |
#' # general data example |
|
59 |
#' data <- teal_data() |
|
60 |
#' data <- within(data, { |
|
61 |
#' require(nestcolor) |
|
62 |
#' CO2 <- CO2 |
|
63 |
#' factors <- names(Filter(isTRUE, vapply(CO2, is.factor, logical(1L)))) |
|
64 |
#' CO2[factors] <- lapply(CO2[factors], as.character) |
|
65 |
#' }) |
|
66 |
#' |
|
67 |
#' app <- init( |
|
68 |
#' data = data, |
|
69 |
#' modules = modules( |
|
70 |
#' tm_g_association( |
|
71 |
#' ref = data_extract_spec( |
|
72 |
#' dataname = "CO2", |
|
73 |
#' select = select_spec( |
|
74 |
#' label = "Select variable:", |
|
75 |
#' choices = variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment")), |
|
76 |
#' selected = "Plant", |
|
77 |
#' fixed = FALSE |
|
78 |
#' ) |
|
79 |
#' ), |
|
80 |
#' vars = data_extract_spec( |
|
81 |
#' dataname = "CO2", |
|
82 |
#' select = select_spec( |
|
83 |
#' label = "Select variables:", |
|
84 |
#' choices = variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment")), |
|
85 |
#' selected = "Treatment", |
|
86 |
#' multiple = TRUE, |
|
87 |
#' fixed = FALSE |
|
88 |
#' ) |
|
89 |
#' ) |
|
90 |
#' ) |
|
91 |
#' ) |
|
92 |
#' ) |
|
93 |
#' if (interactive()) { |
|
94 |
#' shinyApp(app$ui, app$server) |
|
95 |
#' } |
|
96 |
#' |
|
97 |
#' @examplesShinylive |
|
98 |
#' library(teal.modules.general) |
|
99 |
#' interactive <- function() TRUE |
|
100 |
#' {{ next_example }} |
|
101 |
#' @examples |
|
102 |
#' # CDISC data example |
|
103 |
#' data <- teal_data() |
|
104 |
#' data <- within(data, { |
|
105 |
#' require(nestcolor) |
|
106 |
#' ADSL <- teal.data::rADSL |
|
107 |
#' }) |
|
108 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
109 |
#' |
|
110 |
#' app <- init( |
|
111 |
#' data = data, |
|
112 |
#' modules = modules( |
|
113 |
#' tm_g_association( |
|
114 |
#' ref = data_extract_spec( |
|
115 |
#' dataname = "ADSL", |
|
116 |
#' select = select_spec( |
|
117 |
#' label = "Select variable:", |
|
118 |
#' choices = variable_choices( |
|
119 |
#' data[["ADSL"]], |
|
120 |
#' c("SEX", "RACE", "COUNTRY", "ARM", "STRATA1", "STRATA2", "ITTFL", "BMRKR2") |
|
121 |
#' ), |
|
122 |
#' selected = "RACE", |
|
123 |
#' fixed = FALSE |
|
124 |
#' ) |
|
125 |
#' ), |
|
126 |
#' vars = data_extract_spec( |
|
127 |
#' dataname = "ADSL", |
|
128 |
#' select = select_spec( |
|
129 |
#' label = "Select variables:", |
|
130 |
#' choices = variable_choices( |
|
131 |
#' data[["ADSL"]], |
|
132 |
#' c("SEX", "RACE", "COUNTRY", "ARM", "STRATA1", "STRATA2", "ITTFL", "BMRKR2") |
|
133 |
#' ), |
|
134 |
#' selected = "BMRKR2", |
|
135 |
#' multiple = TRUE, |
|
136 |
#' fixed = FALSE |
|
137 |
#' ) |
|
138 |
#' ) |
|
139 |
#' ) |
|
140 |
#' ) |
|
141 |
#' ) |
|
142 |
#' if (interactive()) { |
|
143 |
#' shinyApp(app$ui, app$server) |
|
144 |
#' } |
|
145 |
#' |
|
146 |
#' @export |
|
147 |
#' |
|
148 |
tm_g_association <- function(label = "Association", |
|
149 |
ref, |
|
150 |
vars, |
|
151 |
show_association = TRUE, |
|
152 |
plot_height = c(600, 400, 5000), |
|
153 |
plot_width = NULL, |
|
154 |
distribution_theme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), # nolint: line_length. |
|
155 |
association_theme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), # nolint: line_length. |
|
156 |
pre_output = NULL, |
|
157 |
post_output = NULL, |
|
158 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
159 |
transformators = list(), |
|
160 |
decorators = list()) { |
|
161 | ! |
message("Initializing tm_g_association") |
162 | ||
163 |
# Normalize the parameters |
|
164 | ! |
if (inherits(ref, "data_extract_spec")) ref <- list(ref) |
165 | ! |
if (inherits(vars, "data_extract_spec")) vars <- list(vars) |
166 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
167 | ||
168 |
# Start of assertions |
|
169 | ! |
checkmate::assert_string(label) |
170 | ||
171 | ! |
checkmate::assert_list(ref, types = "data_extract_spec") |
172 | ! |
if (!all(vapply(ref, function(x) !x$select$multiple, logical(1)))) { |
173 | ! |
stop("'ref' should not allow multiple selection") |
174 |
} |
|
175 | ||
176 | ! |
checkmate::assert_list(vars, types = "data_extract_spec") |
177 | ! |
checkmate::assert_flag(show_association) |
178 | ||
179 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
180 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
181 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
182 | ! |
checkmate::assert_numeric( |
183 | ! |
plot_width[1], |
184 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
185 |
) |
|
186 | ||
187 | ! |
distribution_theme <- match.arg(distribution_theme) |
188 | ! |
association_theme <- match.arg(association_theme) |
189 | ||
190 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
191 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
192 | ||
193 | ! |
plot_choices <- c("Bivariate1", "Bivariate2") |
194 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
195 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
196 | ||
197 | ! |
assert_decorators(decorators, "plot") |
198 |
# End of assertions |
|
199 | ||
200 |
# Make UI args |
|
201 | ! |
args <- as.list(environment()) |
202 | ||
203 | ! |
data_extract_list <- list( |
204 | ! |
ref = ref, |
205 | ! |
vars = vars |
206 |
) |
|
207 | ||
208 | ! |
ans <- module( |
209 | ! |
label = label, |
210 | ! |
server = srv_tm_g_association, |
211 | ! |
ui = ui_tm_g_association, |
212 | ! |
ui_args = args, |
213 | ! |
server_args = c( |
214 | ! |
data_extract_list, |
215 | ! |
list(plot_height = plot_height, plot_width = plot_width, ggplot2_args = ggplot2_args, decorators = decorators) |
216 |
), |
|
217 | ! |
transformators = transformators, |
218 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
219 |
) |
|
220 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
221 | ! |
ans |
222 |
} |
|
223 | ||
224 |
# UI function for the association module |
|
225 |
ui_tm_g_association <- function(id, ...) { |
|
226 | ! |
ns <- NS(id) |
227 | ! |
args <- list(...) |
228 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$ref, args$vars) |
229 | ||
230 | ! |
teal.widgets::standard_layout( |
231 | ! |
output = teal.widgets::white_small_well( |
232 | ! |
textOutput(ns("title")), |
233 | ! |
tags$br(), |
234 | ! |
teal.widgets::plot_with_settings_ui(id = ns("myplot")) |
235 |
), |
|
236 | ! |
encoding = tags$div( |
237 | ! |
tags$label("Encodings", class = "text-primary"), |
238 | ! |
teal.transform::datanames_input(args[c("ref", "vars")]), |
239 | ! |
teal.transform::data_extract_ui( |
240 | ! |
id = ns("ref"), |
241 | ! |
label = "Reference variable", |
242 | ! |
data_extract_spec = args$ref, |
243 | ! |
is_single_dataset = is_single_dataset_value |
244 |
), |
|
245 | ! |
teal.transform::data_extract_ui( |
246 | ! |
id = ns("vars"), |
247 | ! |
label = "Associated variables", |
248 | ! |
data_extract_spec = args$vars, |
249 | ! |
is_single_dataset = is_single_dataset_value |
250 |
), |
|
251 | ! |
checkboxInput( |
252 | ! |
ns("association"), |
253 | ! |
"Association with reference variable", |
254 | ! |
value = args$show_association |
255 |
), |
|
256 | ! |
checkboxInput( |
257 | ! |
ns("show_dist"), |
258 | ! |
"Scaled frequencies", |
259 | ! |
value = FALSE |
260 |
), |
|
261 | ! |
checkboxInput( |
262 | ! |
ns("log_transformation"), |
263 | ! |
"Log transformed", |
264 | ! |
value = FALSE |
265 |
), |
|
266 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")), |
267 | ! |
bslib::accordion( |
268 | ! |
open = TRUE, |
269 | ! |
bslib::accordion_panel( |
270 | ! |
title = "Plot settings", |
271 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("alpha"), "Scatterplot opacity:", c(0.5, 0, 1), ticks = FALSE), |
272 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("size"), "Scatterplot points size:", c(2, 1, 8), ticks = FALSE), |
273 | ! |
checkboxInput(ns("swap_axes"), "Swap axes", value = FALSE), |
274 | ! |
checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = FALSE), |
275 | ! |
selectInput( |
276 | ! |
inputId = ns("distribution_theme"), |
277 | ! |
label = "Distribution theme (by ggplot):", |
278 | ! |
choices = ggplot_themes, |
279 | ! |
selected = args$distribution_theme, |
280 | ! |
multiple = FALSE |
281 |
), |
|
282 | ! |
selectInput( |
283 | ! |
inputId = ns("association_theme"), |
284 | ! |
label = "Association theme (by ggplot):", |
285 | ! |
choices = ggplot_themes, |
286 | ! |
selected = args$association_theme, |
287 | ! |
multiple = FALSE |
288 |
) |
|
289 |
) |
|
290 |
) |
|
291 |
), |
|
292 | ! |
forms = tagList( |
293 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
294 |
), |
|
295 | ! |
pre_output = args$pre_output, |
296 | ! |
post_output = args$post_output |
297 |
) |
|
298 |
} |
|
299 | ||
300 |
# Server function for the association module |
|
301 |
srv_tm_g_association <- function(id, |
|
302 |
data, |
|
303 |
ref, |
|
304 |
vars, |
|
305 |
plot_height, |
|
306 |
plot_width, |
|
307 |
ggplot2_args, |
|
308 |
decorators) { |
|
309 | ! |
checkmate::assert_class(data, "reactive") |
310 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
311 | ||
312 | ! |
moduleServer(id, function(input, output, session) { |
313 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
314 | ||
315 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
316 | ! |
data_extract = list(ref = ref, vars = vars), |
317 | ! |
datasets = data, |
318 | ! |
select_validation_rule = list( |
319 | ! |
ref = shinyvalidate::compose_rules( |
320 | ! |
shinyvalidate::sv_required("A reference variable needs to be selected."), |
321 | ! |
~ if ((.) %in% selector_list()$vars()$select) { |
322 | ! |
"Associated variables and reference variable cannot overlap" |
323 |
} |
|
324 |
), |
|
325 | ! |
vars = shinyvalidate::compose_rules( |
326 | ! |
shinyvalidate::sv_required("An associated variable needs to be selected."), |
327 | ! |
~ if (length(selector_list()$ref()$select) != 0 && selector_list()$ref()$select %in% (.)) { |
328 | ! |
"Associated variables and reference variable cannot overlap" |
329 |
} |
|
330 |
) |
|
331 |
) |
|
332 |
) |
|
333 | ||
334 | ! |
iv_r <- reactive({ |
335 | ! |
iv <- shinyvalidate::InputValidator$new() |
336 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
337 |
}) |
|
338 | ||
339 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
340 | ! |
datasets = data, |
341 | ! |
selector_list = selector_list |
342 |
) |
|
343 | ||
344 | ! |
qenv <- reactive({ |
345 | ! |
obj <- data() |
346 | ! |
teal.reporter::teal_card(obj) <- |
347 | ! |
c( |
348 | ! |
teal.reporter::teal_card("# Association Plot"), |
349 | ! |
teal.reporter::teal_card(obj), |
350 | ! |
teal.reporter::teal_card("## Module's code") |
351 |
) |
|
352 | ! |
teal.code::eval_code(obj, 'library("ggplot2");library("dplyr");library("ggmosaic")') # nolint: quotes |
353 |
}) |
|
354 | ! |
anl_merged_q <- reactive({ |
355 | ! |
req(anl_merged_input()) |
356 | ! |
qenv() %>% teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
357 |
}) |
|
358 | ||
359 | ! |
merged <- list( |
360 | ! |
anl_input_r = anl_merged_input, |
361 | ! |
anl_q_r = anl_merged_q |
362 |
) |
|
363 | ||
364 | ! |
output_q <- reactive({ |
365 | ! |
teal::validate_inputs(iv_r()) |
366 | ||
367 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
368 | ! |
teal::validate_has_data(ANL, 3) |
369 | ||
370 | ! |
vars_names <- merged$anl_input_r()$columns_source$vars |
371 | ||
372 | ! |
ref_name <- as.vector(merged$anl_input_r()$columns_source$ref) |
373 | ! |
association <- input$association |
374 | ! |
show_dist <- input$show_dist |
375 | ! |
log_transformation <- input$log_transformation |
376 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
377 | ! |
swap_axes <- input$swap_axes |
378 | ! |
distribution_theme <- input$distribution_theme |
379 | ! |
association_theme <- input$association_theme |
380 | ||
381 | ! |
is_scatterplot <- is.numeric(ANL[[ref_name]]) && any(vapply(ANL[vars_names], is.numeric, logical(1))) |
382 | ! |
if (is_scatterplot) { |
383 | ! |
shinyjs::show("alpha") |
384 | ! |
shinyjs::show("size") |
385 | ! |
alpha <- input$alpha |
386 | ! |
size <- input$size |
387 |
} else { |
|
388 | ! |
shinyjs::hide("alpha") |
389 | ! |
shinyjs::hide("size") |
390 | ! |
alpha <- 0.5 |
391 | ! |
size <- 2 |
392 |
} |
|
393 | ||
394 | ! |
teal::validate_has_data(ANL[, c(ref_name, vars_names)], 3, complete = TRUE, allow_inf = FALSE) |
395 | ||
396 |
# reference |
|
397 | ! |
ref_class <- class(ANL[[ref_name]])[1] |
398 | ! |
if (is.numeric(ANL[[ref_name]]) && log_transformation) { |
399 |
# works for both integers and doubles |
|
400 | ! |
ref_cl_name <- call("log", as.name(ref_name)) |
401 | ! |
ref_cl_lbl <- varname_w_label(ref_name, ANL, prefix = "Log of ") |
402 |
} else { |
|
403 |
# silently ignore when non-numeric even if `log` is selected because some |
|
404 |
# variables may be numeric and others not |
|
405 | ! |
ref_cl_name <- as.name(ref_name) |
406 | ! |
ref_cl_lbl <- varname_w_label(ref_name, ANL) |
407 |
} |
|
408 | ||
409 | ! |
user_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
410 | ! |
user_plot = ggplot2_args[["Bivariate1"]], |
411 | ! |
user_default = ggplot2_args$default |
412 |
) |
|
413 | ||
414 | ! |
ref_call <- bivariate_plot_call( |
415 | ! |
data_name = "ANL", |
416 | ! |
x = ref_cl_name, |
417 | ! |
x_class = ref_class, |
418 | ! |
x_label = ref_cl_lbl, |
419 | ! |
freq = !show_dist, |
420 | ! |
theme = distribution_theme, |
421 | ! |
rotate_xaxis_labels = rotate_xaxis_labels, |
422 | ! |
swap_axes = FALSE, |
423 | ! |
size = size, |
424 | ! |
alpha = alpha, |
425 | ! |
ggplot2_args = user_ggplot2_args |
426 |
) |
|
427 | ||
428 |
# association |
|
429 | ! |
ref_class_cov <- ifelse(association, ref_class, "NULL") |
430 | ||
431 | ! |
var_calls <- lapply(vars_names, function(var_i) { |
432 | ! |
var_class <- class(ANL[[var_i]])[1] |
433 | ! |
if (is.numeric(ANL[[var_i]]) && log_transformation) { |
434 |
# works for both integers and doubles |
|
435 | ! |
var_cl_name <- call("log", as.name(var_i)) |
436 | ! |
var_cl_lbl <- varname_w_label(var_i, ANL, prefix = "Log of ") |
437 |
} else { |
|
438 |
# silently ignore when non-numeric even if `log` is selected because some |
|
439 |
# variables may be numeric and others not |
|
440 | ! |
var_cl_name <- as.name(var_i) |
441 | ! |
var_cl_lbl <- varname_w_label(var_i, ANL) |
442 |
} |
|
443 | ||
444 | ! |
user_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
445 | ! |
user_plot = ggplot2_args[["Bivariate2"]], |
446 | ! |
user_default = ggplot2_args$default |
447 |
) |
|
448 | ||
449 | ! |
bivariate_plot_call( |
450 | ! |
data_name = "ANL", |
451 | ! |
x = ref_cl_name, |
452 | ! |
y = var_cl_name, |
453 | ! |
x_class = ref_class_cov, |
454 | ! |
y_class = var_class, |
455 | ! |
x_label = ref_cl_lbl, |
456 | ! |
y_label = var_cl_lbl, |
457 | ! |
theme = association_theme, |
458 | ! |
freq = !show_dist, |
459 | ! |
rotate_xaxis_labels = rotate_xaxis_labels, |
460 | ! |
swap_axes = swap_axes, |
461 | ! |
alpha = alpha, |
462 | ! |
size = size, |
463 | ! |
ggplot2_args = user_ggplot2_args |
464 |
) |
|
465 |
}) |
|
466 | ||
467 |
# helper function to format variable name |
|
468 | ! |
format_varnames <- function(x) { |
469 | ! |
if (is.numeric(ANL[[x]]) && log_transformation) { |
470 | ! |
varname_w_label(x, ANL, prefix = "Log of ") |
471 |
} else { |
|
472 | ! |
varname_w_label(x, ANL) |
473 |
} |
|
474 |
} |
|
475 | ! |
new_title <- |
476 | ! |
if (association) { |
477 | ! |
switch(as.character(length(vars_names)), |
478 | ! |
"0" = sprintf("Value distribution for %s", ref_cl_lbl), |
479 | ! |
"1" = sprintf( |
480 | ! |
"Association between %s and %s", |
481 | ! |
ref_cl_lbl, |
482 | ! |
format_varnames(vars_names) |
483 |
), |
|
484 | ! |
sprintf( |
485 | ! |
"Associations between %s and: %s", |
486 | ! |
ref_cl_lbl, |
487 | ! |
paste(lapply(vars_names, format_varnames), collapse = ", ") |
488 |
) |
|
489 |
) |
|
490 |
} else { |
|
491 | ! |
switch(as.character(length(vars_names)), |
492 | ! |
"0" = sprintf("Value distribution for %s", ref_cl_lbl), |
493 | ! |
sprintf( |
494 | ! |
"Value distributions for %s and %s", |
495 | ! |
ref_cl_lbl, |
496 | ! |
paste(lapply(vars_names, format_varnames), collapse = ", ") |
497 |
) |
|
498 |
) |
|
499 |
} |
|
500 | ! |
obj <- merged$anl_q_r() |
501 | ! |
teal.reporter::teal_card(obj) <- c(teal.reporter::teal_card(obj), "## Plot") |
502 | ! |
teal.code::eval_code( |
503 | ! |
obj, |
504 | ! |
substitute( |
505 | ! |
expr = title <- new_title, |
506 | ! |
env = list(new_title = new_title) |
507 |
) |
|
508 |
) %>% |
|
509 | ! |
teal.code::eval_code( |
510 | ! |
substitute( |
511 | ! |
expr = { |
512 | ! |
plots <- plot_calls |
513 | ! |
plot <- gridExtra::arrangeGrob(plots[[1]], plots[[2]], ncol = 1) |
514 |
}, |
|
515 | ! |
env = list( |
516 | ! |
plot_calls = do.call( |
517 | ! |
"call", |
518 | ! |
c(list("list", ref_call), var_calls), |
519 | ! |
quote = TRUE |
520 |
) |
|
521 |
) |
|
522 |
) |
|
523 |
) |
|
524 |
}) |
|
525 | ||
526 | ! |
decorated_output_grob_q <- srv_decorate_teal_data( |
527 | ! |
id = "decorator", |
528 | ! |
data = output_q, |
529 | ! |
decorators = select_decorators(decorators, "plot"), |
530 | ! |
expr = quote({ |
531 | ! |
grid::grid.newpage() |
532 | ! |
grid::grid.draw(plot) |
533 |
}) |
|
534 |
) |
|
535 | ||
536 | ! |
plot_r <- reactive({ |
537 | ! |
req(iv_r()$is_valid()) |
538 | ! |
req(decorated_output_grob_q())[["plot"]] |
539 |
}) |
|
540 | ||
541 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
542 | ! |
id = "myplot", |
543 | ! |
plot_r = plot_r, |
544 | ! |
height = plot_height, |
545 | ! |
width = plot_width |
546 |
) |
|
547 | ||
548 | ! |
decorated_output_dims_q <- set_chunk_dims(pws, decorated_output_grob_q) |
549 | ||
550 | ! |
output$title <- renderText(output_q()[["title"]]) |
551 | ||
552 |
# Render R code. |
|
553 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_output_dims_q()))) |
554 | ||
555 | ! |
teal.widgets::verbatim_popup_srv( |
556 | ! |
id = "rcode", |
557 | ! |
verbatim_content = source_code_r, |
558 | ! |
title = "Association Plot" |
559 |
) |
|
560 | ! |
decorated_output_dims_q |
561 |
}) |
|
562 |
} |
1 |
#' Shared parameters documentation |
|
2 |
#' |
|
3 |
#' Defines common arguments shared across multiple functions in the package |
|
4 |
#' to avoid repetition by using `inheritParams`. |
|
5 |
#' |
|
6 |
#' @param plot_height (`numeric`) optional, specifies the plot height as a three-element vector of |
|
7 |
#' `value`, `min`, and `max` intended for use with a slider UI element. |
|
8 |
#' @param plot_width (`numeric`) optional, specifies the plot width as a three-element vector of |
|
9 |
#' `value`, `min`, and `max` for a slider encoding the plot width. |
|
10 |
#' @param rotate_xaxis_labels (`logical`) optional, whether to rotate plot X axis labels. Does not |
|
11 |
#' rotate by default (`FALSE`). |
|
12 |
#' @param ggtheme (`character`) optional, `ggplot2` theme to be used by default. Defaults to `"gray"`. |
|
13 |
#' @param ggplot2_args (`ggplot2_args`) object created by [teal.widgets::ggplot2_args()] |
|
14 |
#' with settings for the module plot. |
|
15 |
#' The argument is merged with options variable `teal.ggplot2_args` and default module setup. |
|
16 |
#' |
|
17 |
#' For more details see the vignette: `vignette("custom-ggplot2-arguments", package = "teal.widgets")` |
|
18 |
#' @param basic_table_args (`basic_table_args`) object created by [teal.widgets::basic_table_args()] |
|
19 |
#' with settings for the module table. |
|
20 |
#' The argument is merged with options variable `teal.basic_table_args` and default module setup. |
|
21 |
#' |
|
22 |
#' For more details see the vignette: `vignette("custom-basic-table-arguments", package = "teal.widgets")` |
|
23 |
#' @param pre_output (`shiny.tag`) optional, text or UI element to be displayed before the module's output, |
|
24 |
#' providing context or a title. |
|
25 |
#' with text placed before the output to put the output into context. For example a title. |
|
26 |
#' @param post_output (`shiny.tag`) optional, text or UI element to be displayed after the module's output, |
|
27 |
#' adding context or further instructions. Elements like `shiny::helpText()` are useful. |
|
28 |
#' @param alpha (`integer(1)` or `integer(3)`) optional, specifies point opacity. |
|
29 |
#' - When the length of `alpha` is one: the plot points will have a fixed opacity. |
|
30 |
#' - When the length of `alpha` is three: the plot points opacity are dynamically adjusted based on |
|
31 |
#' vector of `value`, `min`, and `max`. |
|
32 |
#' @param size (`integer(1)` or `integer(3)`) optional, specifies point size. |
|
33 |
#' - When the length of `size` is one: the plot point sizes will have a fixed size. |
|
34 |
#' - When the length of `size` is three: the plot points size are dynamically adjusted based on |
|
35 |
#' vector of `value`, `min`, and `max`. |
|
36 |
#' @param decorators `r lifecycle::badge("experimental")` |
|
37 |
#' (named `list` of lists of `teal_transform_module`) optional, |
|
38 |
#' decorator for tables or plots included in the module output reported. |
|
39 |
#' The decorators are applied to the respective output objects. |
|
40 |
#' |
|
41 |
#' See section "Decorating Module" below for more details. |
|
42 |
#' |
|
43 |
#' @return Object of class `teal_module` to be used in `teal` applications. |
|
44 |
#' |
|
45 |
#' @name shared_params |
|
46 |
#' @keywords internal |
|
47 |
NULL |
|
48 | ||
49 |
#' Add labels for facets to a `ggplot2` object |
|
50 |
#' |
|
51 |
#' Enhances a `ggplot2` plot by adding labels that describe |
|
52 |
#' the faceting variables along the x and y axes. |
|
53 |
#' |
|
54 |
#' @param p (`ggplot2`) object to which facet labels will be added. |
|
55 |
#' @param xfacet_label (`character`) Label for the facet along the x-axis. |
|
56 |
#' If `NULL`, no label is added. If a vector, labels are joined with " & ". |
|
57 |
#' @param yfacet_label (`character`) Label for the facet along the y-axis. |
|
58 |
#' Similar behavior to `xfacet_label`. |
|
59 |
#' |
|
60 |
#' @return Returns `grid` or `grob` object (to be drawn with `grid.draw`) |
|
61 |
#' |
|
62 |
#' @examples |
|
63 |
#' library(ggplot2) |
|
64 |
#' library(grid) |
|
65 |
#' |
|
66 |
#' p <- ggplot(mtcars) + |
|
67 |
#' aes(x = mpg, y = disp) + |
|
68 |
#' geom_point() + |
|
69 |
#' facet_grid(gear ~ cyl) |
|
70 |
#' |
|
71 |
#' xfacet_label <- "cylinders" |
|
72 |
#' yfacet_label <- "gear" |
|
73 |
#' res <- add_facet_labels(p, xfacet_label, yfacet_label) |
|
74 |
#' grid.newpage() |
|
75 |
#' grid.draw(res) |
|
76 |
#' |
|
77 |
#' grid.newpage() |
|
78 |
#' grid.draw(add_facet_labels(p, xfacet_label = NULL, yfacet_label)) |
|
79 |
#' grid.newpage() |
|
80 |
#' grid.draw(add_facet_labels(p, xfacet_label, yfacet_label = NULL)) |
|
81 |
#' grid.newpage() |
|
82 |
#' grid.draw(add_facet_labels(p, xfacet_label = NULL, yfacet_label = NULL)) |
|
83 |
#' |
|
84 |
#' @export |
|
85 |
#' |
|
86 |
add_facet_labels <- function(p, xfacet_label = NULL, yfacet_label = NULL) { |
|
87 | ! |
checkmate::assert_class(p, classes = "ggplot") |
88 | ! |
checkmate::assert_character(xfacet_label, null.ok = TRUE, min.len = 1) |
89 | ! |
checkmate::assert_character(yfacet_label, null.ok = TRUE, min.len = 1) |
90 | ! |
if (is.null(xfacet_label) && is.null(yfacet_label)) { |
91 | ! |
return(ggplot2::ggplotGrob(p)) |
92 |
} |
|
93 | ! |
grid::grid.grabExpr({ |
94 | ! |
g <- ggplot2::ggplotGrob(p) |
95 | ||
96 |
# we are going to replace these, so we make sure they have nothing in them |
|
97 | ! |
checkmate::assert_class(g$grobs[[grep("xlab-t", g$layout$name, fixed = TRUE)]], "zeroGrob") |
98 | ! |
checkmate::assert_class(g$grobs[[grep("ylab-r", g$layout$name, fixed = TRUE)]], "zeroGrob") |
99 | ||
100 | ! |
xaxis_label_grob <- g$grobs[[grep("xlab-b", g$layout$name, fixed = TRUE)]] |
101 | ! |
xaxis_label_grob$children[[1]]$label <- paste(xfacet_label, collapse = " & ") |
102 | ! |
yaxis_label_grob <- g$grobs[[grep("ylab-l", g$layout$name, fixed = TRUE)]] |
103 | ! |
yaxis_label_grob$children[[1]]$label <- paste(yfacet_label, collapse = " & ") |
104 | ! |
yaxis_label_grob$children[[1]]$rot <- 270 |
105 | ||
106 | ! |
top_height <- if (is.null(xfacet_label)) 0 else grid::unit(2, "line") |
107 | ! |
right_width <- if (is.null(yfacet_label)) 0 else grid::unit(2, "line") |
108 | ||
109 | ! |
grid::grid.newpage() |
110 | ! |
grid::pushViewport(grid::plotViewport(margins = c(0, 0, top_height, right_width), name = "ggplot")) |
111 | ! |
grid::grid.draw(g) |
112 | ! |
grid::upViewport(1) |
113 | ||
114 |
# draw x facet |
|
115 | ! |
if (!is.null(xfacet_label)) { |
116 | ! |
grid::pushViewport(grid::viewport( |
117 | ! |
x = 0, y = grid::unit(1, "npc") - top_height, width = grid::unit(1, "npc"), |
118 | ! |
height = top_height, just = c("left", "bottom"), name = "topxaxis" |
119 |
)) |
|
120 | ! |
grid::grid.draw(xaxis_label_grob) |
121 | ! |
grid::upViewport(1) |
122 |
} |
|
123 | ||
124 |
# draw y facet |
|
125 | ! |
if (!is.null(yfacet_label)) { |
126 | ! |
grid::pushViewport(grid::viewport( |
127 | ! |
x = grid::unit(1, "npc") - grid::unit(as.numeric(right_width) / 2, "line"), y = 0, width = right_width, |
128 | ! |
height = grid::unit(1, "npc"), just = c("left", "bottom"), name = "rightyaxis" |
129 |
)) |
|
130 | ! |
grid::grid.draw(yaxis_label_grob) |
131 | ! |
grid::upViewport(1) |
132 |
} |
|
133 |
}) |
|
134 |
} |
|
135 | ||
136 |
#' Call a function with a character vector for the `...` argument |
|
137 |
#' |
|
138 |
#' @param fun (`character`) Name of a function where the `...` argument shall be replaced by values from `str_args`. |
|
139 |
#' @param str_args (`character`) A character vector that the function shall be executed with |
|
140 |
#' |
|
141 |
#' @return |
|
142 |
#' Value of call to `fun` with arguments specified in `str_args`. |
|
143 |
#' |
|
144 |
#' @keywords internal |
|
145 |
call_fun_dots <- function(fun, str_args) { |
|
146 | ! |
do.call("call", c(list(fun), lapply(str_args, as.name)), quote = TRUE) |
147 |
} |
|
148 | ||
149 |
#' Generate a string for a variable including its label |
|
150 |
#' |
|
151 |
#' @param var_names (`character`) Name of variable to extract labels from. |
|
152 |
#' @param dataset (`dataset`) Name of analysis dataset. |
|
153 |
#' @param prefix,suffix (`character`) String to paste to the beginning/end of the variable name with label. |
|
154 |
#' @param wrap_width (`numeric`) Number of characters to wrap original label to. Defaults to 80. |
|
155 |
#' |
|
156 |
#' @return (`character`) String with variable name and label. |
|
157 |
#' |
|
158 |
#' @keywords internal |
|
159 |
#' |
|
160 |
varname_w_label <- function(var_names, |
|
161 |
dataset, |
|
162 |
wrap_width = 80, |
|
163 |
prefix = NULL, |
|
164 |
suffix = NULL) { |
|
165 | ! |
add_label <- function(var_names) { |
166 | ! |
label <- vapply( |
167 | ! |
dataset[var_names], function(x) { |
168 | ! |
attr_label <- attr(x, "label") |
169 | ! |
`if`(is.null(attr_label), "", attr_label) |
170 |
}, |
|
171 | ! |
character(1) |
172 |
) |
|
173 | ||
174 | ! |
if (length(label) == 1 && !is.na(label) && !identical(label, "")) { |
175 | ! |
paste0(prefix, label, " [", var_names, "]", suffix) |
176 |
} else { |
|
177 | ! |
var_names |
178 |
} |
|
179 |
} |
|
180 | ||
181 | ! |
if (length(var_names) < 1) { |
182 | ! |
NULL |
183 | ! |
} else if (length(var_names) == 1) { |
184 | ! |
stringr::str_wrap(add_label(var_names), width = wrap_width) |
185 | ! |
} else if (length(var_names) > 1) { |
186 | ! |
stringr::str_wrap(vapply(var_names, add_label, character(1)), width = wrap_width) |
187 |
} |
|
188 |
} |
|
189 | ||
190 |
# see vignette("ggplot2-specs", package="ggplot2") |
|
191 |
shape_names <- c( |
|
192 |
"circle", paste("circle", c("open", "filled", "cross", "plus", "small")), "bullet", |
|
193 |
"square", paste("square", c("open", "filled", "cross", "plus", "triangle")), |
|
194 |
"diamond", paste("diamond", c("open", "filled", "plus")), |
|
195 |
"triangle", paste("triangle", c("open", "filled", "square")), |
|
196 |
paste("triangle down", c("open", "filled")), |
|
197 |
"plus", "cross", "asterisk" |
|
198 |
) |
|
199 | ||
200 |
#' Get icons to represent variable types in dataset |
|
201 |
#' |
|
202 |
#' @param var_type (`character`) of R internal types (classes). |
|
203 |
#' @return (`character`) vector of HTML icons corresponding to data type in each column. |
|
204 |
#' @keywords internal |
|
205 |
variable_type_icons <- function(var_type) { |
|
206 | ! |
checkmate::assert_character(var_type, any.missing = FALSE) |
207 | ||
208 | ! |
class_to_icon <- list( |
209 | ! |
numeric = "arrow-up-1-9", |
210 | ! |
integer = "arrow-up-1-9", |
211 | ! |
logical = "pause", |
212 | ! |
Date = "calendar", |
213 | ! |
POSIXct = "calendar", |
214 | ! |
POSIXlt = "calendar", |
215 | ! |
factor = "chart-bar", |
216 | ! |
character = "keyboard", |
217 | ! |
primary_key = "key", |
218 | ! |
unknown = "circle-question" |
219 |
) |
|
220 | ! |
class_to_icon <- lapply(class_to_icon, function(icon_name) toString(icon(icon_name, lib = "font-awesome"))) |
221 | ||
222 | ! |
unname(vapply( |
223 | ! |
var_type, |
224 | ! |
FUN.VALUE = character(1), |
225 | ! |
FUN = function(class) { |
226 | ! |
if (class == "") { |
227 | ! |
class |
228 | ! |
} else if (is.null(class_to_icon[[class]])) { |
229 | ! |
class_to_icon[["unknown"]] |
230 |
} else { |
|
231 | ! |
class_to_icon[[class]] |
232 |
} |
|
233 |
} |
|
234 |
)) |
|
235 |
} |
|
236 | ||
237 |
#' |
|
238 |
#' @param id (`character(1)`) the id of the tab panel with tabs. |
|
239 |
#' @param name (`character(1)`) the name of the tab. |
|
240 |
#' @return JavaScript expression to be used in `shiny::conditionalPanel()` to determine |
|
241 |
#' if the specified tab is active. |
|
242 |
#' @keywords internal |
|
243 |
#' |
|
244 |
is_tab_active_js <- function(id, name) { |
|
245 |
# supporting the bs3 and higher version at the same time |
|
246 | ! |
sprintf( |
247 | ! |
"$(\"#%1$s > li.active\").text().trim() == '%2$s' || $(\"#%1$s > li a.active\").text().trim() == '%2$s'", |
248 | ! |
id, name |
249 |
) |
|
250 |
} |
|
251 | ||
252 |
#' Assert single selection on `data_extract_spec` object |
|
253 |
#' Helper to reduce code in assertions |
|
254 |
#' @noRd |
|
255 |
#' |
|
256 |
assert_single_selection <- function(x, |
|
257 |
.var.name = checkmate::vname(x)) { # nolint: object_name. |
|
258 | 104x |
if (any(vapply(x, function(.x) .x$select$multiple, logical(1)))) { |
259 | 4x |
stop("'", .var.name, "' should not allow multiple selection") |
260 |
} |
|
261 | 100x |
invisible(TRUE) |
262 |
} |
|
263 | ||
264 |
#' Wrappers around `srv_transform_teal_data` that allows to decorate the data |
|
265 |
#' @inheritParams teal::srv_transform_teal_data |
|
266 |
#' @inheritParams teal.reporter::`eval_code,teal_report-method` |
|
267 |
#' @param expr (`reactive`) with expression to evaluate on the output of the |
|
268 |
#' decoration. It must be compatible with `code` argument of [teal.code::eval_code()]. |
|
269 |
#' Default is `NULL` which won't evaluate any appending code. |
|
270 |
#' @details |
|
271 |
#' `srv_decorate_teal_data` is a wrapper around `srv_transform_teal_data` that |
|
272 |
#' allows to decorate the data with additional expressions. |
|
273 |
#' When original `teal_data` object is in error state, it will show that error |
|
274 |
#' first. |
|
275 |
#' |
|
276 |
#' @keywords internal |
|
277 |
srv_decorate_teal_data <- function(id, data, decorators, expr) { |
|
278 | ! |
checkmate::assert_class(data, classes = "reactive") |
279 | ! |
checkmate::assert_list(decorators, "teal_transform_module") |
280 | ||
281 | ! |
no_expr <- missing(expr) |
282 | ||
283 | ! |
moduleServer(id, function(input, output, session) { |
284 | ! |
decorated_output <- srv_transform_teal_data("inner", data = data, transformators = decorators) |
285 | ||
286 | ! |
expr_r <- if (is.reactive(expr)) expr else reactive(expr) |
287 | ||
288 | ! |
reactive({ |
289 | ! |
req(decorated_output()) |
290 | ! |
if (no_expr) { |
291 | ! |
decorated_output() |
292 |
} else { |
|
293 | ! |
teal.code::eval_code(decorated_output(), expr_r()) |
294 |
} |
|
295 |
}) |
|
296 |
}) |
|
297 |
} |
|
298 | ||
299 |
#' @rdname srv_decorate_teal_data |
|
300 |
#' @details |
|
301 |
#' `ui_decorate_teal_data` is a wrapper around `ui_transform_teal_data`. |
|
302 |
#' @keywords internal |
|
303 |
ui_decorate_teal_data <- function(id, decorators, ...) { |
|
304 | ! |
teal::ui_transform_teal_data(NS(id, "inner"), transformators = decorators, ...) |
305 |
} |
|
306 | ||
307 |
#' Internal function to check if decorators is a valid object |
|
308 |
#' @noRd |
|
309 |
check_decorators <- function(x, names = NULL) { # nolint: object_name. |
|
310 | ||
311 | 5x |
check_message <- checkmate::check_list(x, names = "named") |
312 | ||
313 | 5x |
if (!is.null(names)) { |
314 | 5x |
if (isTRUE(check_message)) { |
315 | 5x |
if (length(names(x)) != length(unique(names(x)))) { |
316 | ! |
check_message <- sprintf( |
317 | ! |
"The `decorators` must contain unique names from these names: %s.", |
318 | ! |
paste(names, collapse = ", ") |
319 |
) |
|
320 |
} |
|
321 |
} else { |
|
322 | ! |
check_message <- sprintf( |
323 | ! |
"The `decorators` must be a named list from these names: %s.", |
324 | ! |
paste(names, collapse = ", ") |
325 |
) |
|
326 |
} |
|
327 |
} |
|
328 | ||
329 | 5x |
if (!isTRUE(check_message)) { |
330 | ! |
return(check_message) |
331 |
} |
|
332 | ||
333 | 5x |
valid_elements <- vapply( |
334 | 5x |
x, |
335 | 5x |
checkmate::test_class, |
336 | 5x |
classes = "teal_transform_module", |
337 | 5x |
FUN.VALUE = logical(1L) |
338 |
) |
|
339 | ||
340 | 5x |
if (all(valid_elements)) { |
341 | 5x |
return(TRUE) |
342 |
} |
|
343 | ||
344 | ! |
"Make sure that the named list contains 'teal_transform_module' objects created using `teal_transform_module()`." |
345 |
} |
|
346 |
#' Internal assertion on decorators |
|
347 |
#' @noRd |
|
348 |
assert_decorators <- checkmate::makeAssertionFunction(check_decorators) |
|
349 | ||
350 |
#' Subset decorators based on the scope |
|
351 |
#' |
|
352 |
#' @param scope (`character`) a character vector of decorator names to include. |
|
353 |
#' @param decorators (named `list`) of list decorators to subset. |
|
354 |
#' |
|
355 |
#' @return Subsetted list with all decorators to include. |
|
356 |
#' It can be an empty list if none of the scope exists in `decorators` argument. |
|
357 |
#' @keywords internal |
|
358 |
select_decorators <- function(decorators, scope) { |
|
359 | ! |
checkmate::assert_character(scope, null.ok = TRUE) |
360 | ! |
if (scope %in% names(decorators)) { |
361 | ! |
decorators[scope] |
362 |
} else { |
|
363 | ! |
list() |
364 |
} |
|
365 |
} |
|
366 | ||
367 |
#' Set the attributes of the last chunk outputs |
|
368 |
#' @param teal_card (`teal_card`) object to modify. |
|
369 |
#' @param attributes (`list`) of attributes to set on the last chunk outputs. |
|
370 |
#' @param n (`integer(1)`) number of the last element of `teal_card` to modify. |
|
371 |
#' it will only change `chunk_output` objects. |
|
372 |
#' @param inner_classes (`character`) classes within `chunk_output` that should be modified. |
|
373 |
#' This can be used to only change `recordedplot`, `ggplot2` or other type of objects. |
|
374 |
#' @keywords internal |
|
375 |
set_chunk_attrs <- function(teal_card, |
|
376 |
attributes, |
|
377 |
n = 1, |
|
378 |
inner_classes = NULL, |
|
379 |
quiet = FALSE) { |
|
380 | 7x |
checkmate::assert_class(teal_card, "teal_card") |
381 | 7x |
checkmate::assert_list(attributes, names = "unique") |
382 | 7x |
checkmate::assert_int(n, lower = 1) |
383 | 7x |
checkmate::assert_character(inner_classes, null.ok = TRUE) |
384 | 7x |
checkmate::assert_flag(quiet) |
385 | ||
386 | 7x |
if (!inherits(teal_card[[length(teal_card)]], "chunk_output")) { |
387 | 1x |
if (!quiet) { |
388 | 1x |
warning("The last element of the `teal_card` is not a `chunk_output` object. No attributes were modified.") |
389 |
} |
|
390 | 1x |
return(teal_card) |
391 |
} |
|
392 | ||
393 | 6x |
for (ix in seq_len(length(teal_card))) { |
394 | 14x |
if (ix > n) { |
395 | 4x |
break |
396 |
} |
|
397 | 10x |
current_ix <- length(teal_card) + 1 - ix |
398 | 10x |
if (!inherits(teal_card[[current_ix]], "chunk_output")) { |
399 | 2x |
if (!quiet) { |
400 | 1x |
warning( |
401 | 1x |
"The ", ix, |
402 | 1x |
" to last element of the `teal_card` is not a `chunk_output` object. Skipping any further modifications." |
403 |
) |
|
404 |
} |
|
405 | 2x |
return(teal_card) |
406 |
} |
|
407 | ||
408 | 8x |
if (length(inner_classes) > 0 && !checkmate::test_multi_class(teal_card[[current_ix]][[1]], inner_classes)) { |
409 | 1x |
next |
410 |
} |
|
411 | ||
412 | 7x |
attributes(teal_card[[current_ix]]) <- utils::modifyList( |
413 | 7x |
attributes(teal_card[[current_ix]]), |
414 | 7x |
attributes |
415 |
) |
|
416 |
} |
|
417 | ||
418 | 4x |
teal_card |
419 |
} |
|
420 | ||
421 |
#' Create a reactive that sets plot dimensions on a `teal_card` |
|
422 |
#' |
|
423 |
#' This is a convenience function that creates a reactive expression that |
|
424 |
#' automatically sets the `dev.width` and `dev.height` attributes on the last |
|
425 |
#' chunk outputs of a `teal_card` based on plot dimensions from a plot widget. |
|
426 |
#' |
|
427 |
#' @param pws (`plot_widget`) plot widget that provides dimensions via `dim()` method |
|
428 |
#' @param q_r (`reactive`) reactive expression that returns a `teal_reporter` |
|
429 |
#' @param inner_classes (`character`) classes within `chunk_output` that should be modified. |
|
430 |
#' This can be used to only change `recordedplot`, `ggplot2` or other type of objects. |
|
431 |
#' |
|
432 |
#' @return A reactive expression that returns the `teal_card` with updated dimensions |
|
433 |
#' |
|
434 |
#' @keywords internal |
|
435 |
set_chunk_dims <- function(pws, q_r, inner_classes = NULL) { |
|
436 | 1x |
checkmate::assert_list(pws) |
437 | 1x |
checkmate::assert_names(names(pws), must.include = "dim") |
438 | 1x |
checkmate::assert_class(pws$dim, "reactive") |
439 | 1x |
checkmate::assert_class(q_r, "reactive") |
440 | 1x |
checkmate::assert_character(inner_classes, null.ok = TRUE) |
441 | ||
442 | 1x |
reactive({ |
443 | 1x |
pws_dim <- stats::setNames(as.list(req(pws$dim())), c("width", "height")) |
444 | 1x |
if (identical(pws_dim$width, "auto")) { # ignore non-numeric values (such as "auto") |
445 | 1x |
pws_dim$width <- NULL |
446 |
} |
|
447 | 1x |
if (identical(pws_dim$height, "auto")) { # ignore non-numeric values (such as "auto") |
448 | ! |
pws_dim$height <- NULL |
449 |
} |
|
450 | 1x |
q <- req(q_r()) |
451 | 1x |
teal.reporter::teal_card(q) <- set_chunk_attrs( |
452 | 1x |
teal.reporter::teal_card(q), |
453 | 1x |
list(dev.width = pws_dim$width, dev.height = pws_dim$height), |
454 | 1x |
inner_classes = inner_classes |
455 |
) |
|
456 | 1x |
q |
457 |
}) |
|
458 |
} |
1 |
#' `teal` module: Cross-table |
|
2 |
#' |
|
3 |
#' Generates a simple cross-table of two variables from a dataset with custom |
|
4 |
#' options for showing percentages and sub-totals. |
|
5 |
#' |
|
6 |
#' @inheritParams teal::module |
|
7 |
#' @inheritParams shared_params |
|
8 |
#' @param x (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
9 |
#' Object with all available choices with pre-selected option for variable X - row values. |
|
10 |
#' In case of `data_extract_spec` use `select_spec(..., ordered = TRUE)` if table elements should be |
|
11 |
#' rendered according to selection order. |
|
12 |
#' @param y (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
13 |
#' Object with all available choices with pre-selected option for variable Y - column values. |
|
14 |
#' |
|
15 |
#' `data_extract_spec` must not allow multiple selection in this case. |
|
16 |
#' @param show_percentage (`logical(1)`) |
|
17 |
#' Indicates whether to show percentages (relevant only when `x` is a `factor`). |
|
18 |
#' Defaults to `TRUE`. |
|
19 |
#' @param show_total (`logical(1)`) |
|
20 |
#' Indicates whether to show total column. |
|
21 |
#' Defaults to `TRUE`. |
|
22 |
#' @param remove_zero_columns (`logical(1)`) |
|
23 |
#' Indicates whether to remove columns that contain only zeros from the output table. |
|
24 |
#' Defaults to `FALSE`. |
|
25 |
#' |
|
26 |
#' @note For more examples, please see the vignette "Using cross table" via |
|
27 |
#' `vignette("using-cross-table", package = "teal.modules.general")`. |
|
28 |
#' |
|
29 |
#' @inherit shared_params return |
|
30 |
#' |
|
31 |
#' @section Table Settings: |
|
32 |
#' The module provides several table settings that can be adjusted: |
|
33 |
#' \itemize{ |
|
34 |
#' \item \code{Show column percentage}: Shows column percentages when enabled |
|
35 |
#' \item \code{Show total column}: Shows a total column when enabled |
|
36 |
#' \item \code{Remove zero-only columns}: Removes columns that contain only zeros from the output table |
|
37 |
#' } |
|
38 |
#' |
|
39 |
#' @section Decorating Module: |
|
40 |
#' |
|
41 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
42 |
#' - `table` (`ElementaryTable` - output of `rtables::build_table`) |
|
43 |
#' |
|
44 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
45 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
46 |
#' See code snippet below: |
|
47 |
#' |
|
48 |
#' ``` |
|
49 |
#' tm_t_crosstable( |
|
50 |
#' ..., # arguments for module |
|
51 |
#' decorators = list( |
|
52 |
#' table = teal_transform_module(...) # applied to the `table` output |
|
53 |
#' ) |
|
54 |
#' ) |
|
55 |
#' ``` |
|
56 |
#' For additional details and examples of decorators, refer to the vignette |
|
57 |
#' `vignette("decorate-module-output", package = "teal.modules.general")`. |
|
58 |
#' |
|
59 |
#' To learn more please refer to the vignette |
|
60 |
#' `vignette("transform-module-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
61 |
#' |
|
62 |
#' @inheritSection teal::example_module Reporting |
|
63 |
#' |
|
64 |
#' @examplesShinylive |
|
65 |
#' library(teal.modules.general) |
|
66 |
#' interactive <- function() TRUE |
|
67 |
#' {{ next_example }} |
|
68 |
#' @examples |
|
69 |
#' # general data example |
|
70 |
#' data <- teal_data() |
|
71 |
#' data <- within(data, { |
|
72 |
#' mtcars <- mtcars |
|
73 |
#' for (v in c("cyl", "vs", "am", "gear")) { |
|
74 |
#' mtcars[[v]] <- as.factor(mtcars[[v]]) |
|
75 |
#' } |
|
76 |
#' mtcars[["primary_key"]] <- seq_len(nrow(mtcars)) |
|
77 |
#' }) |
|
78 |
#' join_keys(data) <- join_keys(join_key("mtcars", "mtcars", "primary_key")) |
|
79 |
#' |
|
80 |
#' app <- init( |
|
81 |
#' data = data, |
|
82 |
#' modules = modules( |
|
83 |
#' tm_t_crosstable( |
|
84 |
#' label = "Cross Table", |
|
85 |
#' x = data_extract_spec( |
|
86 |
#' dataname = "mtcars", |
|
87 |
#' select = select_spec( |
|
88 |
#' label = "Select variable:", |
|
89 |
#' choices = variable_choices(data[["mtcars"]], c("cyl", "vs", "am", "gear")), |
|
90 |
#' selected = c("cyl", "gear"), |
|
91 |
#' multiple = TRUE, |
|
92 |
#' ordered = TRUE, |
|
93 |
#' fixed = FALSE |
|
94 |
#' ) |
|
95 |
#' ), |
|
96 |
#' y = data_extract_spec( |
|
97 |
#' dataname = "mtcars", |
|
98 |
#' select = select_spec( |
|
99 |
#' label = "Select variable:", |
|
100 |
#' choices = variable_choices(data[["mtcars"]], c("cyl", "vs", "am", "gear")), |
|
101 |
#' selected = "vs", |
|
102 |
#' multiple = FALSE, |
|
103 |
#' fixed = FALSE |
|
104 |
#' ) |
|
105 |
#' ) |
|
106 |
#' ) |
|
107 |
#' ) |
|
108 |
#' ) |
|
109 |
#' if (interactive()) { |
|
110 |
#' shinyApp(app$ui, app$server) |
|
111 |
#' } |
|
112 |
#' |
|
113 |
#' @examplesShinylive |
|
114 |
#' library(teal.modules.general) |
|
115 |
#' interactive <- function() TRUE |
|
116 |
#' {{ next_example }} |
|
117 |
#' @examples |
|
118 |
#' # CDISC data example |
|
119 |
#' data <- teal_data() |
|
120 |
#' data <- within(data, { |
|
121 |
#' ADSL <- teal.data::rADSL |
|
122 |
#' }) |
|
123 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
124 |
#' |
|
125 |
#' app <- init( |
|
126 |
#' data = data, |
|
127 |
#' modules = modules( |
|
128 |
#' tm_t_crosstable( |
|
129 |
#' label = "Cross Table", |
|
130 |
#' x = data_extract_spec( |
|
131 |
#' dataname = "ADSL", |
|
132 |
#' select = select_spec( |
|
133 |
#' label = "Select variable:", |
|
134 |
#' choices = variable_choices(data[["ADSL"]], subset = function(data) { |
|
135 |
#' idx <- !vapply(data, inherits, logical(1), c("Date", "POSIXct", "POSIXlt")) |
|
136 |
#' return(names(data)[idx]) |
|
137 |
#' }), |
|
138 |
#' selected = "COUNTRY", |
|
139 |
#' multiple = TRUE, |
|
140 |
#' ordered = TRUE, |
|
141 |
#' fixed = FALSE |
|
142 |
#' ) |
|
143 |
#' ), |
|
144 |
#' y = data_extract_spec( |
|
145 |
#' dataname = "ADSL", |
|
146 |
#' select = select_spec( |
|
147 |
#' label = "Select variable:", |
|
148 |
#' choices = variable_choices(data[["ADSL"]], subset = function(data) { |
|
149 |
#' idx <- vapply(data, is.factor, logical(1)) |
|
150 |
#' return(names(data)[idx]) |
|
151 |
#' }), |
|
152 |
#' selected = "SEX", |
|
153 |
#' multiple = FALSE, |
|
154 |
#' fixed = FALSE |
|
155 |
#' ) |
|
156 |
#' ) |
|
157 |
#' ) |
|
158 |
#' ) |
|
159 |
#' ) |
|
160 |
#' if (interactive()) { |
|
161 |
#' shinyApp(app$ui, app$server) |
|
162 |
#' } |
|
163 |
#' |
|
164 |
#' @export |
|
165 |
#' |
|
166 |
tm_t_crosstable <- function(label = "Cross Table", |
|
167 |
x, |
|
168 |
y, |
|
169 |
show_percentage = TRUE, |
|
170 |
show_total = TRUE, |
|
171 |
remove_zero_columns = FALSE, |
|
172 |
pre_output = NULL, |
|
173 |
post_output = NULL, |
|
174 |
basic_table_args = teal.widgets::basic_table_args(), |
|
175 |
transformators = list(), |
|
176 |
decorators = list()) { |
|
177 | ! |
message("Initializing tm_t_crosstable") |
178 | ||
179 |
# Normalize the parameters |
|
180 | ! |
if (inherits(x, "data_extract_spec")) x <- list(x) |
181 | ! |
if (inherits(y, "data_extract_spec")) y <- list(y) |
182 | ||
183 |
# Start of assertions |
|
184 | ! |
checkmate::assert_string(label) |
185 | ! |
checkmate::assert_list(x, types = "data_extract_spec") |
186 | ||
187 | ! |
checkmate::assert_list(y, types = "data_extract_spec") |
188 | ! |
assert_single_selection(y) |
189 | ||
190 | ! |
checkmate::assert_flag(show_percentage) |
191 | ! |
checkmate::assert_flag(show_total) |
192 | ! |
checkmate::assert_flag(remove_zero_columns) |
193 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
194 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
195 | ! |
checkmate::assert_class(basic_table_args, classes = "basic_table_args") |
196 | ||
197 | ! |
assert_decorators(decorators, "table") |
198 |
# End of assertions |
|
199 | ||
200 |
# Make UI args |
|
201 | ! |
ui_args <- as.list(environment()) |
202 | ||
203 | ! |
server_args <- list( |
204 | ! |
label = label, |
205 | ! |
x = x, |
206 | ! |
y = y, |
207 | ! |
remove_zero_columns = remove_zero_columns, |
208 | ! |
basic_table_args = basic_table_args, |
209 | ! |
decorators = decorators |
210 |
) |
|
211 | ||
212 | ! |
ans <- module( |
213 | ! |
label = label, |
214 | ! |
server = srv_t_crosstable, |
215 | ! |
ui = ui_t_crosstable, |
216 | ! |
ui_args = ui_args, |
217 | ! |
server_args = server_args, |
218 | ! |
transformators = transformators, |
219 | ! |
datanames = teal.transform::get_extract_datanames(list(x = x, y = y)) |
220 |
) |
|
221 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
222 | ! |
ans |
223 |
} |
|
224 | ||
225 |
# UI function for the cross-table module |
|
226 |
ui_t_crosstable <- function(id, x, y, show_percentage, show_total, remove_zero_columns, pre_output, post_output, ...) { |
|
227 | ! |
args <- list(...) |
228 | ! |
ns <- NS(id) |
229 | ! |
is_single_dataset <- teal.transform::is_single_dataset(x, y) |
230 | ||
231 | ! |
join_default_options <- c( |
232 | ! |
"Full Join" = "dplyr::full_join", |
233 | ! |
"Inner Join" = "dplyr::inner_join", |
234 | ! |
"Left Join" = "dplyr::left_join", |
235 | ! |
"Right Join" = "dplyr::right_join" |
236 |
) |
|
237 | ||
238 | ! |
teal.widgets::standard_layout( |
239 | ! |
output = teal.widgets::white_small_well( |
240 | ! |
textOutput(ns("title")), |
241 | ! |
teal.widgets::table_with_settings_ui(ns("table")) |
242 |
), |
|
243 | ! |
encoding = tags$div( |
244 | ! |
tags$label("Encodings", class = "text-primary"), |
245 | ! |
teal.transform::datanames_input(list(x, y)), |
246 | ! |
teal.transform::data_extract_ui(ns("x"), label = "Row values", x, is_single_dataset = is_single_dataset), |
247 | ! |
teal.transform::data_extract_ui(ns("y"), label = "Column values", y, is_single_dataset = is_single_dataset), |
248 | ! |
teal.widgets::optionalSelectInput( |
249 | ! |
ns("join_fun"), |
250 | ! |
label = "Row to Column type of join", |
251 | ! |
choices = join_default_options, |
252 | ! |
selected = join_default_options[1], |
253 | ! |
multiple = FALSE |
254 |
), |
|
255 | ! |
tags$hr(), |
256 | ! |
bslib::accordion( |
257 | ! |
open = TRUE, |
258 | ! |
bslib::accordion_panel( |
259 | ! |
title = "Table settings", |
260 | ! |
checkboxInput(ns("show_percentage"), "Show column percentage", value = show_percentage), |
261 | ! |
checkboxInput(ns("show_total"), "Show total column", value = show_total), |
262 | ! |
checkboxInput(ns("remove_zero_columns"), "Remove zero-only columns", value = remove_zero_columns) |
263 |
) |
|
264 |
), |
|
265 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "table")) |
266 |
), |
|
267 | ! |
forms = tagList( |
268 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
269 |
), |
|
270 | ! |
pre_output = pre_output, |
271 | ! |
post_output = post_output |
272 |
) |
|
273 |
} |
|
274 | ||
275 |
# Server function for the cross-table module |
|
276 |
srv_t_crosstable <- function(id, data, label, x, y, remove_zero_columns, basic_table_args, decorators) { |
|
277 | ! |
checkmate::assert_class(data, "reactive") |
278 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
279 | ! |
moduleServer(id, function(input, output, session) { |
280 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
281 | ||
282 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
283 | ! |
data_extract = list(x = x, y = y), |
284 | ! |
datasets = data, |
285 | ! |
select_validation_rule = list( |
286 | ! |
x = shinyvalidate::sv_required("Please define column for row variable."), |
287 | ! |
y = shinyvalidate::sv_required("Please define column for column variable.") |
288 |
) |
|
289 |
) |
|
290 | ||
291 | ! |
iv_r <- reactive({ |
292 | ! |
iv <- shinyvalidate::InputValidator$new() |
293 | ! |
iv$add_rule("join_fun", function(value) { |
294 | ! |
if (!identical(selector_list()$x()$dataname, selector_list()$y()$dataname)) { |
295 | ! |
if (!shinyvalidate::input_provided(value)) { |
296 | ! |
"Please select a joining function." |
297 |
} |
|
298 |
} |
|
299 |
}) |
|
300 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
301 |
}) |
|
302 | ||
303 | ! |
observeEvent( |
304 | ! |
eventExpr = { |
305 | ! |
req(!is.null(selector_list()$x()) && !is.null(selector_list()$y())) |
306 | ! |
list(selector_list()$x(), selector_list()$y()) |
307 |
}, |
|
308 | ! |
handlerExpr = { |
309 | ! |
if (identical(selector_list()$x()$dataname, selector_list()$y()$dataname)) { |
310 | ! |
shinyjs::hide("join_fun") |
311 |
} else { |
|
312 | ! |
shinyjs::show("join_fun") |
313 |
} |
|
314 |
} |
|
315 |
) |
|
316 | ||
317 | ! |
merge_function <- reactive({ |
318 | ! |
if (is.null(input$join_fun)) { |
319 | ! |
"dplyr::full_join" |
320 |
} else { |
|
321 | ! |
input$join_fun |
322 |
} |
|
323 |
}) |
|
324 | ||
325 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
326 | ! |
datasets = data, |
327 | ! |
selector_list = selector_list, |
328 | ! |
merge_function = merge_function |
329 |
) |
|
330 | ! |
qenv <- reactive({ |
331 | ! |
obj <- data() |
332 | ! |
teal.reporter::teal_card(obj) <- |
333 | ! |
c( |
334 | ! |
teal.reporter::teal_card("# Cross Table"), |
335 | ! |
teal.reporter::teal_card(obj), |
336 | ! |
teal.reporter::teal_card("## Module's code") |
337 |
) |
|
338 | ! |
teal.code::eval_code(obj, 'library("rtables");library("tern");library("dplyr")') # nolint quotes |
339 |
}) |
|
340 | ! |
anl_merged_q <- reactive({ |
341 | ! |
req(anl_merged_input()) |
342 | ! |
qenv() %>% |
343 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
344 |
}) |
|
345 | ||
346 | ! |
merged <- list( |
347 | ! |
anl_input_r = anl_merged_input, |
348 | ! |
anl_q_r = anl_merged_q |
349 |
) |
|
350 | ||
351 | ! |
output_q <- reactive({ |
352 | ! |
teal::validate_inputs(iv_r()) |
353 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
354 | ||
355 |
# As this is a summary |
|
356 | ! |
x_name <- as.vector(merged$anl_input_r()$columns_source$x) |
357 | ! |
y_name <- as.vector(merged$anl_input_r()$columns_source$y) |
358 | ||
359 | ! |
teal::validate_has_data(ANL, 3) |
360 | ! |
teal::validate_has_data(ANL[, c(x_name, y_name)], 3, complete = TRUE, allow_inf = FALSE) |
361 | ||
362 | ! |
is_allowed_class <- function(x) is.numeric(x) || is.factor(x) || is.character(x) || is.logical(x) |
363 | ! |
validate(need( |
364 | ! |
all(vapply(ANL[x_name], is_allowed_class, logical(1))), |
365 | ! |
"Selected row variable has an unsupported data type." |
366 |
)) |
|
367 | ! |
validate(need( |
368 | ! |
is_allowed_class(ANL[[y_name]]), |
369 | ! |
"Selected column variable has an unsupported data type." |
370 |
)) |
|
371 | ||
372 | ! |
show_percentage <- input$show_percentage |
373 | ! |
show_total <- input$show_total |
374 | ! |
remove_zero_columns <- input$remove_zero_columns |
375 | ||
376 | ! |
plot_title <- paste( |
377 | ! |
"Cross-Table of", |
378 | ! |
paste0(varname_w_label(x_name, ANL), collapse = ", "), |
379 | ! |
"(rows)", "vs.", |
380 | ! |
varname_w_label(y_name, ANL), |
381 | ! |
"(columns)" |
382 |
) |
|
383 | ||
384 | ! |
labels_vec <- vapply( |
385 | ! |
x_name, |
386 | ! |
varname_w_label, |
387 | ! |
character(1), |
388 | ! |
ANL |
389 |
) |
|
390 | ||
391 | ! |
obj <- merged$anl_q_r() |
392 | ! |
teal.reporter::teal_card(obj) <- c(teal.reporter::teal_card(obj), "# Table") |
393 | ! |
obj <- teal.code::eval_code( |
394 | ! |
obj, |
395 | ! |
substitute( |
396 | ! |
expr = { |
397 | ! |
title <- plot_title |
398 |
}, |
|
399 | ! |
env = list(plot_title = plot_title) |
400 |
) |
|
401 |
) %>% |
|
402 | ! |
teal.code::eval_code( |
403 | ! |
substitute( |
404 | ! |
expr = { |
405 | ! |
table <- basic_tables %>% |
406 | ! |
split_call %>% # styler: off |
407 | ! |
rtables::add_colcounts() %>% |
408 | ! |
tern::analyze_vars( |
409 | ! |
vars = x_name, |
410 | ! |
var_labels = labels_vec, |
411 | ! |
na.rm = FALSE, |
412 | ! |
denom = "N_col", |
413 | ! |
.stats = c("mean_sd", "median", "range", count_value) |
414 |
) |
|
415 |
}, |
|
416 | ! |
env = list( |
417 | ! |
basic_tables = teal.widgets::parse_basic_table_args( |
418 | ! |
basic_table_args = teal.widgets::resolve_basic_table_args(basic_table_args) |
419 |
), |
|
420 | ! |
split_call = if (show_total) { |
421 | ! |
substitute( |
422 | ! |
expr = rtables::split_cols_by( |
423 | ! |
y_name, |
424 | ! |
split_fun = rtables::add_overall_level(label = "Total", first = FALSE) |
425 |
), |
|
426 | ! |
env = list(y_name = y_name) |
427 |
) |
|
428 |
} else { |
|
429 | ! |
substitute(rtables::split_cols_by(y_name), env = list(y_name = y_name)) |
430 |
}, |
|
431 | ! |
x_name = x_name, |
432 | ! |
labels_vec = labels_vec, |
433 | ! |
count_value = ifelse(show_percentage, "count_fraction", "count") |
434 |
) |
|
435 |
) |
|
436 |
) %>% |
|
437 | ! |
teal.code::eval_code( |
438 | ! |
expression(ANL <- tern::df_explicit_na(ANL)) |
439 |
) |
|
440 | ||
441 | ! |
if (remove_zero_columns) { |
442 | ! |
obj <- obj %>% |
443 | ! |
teal.code::eval_code( |
444 | ! |
substitute( |
445 | ! |
expr = { |
446 | ! |
ANL[[y_name]] <- droplevels(ANL[[y_name]]) |
447 | ! |
table <- rtables::build_table(lyt = table, df = ANL[order(ANL[[y_name]]), ]) |
448 |
}, |
|
449 | ! |
env = list(y_name = y_name) |
450 |
) |
|
451 |
) |
|
452 |
} else { |
|
453 | ! |
obj <- obj %>% |
454 | ! |
teal.code::eval_code( |
455 | ! |
substitute( |
456 | ! |
expr = { |
457 | ! |
table <- rtables::build_table(lyt = table, df = ANL[order(ANL[[y_name]]), ]) |
458 |
}, |
|
459 | ! |
env = list(y_name = y_name) |
460 |
) |
|
461 |
) |
|
462 |
} |
|
463 | ! |
obj |
464 |
}) |
|
465 | ||
466 | ! |
decorated_output_q <- srv_decorate_teal_data( |
467 | ! |
id = "decorator", |
468 | ! |
data = output_q, |
469 | ! |
decorators = select_decorators(decorators, "table"), |
470 | ! |
expr = quote(table) |
471 |
) |
|
472 | ||
473 | ! |
output$title <- renderText(req(decorated_output_q())[["title"]]) |
474 | ||
475 | ! |
table_r <- reactive({ |
476 | ! |
req(iv_r()$is_valid()) |
477 | ! |
req(decorated_output_q())[["table"]] |
478 |
}) |
|
479 | ||
480 | ! |
teal.widgets::table_with_settings_srv( |
481 | ! |
id = "table", |
482 | ! |
table_r = table_r |
483 |
) |
|
484 | ||
485 |
# Render R code. |
|
486 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_output_q()))) |
487 | ||
488 | ! |
teal.widgets::verbatim_popup_srv( |
489 | ! |
id = "rcode", |
490 | ! |
verbatim_content = source_code_r, |
491 | ! |
title = "Show R Code for Cross-Table" |
492 |
) |
|
493 | ! |
decorated_output_q |
494 |
}) |
|
495 |
} |
1 |
#' `teal` module: Front page |
|
2 |
#' |
|
3 |
#' Creates a simple front page for `teal` applications, displaying |
|
4 |
#' introductory text, tables, additional `html` or `shiny` tags, and footnotes. |
|
5 |
#' |
|
6 |
#' @inheritParams teal::module |
|
7 |
#' @param header_text (`character` vector) text to be shown at the top of the module, for each |
|
8 |
#' element, if named the name is shown first in bold as a header followed by the value. The first |
|
9 |
#' element's header is displayed larger than the others. |
|
10 |
#' @param tables (`named list` of `data.frame`s) tables to be shown in the module. |
|
11 |
#' @param additional_tags (`shiny.tag.list` or `html`) additional `shiny` tags or `html` to be included after the table, |
|
12 |
#' for example to include an image, `tagList(tags$img(src = "image.png"))` or to include further `html`, |
|
13 |
#' `HTML("html text here")`. |
|
14 |
#' @param footnotes (`character` vector) of text to be shown at the bottom of the module, for each |
|
15 |
#' element, if named the name is shown first in bold, followed by the value. |
|
16 |
#' @param show_metadata (`logical`) `r lifecycle::badge("deprecated")` indicating |
|
17 |
#' whether the metadata of the datasets be available on the module. |
|
18 |
#' Metadata shown automatically when `datanames` set. |
|
19 |
#' @inheritParams tm_variable_browser |
|
20 |
#' |
|
21 |
#' @inherit shared_params return |
|
22 |
#' |
|
23 |
#' @examplesShinylive |
|
24 |
#' library(teal.modules.general) |
|
25 |
#' interactive <- function() TRUE |
|
26 |
#' {{ next_example }} |
|
27 |
#' @examples |
|
28 |
#' data <- teal_data() |
|
29 |
#' data <- within(data, { |
|
30 |
#' require(nestcolor) |
|
31 |
#' ADSL <- teal.data::rADSL |
|
32 |
#' attr(ADSL, "metadata") <- list("Author" = "NEST team", "data_source" = "synthetic data") |
|
33 |
#' }) |
|
34 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
35 |
#' |
|
36 |
#' table_1 <- data.frame(Info = c("A", "B"), Text = c("A", "B")) |
|
37 |
#' table_2 <- data.frame(`Column 1` = c("C", "D"), `Column 2` = c(5.5, 6.6), `Column 3` = c("A", "B")) |
|
38 |
#' table_3 <- data.frame(Info = c("E", "F"), Text = c("G", "H")) |
|
39 |
#' |
|
40 |
#' table_input <- list( |
|
41 |
#' "Table 1" = table_1, |
|
42 |
#' "Table 2" = table_2, |
|
43 |
#' "Table 3" = table_3 |
|
44 |
#' ) |
|
45 |
#' |
|
46 |
#' app <- init( |
|
47 |
#' data = data, |
|
48 |
#' modules = modules( |
|
49 |
#' tm_front_page( |
|
50 |
#' header_text = c( |
|
51 |
#' "Important information" = "It can go here.", |
|
52 |
#' "Other information" = "Can go here." |
|
53 |
#' ), |
|
54 |
#' tables = table_input, |
|
55 |
#' additional_tags = HTML("Additional HTML or shiny tags go here <br>"), |
|
56 |
#' footnotes = c("X" = "is the first footnote", "Y is the second footnote") |
|
57 |
#' ) |
|
58 |
#' ) |
|
59 |
#' ) |> |
|
60 |
#' modify_header(tags$h1("Sample Application")) |> |
|
61 |
#' modify_footer(tags$p("Application footer")) |
|
62 |
#' |
|
63 |
#' if (interactive()) { |
|
64 |
#' shinyApp(app$ui, app$server) |
|
65 |
#' } |
|
66 |
#' |
|
67 |
#' @export |
|
68 |
#' |
|
69 |
tm_front_page <- function(label = "Front page", |
|
70 |
header_text = character(0), |
|
71 |
tables = list(), |
|
72 |
additional_tags = tagList(), |
|
73 |
footnotes = character(0), |
|
74 |
show_metadata = deprecated(), |
|
75 |
datanames = if (missing(show_metadata)) NULL else "all", |
|
76 |
transformators = list()) { |
|
77 | ! |
message("Initializing tm_front_page") |
78 | ||
79 |
# Start of assertions |
|
80 | ! |
checkmate::assert_string(label) |
81 | ! |
checkmate::assert_character(header_text, min.len = 0, any.missing = FALSE) |
82 | ! |
checkmate::assert_list(tables, types = "data.frame", names = "named", any.missing = FALSE) |
83 | ! |
checkmate::assert_multi_class(additional_tags, classes = c("shiny.tag.list", "html")) |
84 | ! |
checkmate::assert_character(footnotes, min.len = 0, any.missing = FALSE) |
85 | ! |
if (!missing(show_metadata)) { |
86 | ! |
lifecycle::deprecate_stop( |
87 | ! |
when = "0.4.0", |
88 | ! |
what = "tm_front_page(show_metadata)", |
89 | ! |
with = "tm_front_page(datanames)", |
90 | ! |
details = c( |
91 | ! |
"With `datanames` you can select which datasets are displayed.", |
92 | ! |
i = "Use `tm_front_page(datanames = 'all')` to keep the previous behavior and avoid this warning." |
93 |
) |
|
94 |
) |
|
95 |
} |
|
96 | ! |
checkmate::assert_character(datanames, min.len = 0, min.chars = 1, null.ok = TRUE) |
97 | ||
98 |
# End of assertions |
|
99 | ||
100 |
# Make UI args |
|
101 | ! |
args <- as.list(environment()) |
102 | ||
103 | ! |
ans <- module( |
104 | ! |
label = label, |
105 | ! |
server = srv_front_page, |
106 | ! |
ui = ui_front_page, |
107 | ! |
ui_args = args, |
108 | ! |
server_args = list(tables = tables), |
109 | ! |
datanames = datanames, , |
110 | ! |
transformators = transformators |
111 |
) |
|
112 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
113 | ! |
ans |
114 |
} |
|
115 | ||
116 |
# UI function for the front page module |
|
117 |
ui_front_page <- function(id, ...) { |
|
118 | ! |
args <- list(...) |
119 | ! |
ns <- NS(id) |
120 | ||
121 | ! |
tagList( |
122 | ! |
tags$div( |
123 | ! |
id = "front_page_content", |
124 | ! |
style = "margin-left: 2rem;", |
125 | ! |
tags$div( |
126 | ! |
id = "front_page_headers", |
127 | ! |
get_header_tags(args$header_text) |
128 |
), |
|
129 | ! |
tags$div( |
130 | ! |
id = "front_page_tables", |
131 | ! |
style = "margin-left: 2rem;", |
132 | ! |
get_table_tags(args$tables, ns) |
133 |
), |
|
134 | ! |
tags$div( |
135 | ! |
id = "front_page_custom_html", |
136 | ! |
style = "margin-left: 2rem;", |
137 | ! |
args$additional_tags |
138 |
), |
|
139 | ! |
if (length(args$datanames) > 0L) { |
140 | ! |
tags$div( |
141 | ! |
id = "front_page_metabutton", |
142 | ! |
style = "margin: 1rem;", |
143 | ! |
actionButton(ns("metadata_button"), "Show metadata") |
144 |
) |
|
145 |
}, |
|
146 | ! |
tags$footer( |
147 | ! |
class = "small", |
148 | ! |
get_footer_tags(args$footnotes) |
149 |
) |
|
150 |
) |
|
151 |
) |
|
152 |
} |
|
153 | ||
154 |
# Server function for the front page module |
|
155 |
srv_front_page <- function(id, data, tables) { |
|
156 | ! |
checkmate::assert_class(data, "reactive") |
157 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
158 | ! |
moduleServer(id, function(input, output, session) { |
159 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
160 | ||
161 | ! |
ns <- session$ns |
162 | ||
163 | ! |
setBookmarkExclude("metadata_button") |
164 | ||
165 | ! |
lapply(seq_along(tables), function(idx) { |
166 | ! |
output[[paste0("table_", idx)]] <- renderTable( |
167 | ! |
tables[[idx]], |
168 | ! |
bordered = TRUE, |
169 | ! |
caption = names(tables)[idx], |
170 | ! |
caption.placement = "top" |
171 |
) |
|
172 |
}) |
|
173 | ! |
if (length(isolate(names(data()))) > 0L) { |
174 | ! |
observeEvent( |
175 | ! |
input$metadata_button, showModal( |
176 | ! |
modalDialog( |
177 | ! |
title = "Metadata", |
178 | ! |
dataTableOutput(ns("metadata_table")), |
179 | ! |
size = "l", |
180 | ! |
easyClose = TRUE |
181 |
) |
|
182 |
) |
|
183 |
) |
|
184 | ||
185 | ! |
metadata_data_frame <- reactive({ |
186 | ! |
datanames <- names(data()) |
187 | ! |
convert_metadata_to_dataframe( |
188 | ! |
lapply(datanames, function(dataname) attr(data()[[dataname]], "metadata")), |
189 | ! |
datanames |
190 |
) |
|
191 |
}) |
|
192 | ||
193 | ! |
output$metadata_table <- renderDataTable({ |
194 | ! |
validate(need(nrow(metadata_data_frame()) > 0, "The data has no associated metadata")) |
195 | ! |
metadata_data_frame() |
196 |
}) |
|
197 |
} |
|
198 |
}) |
|
199 |
} |
|
200 | ||
201 |
## utils functions |
|
202 | ||
203 |
get_header_tags <- function(header_text) { |
|
204 | ! |
if (length(header_text) == 0) { |
205 | ! |
return(list()) |
206 |
} |
|
207 | ||
208 | ! |
get_single_header_tags <- function(header_text, p_text, header_tag = tags$h4) { |
209 | ! |
tagList( |
210 | ! |
tags$div( |
211 | ! |
if (!is.null(header_text) && nchar(header_text) > 0) header_tag(header_text), |
212 | ! |
tags$p(p_text) |
213 |
) |
|
214 |
) |
|
215 |
} |
|
216 | ||
217 | ! |
header_tags <- get_single_header_tags(names(header_text[1]), header_text[1], header_tag = tags$h3) |
218 | ! |
c(header_tags, mapply(get_single_header_tags, utils::tail(names(header_text), -1), utils::tail(header_text, -1))) |
219 |
} |
|
220 | ||
221 |
get_table_tags <- function(tables, ns) { |
|
222 | ! |
if (length(tables) == 0) { |
223 | ! |
return(list()) |
224 |
} |
|
225 | ! |
table_tags <- c(lapply(seq_along(tables), function(idx) { |
226 | ! |
list( |
227 | ! |
tableOutput(ns(paste0("table_", idx))) |
228 |
) |
|
229 |
})) |
|
230 | ! |
table_tags |
231 |
} |
|
232 | ||
233 |
get_footer_tags <- function(footnotes) { |
|
234 | ! |
if (length(footnotes) == 0) { |
235 | ! |
return(list()) |
236 |
} |
|
237 | ! |
bold_texts <- if (is.null(names(footnotes))) rep("", length(footnotes)) else names(footnotes) |
238 | ! |
footnote_tags <- mapply(function(bold_text, value) { |
239 | ! |
list( |
240 | ! |
tags$div( |
241 | ! |
tags$b(bold_text), |
242 | ! |
value, |
243 | ! |
tags$br() |
244 |
) |
|
245 |
) |
|
246 | ! |
}, bold_text = bold_texts, value = footnotes) |
247 |
} |
|
248 | ||
249 |
# take a list of metadata, one item per dataset (raw_metadata each element from datasets$get_metadata()) |
|
250 |
# and the corresponding datanames and output a data.frame with columns {Dataset, Name, Value}. |
|
251 |
# which are, the Dataset the metadata came from, the metadata's name and value |
|
252 |
convert_metadata_to_dataframe <- function(raw_metadata, datanames) { |
|
253 | 4x |
output <- mapply(function(metadata, dataname) { |
254 | 6x |
if (is.null(metadata)) { |
255 | 2x |
return(data.frame(Dataset = character(0), Name = character(0), Value = character(0))) |
256 |
} |
|
257 | 4x |
data.frame( |
258 | 4x |
Dataset = dataname, |
259 | 4x |
Name = names(metadata), |
260 | 4x |
Value = unname(unlist(lapply(metadata, as.character))) |
261 |
) |
|
262 | 4x |
}, raw_metadata, datanames, SIMPLIFY = FALSE) |
263 | 4x |
do.call(rbind, output) |
264 |
} |
1 |
#' `teal` module: File viewer |
|
2 |
#' |
|
3 |
#' The file viewer module provides a tool to view static files. |
|
4 |
#' Supported formats include text formats, `PDF`, `PNG` `APNG`, |
|
5 |
#' `JPEG` `SVG`, `WEBP`, `GIF` and `BMP`. |
|
6 |
#' |
|
7 |
#' @inheritParams teal::module |
|
8 |
#' @inheritParams shared_params |
|
9 |
#' @param input_path (`list`) of the input paths, optional. Each element can be: |
|
10 |
#' |
|
11 |
#' Paths can be specified as absolute paths or relative to the running directory of the application. |
|
12 |
#' Default to the current working directory if not supplied. |
|
13 |
#' |
|
14 |
#' @inherit shared_params return |
|
15 |
#' |
|
16 |
#' @examplesShinylive |
|
17 |
#' library(teal.modules.general) |
|
18 |
#' interactive <- function() TRUE |
|
19 |
#' {{ next_example }} |
|
20 |
#' @examples |
|
21 |
#' data <- teal_data() |
|
22 |
#' data <- within(data, { |
|
23 |
#' data <- data.frame(1) |
|
24 |
#' }) |
|
25 |
#' |
|
26 |
#' app <- init( |
|
27 |
#' data = data, |
|
28 |
#' modules = modules( |
|
29 |
#' tm_file_viewer( |
|
30 |
#' input_path = list( |
|
31 |
#' folder = system.file("sample_files", package = "teal.modules.general"), |
|
32 |
#' png = system.file("sample_files/sample_file.png", package = "teal.modules.general"), |
|
33 |
#' txt = system.file("sample_files/sample_file.txt", package = "teal.modules.general"), |
|
34 |
#' url = "https://fda.gov/files/drugs/published/Portable-Document-Format-Specifications.pdf" |
|
35 |
#' ) |
|
36 |
#' ) |
|
37 |
#' ) |
|
38 |
#' ) |
|
39 |
#' if (interactive()) { |
|
40 |
#' shinyApp(app$ui, app$server) |
|
41 |
#' } |
|
42 |
#' |
|
43 |
#' @export |
|
44 |
#' |
|
45 |
tm_file_viewer <- function(label = "File Viewer Module", |
|
46 |
input_path = list("Current Working Directory" = ".")) { |
|
47 | ! |
message("Initializing tm_file_viewer") |
48 | ||
49 |
# Normalize the parameters |
|
50 | ! |
if (length(label) == 0 || identical(label, "")) label <- " " |
51 | ! |
if (length(input_path) == 0 || identical(input_path, "")) input_path <- list() |
52 | ||
53 |
# Start of assertions |
|
54 | ! |
checkmate::assert_string(label) |
55 | ||
56 | ! |
checkmate::assert( |
57 | ! |
checkmate::check_list(input_path, types = "character", min.len = 0), |
58 | ! |
checkmate::check_character(input_path, min.len = 1) |
59 |
) |
|
60 | ! |
if (length(input_path) > 0) { |
61 | ! |
valid_url <- function(url_input, timeout = 2) { |
62 | ! |
con <- try(url(url_input), silent = TRUE) |
63 | ! |
check <- suppressWarnings(try(open.connection(con, open = "rt", timeout = timeout), silent = TRUE)[1]) |
64 | ! |
try(close.connection(con), silent = TRUE) |
65 | ! |
is.null(check) |
66 |
} |
|
67 | ! |
idx <- vapply(input_path, function(x) file.exists(x) || valid_url(x), logical(1)) |
68 | ||
69 | ! |
if (!all(idx)) { |
70 | ! |
warning( |
71 | ! |
paste0( |
72 | ! |
"Non-existent file or url path. Please provide valid paths for:\n", |
73 | ! |
paste0(input_path[!idx], collapse = "\n") |
74 |
) |
|
75 |
) |
|
76 |
} |
|
77 | ! |
input_path <- input_path[idx] |
78 |
} else { |
|
79 | ! |
warning( |
80 | ! |
"No file or url paths were provided." |
81 |
) |
|
82 |
} |
|
83 |
# End of assertions |
|
84 | ||
85 |
# Make UI args |
|
86 | ! |
args <- as.list(environment()) |
87 | ||
88 | ! |
ans <- module( |
89 | ! |
label = label, |
90 | ! |
server = srv_viewer, |
91 | ! |
server_args = list(input_path = input_path), |
92 | ! |
ui = ui_viewer, |
93 | ! |
ui_args = args, |
94 | ! |
datanames = NULL |
95 |
) |
|
96 | ! |
attr(ans, "teal_bookmarkable") <- FALSE |
97 | ! |
ans |
98 |
} |
|
99 | ||
100 |
# UI function for the file viewer module |
|
101 |
ui_viewer <- function(id, ...) { |
|
102 | ! |
args <- list(...) |
103 | ! |
ns <- NS(id) |
104 | ||
105 | ! |
tagList( |
106 | ! |
teal.widgets::standard_layout( |
107 | ! |
output = tags$div( |
108 | ! |
uiOutput(ns("output")) |
109 |
), |
|
110 | ! |
encoding = tags$div( |
111 | ! |
style = "overflow-y: hidden; overflow-x: auto;", |
112 | ! |
tags$label("Encodings", class = "text-primary"), |
113 | ! |
shinyTree::shinyTree( |
114 | ! |
ns("tree"), |
115 | ! |
dragAndDrop = FALSE, |
116 | ! |
sort = FALSE, |
117 | ! |
theme = "proton", |
118 | ! |
multiple = FALSE, |
119 | ! |
search = TRUE |
120 |
) |
|
121 |
) |
|
122 |
) |
|
123 |
) |
|
124 |
} |
|
125 | ||
126 |
# Server function for the file viewer module |
|
127 |
srv_viewer <- function(id, input_path) { |
|
128 | ! |
moduleServer(id, function(input, output, session) { |
129 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
130 | ||
131 | ! |
temp_dir <- tempfile() |
132 | ! |
if (!dir.exists(temp_dir)) { |
133 | ! |
dir.create(temp_dir, recursive = TRUE) |
134 |
} |
|
135 | ! |
addResourcePath(basename(temp_dir), temp_dir) |
136 | ||
137 | ! |
test_path_text <- function(selected_path, type) { |
138 | ! |
out <- tryCatch( |
139 | ! |
expr = { |
140 | ! |
if (type != "url") { |
141 | ! |
selected_path <- normalizePath(selected_path, winslash = "/") |
142 |
} |
|
143 | ! |
readLines(con = selected_path) |
144 |
}, |
|
145 | ! |
error = function(cond) FALSE, |
146 | ! |
warning = function(cond) { |
147 | ! |
`if`(grepl("^incomplete final line found on", cond[[1]]), suppressWarnings(eval(cond[[2]])), FALSE) |
148 |
} |
|
149 |
) |
|
150 |
} |
|
151 | ||
152 | ! |
handle_connection_type <- function(selected_path) { |
153 | ! |
file_extension <- tools::file_ext(selected_path) |
154 | ! |
file_class <- suppressWarnings(file(selected_path)) |
155 | ! |
close(file_class) |
156 | ||
157 | ! |
output_text <- test_path_text(selected_path, type = class(file_class)[1]) |
158 | ||
159 | ! |
if (class(file_class)[1] == "url") { |
160 | ! |
list(selected_path = selected_path, output_text = output_text) |
161 |
} else { |
|
162 | ! |
file.copy(normalizePath(selected_path, winslash = "/"), temp_dir) |
163 | ! |
selected_path <- file.path(basename(temp_dir), basename(selected_path)) |
164 | ! |
list(selected_path = selected_path, output_text = output_text) |
165 |
} |
|
166 |
} |
|
167 | ||
168 | ! |
display_file <- function(selected_path) { |
169 | ! |
con_type <- handle_connection_type(selected_path) |
170 | ! |
file_extension <- tools::file_ext(selected_path) |
171 | ! |
if (file_extension %in% c("png", "apng", "jpg", "jpeg", "svg", "gif", "webp", "bmp")) { |
172 | ! |
tags$img(src = con_type$selected_path, alt = "file does not exist") |
173 | ! |
} else if (file_extension == "pdf") { |
174 | ! |
tags$embed( |
175 | ! |
style = "height: 600px; width: 100%;", |
176 | ! |
src = con_type$selected_path |
177 |
) |
|
178 | ! |
} else if (!isFALSE(con_type$output_text[1])) { |
179 | ! |
tags$pre(paste0(con_type$output_text, collapse = "\n")) |
180 |
} else { |
|
181 | ! |
tags$p("Please select a supported format.") |
182 |
} |
|
183 |
} |
|
184 | ||
185 | ! |
tree_list <- function(file_or_dir) { |
186 | ! |
nested_list <- lapply(file_or_dir, function(path) { |
187 | ! |
file_class <- suppressWarnings(file(path)) |
188 | ! |
close(file_class) |
189 | ! |
if (class(file_class)[[1]] != "url") { |
190 | ! |
isdir <- file.info(path)$isdir |
191 | ! |
if (!isdir) { |
192 | ! |
structure(path, ancestry = path, sticon = "file") |
193 |
} else { |
|
194 | ! |
files <- list.files(path, full.names = TRUE, include.dirs = TRUE) |
195 | ! |
out <- lapply(files, function(x) tree_list(x)) |
196 | ! |
out <- unlist(out, recursive = FALSE) |
197 | ! |
if (length(files) > 0) names(out) <- basename(files) |
198 | ! |
out |
199 |
} |
|
200 |
} else { |
|
201 | ! |
structure(path, ancestry = path, sticon = "file") |
202 |
} |
|
203 |
}) |
|
204 | ||
205 | ! |
missing_labels <- if (is.null(names(nested_list))) seq_along(nested_list) else which(names(nested_list) == "") |
206 | ! |
names(nested_list)[missing_labels] <- file_or_dir[missing_labels] |
207 | ! |
nested_list |
208 |
} |
|
209 | ||
210 | ! |
output$tree <- shinyTree::renderTree({ |
211 | ! |
if (length(input_path) > 0) { |
212 | ! |
tree_list(input_path) |
213 |
} else { |
|
214 | ! |
list("Empty Path" = NULL) |
215 |
} |
|
216 |
}) |
|
217 | ||
218 | ! |
output$output <- renderUI({ |
219 | ! |
validate( |
220 | ! |
need( |
221 | ! |
length(shinyTree::get_selected(input$tree)) > 0, |
222 | ! |
"Please select a file." |
223 |
) |
|
224 |
) |
|
225 | ||
226 | ! |
obj <- shinyTree::get_selected(input$tree, format = "names")[[1]] |
227 | ! |
repo <- attr(obj, "ancestry") |
228 | ! |
repo_collapsed <- if (length(repo) > 1) paste0(repo, collapse = "/") else repo |
229 | ! |
is_not_named <- file.exists(file.path(c(repo_collapsed, obj[1])))[1] |
230 | ||
231 | ! |
if (is_not_named) { |
232 | ! |
selected_path <- do.call("file.path", as.list(c(repo, obj[1]))) |
233 |
} else { |
|
234 | ! |
if (length(repo) == 0) { |
235 | ! |
selected_path <- do.call("file.path", as.list(attr(input$tree[[obj[1]]], "ancestry"))) |
236 |
} else { |
|
237 | ! |
selected_path <- do.call("file.path", as.list(attr(input$tree[[repo]][[obj[1]]], "ancestry"))) |
238 |
} |
|
239 |
} |
|
240 | ||
241 | ! |
validate( |
242 | ! |
need( |
243 | ! |
!isTRUE(file.info(selected_path)$isdir) && length(selected_path) > 0, |
244 | ! |
"Please select a single file." |
245 |
) |
|
246 |
) |
|
247 | ! |
display_file(selected_path) |
248 |
}) |
|
249 | ||
250 | ! |
onStop(function() { |
251 | ! |
removeResourcePath(basename(temp_dir)) |
252 | ! |
unlink(temp_dir) |
253 |
}) |
|
254 |
}) |
|
255 |
} |
1 |
.onLoad <- function(libname, pkgname) { |
|
2 | ! |
teal.logger::register_logger(namespace = "teal.modules.general") |
3 | ! |
teal.logger::register_handlers("teal.modules.general") |
4 |
} |
|
5 | ||
6 |
### global variables |
|
7 |
ggplot_themes <- c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void") |
|
8 | ||
9 |
#' @importFrom lifecycle deprecated |
|
10 |
interactive <- NULL |