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 |
#' @param decorators `r roxygen_decorators_param("tm_g_distribution")` |
|
27 |
#' |
|
28 |
#' @inherit shared_params return |
|
29 |
#' |
|
30 |
#' @section Decorating `tm_g_distribution`: |
|
31 |
#' |
|
32 |
#' This module generates the following objects, which can be modified in place using decorators:: |
|
33 |
#' - `histogram_plot` (`ggplot2`) |
|
34 |
#' - `qq_plot` (`data.frame`) |
|
35 |
#' - `summary_table` (`data.frame`) |
|
36 |
#' - `test_table` (`data.frame`) |
|
37 |
#' |
|
38 |
#' Decorators can be applied to all outputs or only to specific objects using a |
|
39 |
#' named list of `teal_transform_module` objects. |
|
40 |
#' The `"default"` name is reserved for decorators that are applied to all outputs. |
|
41 |
#' See code snippet below: |
|
42 |
#' |
|
43 |
#' ``` |
|
44 |
#' tm_g_distribution( |
|
45 |
#' ..., # arguments for module |
|
46 |
#' decorators = list( |
|
47 |
#' default = list(teal_transform_module(...)), # applied to all outputs |
|
48 |
#' histogram_plot = list(teal_transform_module(...)), # applied only to `histogram_plot` output |
|
49 |
#' qq_plot = list(teal_transform_module(...)) # applied only to `qq_plot` output |
|
50 |
#' summary_table = list(teal_transform_module(...)) # applied only to `summary_table` output |
|
51 |
#' test_table = list(teal_transform_module(...)) # applied only to `test_table` output |
|
52 |
#' ) |
|
53 |
#' ) |
|
54 |
#' ``` |
|
55 |
#' |
|
56 |
#' For additional details and examples of decorators, refer to the vignette |
|
57 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
58 |
#' |
|
59 |
#' @examplesShinylive |
|
60 |
#' library(teal.modules.general) |
|
61 |
#' interactive <- function() TRUE |
|
62 |
#' {{ next_example }} |
|
63 |
# nolint start: line_length_linter. |
|
64 |
#' @examplesIf require("ggpmisc", quietly = TRUE) && require("ggpp", quietly = TRUE) && require("goftest", quietly = TRUE) && require("MASS", quietly = TRUE) && require("broom", quietly = TRUE) |
|
65 |
# nolint end: line_length_linter. |
|
66 |
#' # general data example |
|
67 |
#' data <- teal_data() |
|
68 |
#' data <- within(data, { |
|
69 |
#' iris <- iris |
|
70 |
#' }) |
|
71 |
#' |
|
72 |
#' app <- init( |
|
73 |
#' data = data, |
|
74 |
#' modules = list( |
|
75 |
#' tm_g_distribution( |
|
76 |
#' dist_var = data_extract_spec( |
|
77 |
#' dataname = "iris", |
|
78 |
#' select = select_spec(variable_choices("iris"), "Petal.Length") |
|
79 |
#' ) |
|
80 |
#' ) |
|
81 |
#' ) |
|
82 |
#' ) |
|
83 |
#' if (interactive()) { |
|
84 |
#' shinyApp(app$ui, app$server) |
|
85 |
#' } |
|
86 |
#' |
|
87 |
#' @examplesShinylive |
|
88 |
#' library(teal.modules.general) |
|
89 |
#' interactive <- function() TRUE |
|
90 |
#' {{ next_example }} |
|
91 |
# nolint start: line_length_linter. |
|
92 |
#' @examplesIf require("ggpmisc", quietly = TRUE) && require("ggpp", quietly = TRUE) && require("goftest", quietly = TRUE) && require("MASS", quietly = TRUE) && require("broom", quietly = TRUE) |
|
93 |
# nolint end: line_length_linter. |
|
94 |
#' # CDISC data example |
|
95 |
#' data <- teal_data() |
|
96 |
#' data <- within(data, { |
|
97 |
#' ADSL <- teal.data::rADSL |
|
98 |
#' }) |
|
99 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
100 |
#' |
|
101 |
#' vars1 <- choices_selected( |
|
102 |
#' variable_choices(data[["ADSL"]], c("ARM", "COUNTRY", "SEX")), |
|
103 |
#' selected = NULL |
|
104 |
#' ) |
|
105 |
#' |
|
106 |
#' app <- init( |
|
107 |
#' data = data, |
|
108 |
#' modules = modules( |
|
109 |
#' tm_g_distribution( |
|
110 |
#' dist_var = data_extract_spec( |
|
111 |
#' dataname = "ADSL", |
|
112 |
#' select = select_spec( |
|
113 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1")), |
|
114 |
#' selected = "BMRKR1", |
|
115 |
#' multiple = FALSE, |
|
116 |
#' fixed = FALSE |
|
117 |
#' ) |
|
118 |
#' ), |
|
119 |
#' strata_var = data_extract_spec( |
|
120 |
#' dataname = "ADSL", |
|
121 |
#' filter = filter_spec( |
|
122 |
#' vars = vars1, |
|
123 |
#' multiple = TRUE |
|
124 |
#' ) |
|
125 |
#' ), |
|
126 |
#' group_var = data_extract_spec( |
|
127 |
#' dataname = "ADSL", |
|
128 |
#' filter = filter_spec( |
|
129 |
#' vars = vars1, |
|
130 |
#' multiple = TRUE |
|
131 |
#' ) |
|
132 |
#' ) |
|
133 |
#' ) |
|
134 |
#' ) |
|
135 |
#' ) |
|
136 |
#' if (interactive()) { |
|
137 |
#' shinyApp(app$ui, app$server) |
|
138 |
#' } |
|
139 |
#' |
|
140 |
#' @export |
|
141 |
#' |
|
142 |
tm_g_distribution <- function(label = "Distribution Module", |
|
143 |
dist_var, |
|
144 |
strata_var = NULL, |
|
145 |
group_var = NULL, |
|
146 |
freq = FALSE, |
|
147 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
148 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
149 |
bins = c(30L, 1L, 100L), |
|
150 |
plot_height = c(600, 200, 2000), |
|
151 |
plot_width = NULL, |
|
152 |
pre_output = NULL, |
|
153 |
post_output = NULL, |
|
154 |
decorators = NULL) { |
|
155 | ! |
message("Initializing tm_g_distribution") |
156 | ||
157 |
# Requires Suggested packages |
|
158 | ! |
extra_packages <- c("ggpmisc", "ggpp", "goftest", "MASS", "broom") |
159 | ! |
missing_packages <- Filter(function(x) !requireNamespace(x, quietly = TRUE), extra_packages) |
160 | ! |
if (length(missing_packages) > 0L) { |
161 | ! |
stop(sprintf( |
162 | ! |
"Cannot load package(s): %s.\nInstall or restart your session.", |
163 | ! |
toString(missing_packages) |
164 |
)) |
|
165 |
} |
|
166 | ||
167 |
# Normalize the parameters |
|
168 | ! |
if (inherits(dist_var, "data_extract_spec")) dist_var <- list(dist_var) |
169 | ! |
if (inherits(strata_var, "data_extract_spec")) strata_var <- list(strata_var) |
170 | ! |
if (inherits(group_var, "data_extract_spec")) group_var <- list(group_var) |
171 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
172 | ||
173 |
# Start of assertions |
|
174 | ! |
checkmate::assert_string(label) |
175 | ||
176 | ! |
checkmate::assert_list(dist_var, "data_extract_spec") |
177 | ! |
checkmate::assert_false(dist_var[[1L]]$select$multiple) |
178 | ||
179 | ! |
checkmate::assert_list(strata_var, types = "data_extract_spec", null.ok = TRUE) |
180 | ! |
checkmate::assert_list(group_var, types = "data_extract_spec", null.ok = TRUE) |
181 | ! |
checkmate::assert_flag(freq) |
182 | ! |
ggtheme <- match.arg(ggtheme) |
183 | ||
184 | ! |
plot_choices <- c("Histogram", "QQplot") |
185 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
186 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
187 | ||
188 | ! |
if (length(bins) == 1) { |
189 | ! |
checkmate::assert_numeric(bins, any.missing = FALSE, lower = 1) |
190 |
} else { |
|
191 | ! |
checkmate::assert_numeric(bins, len = 3, any.missing = FALSE, lower = 1) |
192 | ! |
checkmate::assert_numeric(bins[1], lower = bins[2], upper = bins[3], .var.name = "bins") |
193 |
} |
|
194 | ||
195 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
196 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
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], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
201 |
) |
|
202 | ||
203 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
204 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
205 | ||
206 | ! |
available_decorators <- c("histogram_plot", "qq_plot", "test_table", "summary_table") |
207 | ! |
decorators <- normalize_decorators(decorators) |
208 | ! |
assert_decorators(decorators, null.ok = TRUE, names = available_decorators) |
209 | ||
210 |
# End of assertions |
|
211 | ||
212 |
# Make UI args |
|
213 | ! |
args <- as.list(environment()) |
214 | ||
215 | ! |
data_extract_list <- list( |
216 | ! |
dist_var = dist_var, |
217 | ! |
strata_var = strata_var, |
218 | ! |
group_var = group_var |
219 |
) |
|
220 | ||
221 | ! |
ans <- module( |
222 | ! |
label = label, |
223 | ! |
server = srv_distribution, |
224 | ! |
server_args = c( |
225 | ! |
data_extract_list, |
226 | ! |
list( |
227 | ! |
plot_height = plot_height, |
228 | ! |
plot_width = plot_width, |
229 | ! |
ggplot2_args = ggplot2_args, |
230 | ! |
decorators = decorators |
231 |
) |
|
232 |
), |
|
233 | ! |
ui = ui_distribution, |
234 | ! |
ui_args = args, |
235 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
236 |
) |
|
237 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
238 | ! |
ans |
239 |
} |
|
240 | ||
241 |
# UI function for the distribution module |
|
242 |
ui_distribution <- function(id, ...) { |
|
243 | ! |
args <- list(...) |
244 | ! |
ns <- NS(id) |
245 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$dist_var, args$strata_var, args$group_var) |
246 | ||
247 | ! |
teal.widgets::standard_layout( |
248 | ! |
output = teal.widgets::white_small_well( |
249 | ! |
tabsetPanel( |
250 | ! |
id = ns("tabs"), |
251 | ! |
tabPanel("Histogram", teal.widgets::plot_with_settings_ui(id = ns("hist_plot"))), |
252 | ! |
tabPanel("QQplot", teal.widgets::plot_with_settings_ui(id = ns("qq_plot"))) |
253 |
), |
|
254 | ! |
tags$h3("Statistics Table"), |
255 | ! |
DT::dataTableOutput(ns("summary_table")), |
256 | ! |
tags$h3("Tests"), |
257 | ! |
DT::dataTableOutput(ns("t_stats")) |
258 |
), |
|
259 | ! |
encoding = tags$div( |
260 |
### Reporter |
|
261 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
262 |
### |
|
263 | ! |
tags$label("Encodings", class = "text-primary"), |
264 | ! |
teal.transform::datanames_input(args[c("dist_var", "strata_var")]), |
265 | ! |
teal.transform::data_extract_ui( |
266 | ! |
id = ns("dist_i"), |
267 | ! |
label = "Variable", |
268 | ! |
data_extract_spec = args$dist_var, |
269 | ! |
is_single_dataset = is_single_dataset_value |
270 |
), |
|
271 | ! |
if (!is.null(args$group_var)) { |
272 | ! |
tagList( |
273 | ! |
teal.transform::data_extract_ui( |
274 | ! |
id = ns("group_i"), |
275 | ! |
label = "Group by", |
276 | ! |
data_extract_spec = args$group_var, |
277 | ! |
is_single_dataset = is_single_dataset_value |
278 |
), |
|
279 | ! |
uiOutput(ns("scales_types_ui")) |
280 |
) |
|
281 |
}, |
|
282 | ! |
if (!is.null(args$strata_var)) { |
283 | ! |
teal.transform::data_extract_ui( |
284 | ! |
id = ns("strata_i"), |
285 | ! |
label = "Stratify by", |
286 | ! |
data_extract_spec = args$strata_var, |
287 | ! |
is_single_dataset = is_single_dataset_value |
288 |
) |
|
289 |
}, |
|
290 | ! |
teal.widgets::panel_group( |
291 | ! |
conditionalPanel( |
292 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'Histogram'"), |
293 | ! |
teal.widgets::panel_item( |
294 | ! |
"Histogram", |
295 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("bins"), "Bins", args$bins, ticks = FALSE, step = 1), |
296 | ! |
shinyWidgets::prettyRadioButtons( |
297 | ! |
ns("main_type"), |
298 | ! |
label = "Plot Type:", |
299 | ! |
choices = c("Density", "Frequency"), |
300 | ! |
selected = if (!args$freq) "Density" else "Frequency", |
301 | ! |
bigger = FALSE, |
302 | ! |
inline = TRUE |
303 |
), |
|
304 | ! |
checkboxInput(ns("add_dens"), label = "Overlay Density", value = TRUE), |
305 | ! |
ui_decorate_teal_data( |
306 | ! |
ns("d_density"), |
307 | ! |
decorators = select_decorators(args$decorators, "histogram_plot") |
308 |
), |
|
309 | ! |
collapsed = FALSE |
310 |
) |
|
311 |
), |
|
312 | ! |
conditionalPanel( |
313 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'QQplot'"), |
314 | ! |
teal.widgets::panel_item( |
315 | ! |
"QQ Plot", |
316 | ! |
checkboxInput(ns("qq_line"), label = "Add diagonal line(s)", TRUE), |
317 | ! |
ui_decorate_teal_data( |
318 | ! |
ns("d_qq"), |
319 | ! |
decorators = select_decorators(args$decorators, "qq_plot") |
320 |
), |
|
321 | ! |
collapsed = FALSE |
322 |
) |
|
323 |
), |
|
324 | ! |
ui_decorate_teal_data( |
325 | ! |
ns("d_summary"), |
326 | ! |
decorators = select_decorators(args$decorators, "summary_table") |
327 |
), |
|
328 | ! |
ui_decorate_teal_data( |
329 | ! |
ns("d_test"), |
330 | ! |
decorators = select_decorators(args$decorators, "test_table") |
331 |
), |
|
332 | ! |
conditionalPanel( |
333 | ! |
condition = paste0("input['", ns("main_type"), "'] == 'Density'"), |
334 | ! |
teal.widgets::panel_item( |
335 | ! |
"Theoretical Distribution", |
336 | ! |
teal.widgets::optionalSelectInput( |
337 | ! |
ns("t_dist"), |
338 | ! |
tags$div( |
339 | ! |
class = "teal-tooltip", |
340 | ! |
tagList( |
341 | ! |
"Distribution:", |
342 | ! |
icon("circle-info"), |
343 | ! |
tags$span( |
344 | ! |
class = "tooltiptext", |
345 | ! |
"Default parameters are optimized with MASS::fitdistr function." |
346 |
) |
|
347 |
) |
|
348 |
), |
|
349 | ! |
choices = c("normal", "lognormal", "gamma", "unif"), |
350 | ! |
selected = NULL, |
351 | ! |
multiple = FALSE |
352 |
), |
|
353 | ! |
numericInput(ns("dist_param1"), label = "param1", value = NULL), |
354 | ! |
numericInput(ns("dist_param2"), label = "param2", value = NULL), |
355 | ! |
tags$span(actionButton(ns("params_reset"), "Default params")), |
356 | ! |
collapsed = FALSE |
357 |
) |
|
358 |
) |
|
359 |
), |
|
360 | ! |
teal.widgets::panel_item( |
361 | ! |
"Tests", |
362 | ! |
teal.widgets::optionalSelectInput( |
363 | ! |
ns("dist_tests"), |
364 | ! |
"Tests:", |
365 | ! |
choices = c( |
366 | ! |
"Shapiro-Wilk", |
367 | ! |
if (!is.null(args$strata_var)) "t-test (two-samples, not paired)", |
368 | ! |
if (!is.null(args$strata_var)) "one-way ANOVA", |
369 | ! |
if (!is.null(args$strata_var)) "Fligner-Killeen", |
370 | ! |
if (!is.null(args$strata_var)) "F-test", |
371 | ! |
"Kolmogorov-Smirnov (one-sample)", |
372 | ! |
"Anderson-Darling (one-sample)", |
373 | ! |
"Cramer-von Mises (one-sample)", |
374 | ! |
if (!is.null(args$strata_var)) "Kolmogorov-Smirnov (two-samples)" |
375 |
), |
|
376 | ! |
selected = NULL |
377 |
) |
|
378 |
), |
|
379 | ! |
teal.widgets::panel_item( |
380 | ! |
"Statistics Table", |
381 | ! |
sliderInput(ns("roundn"), "Round to n digits", min = 0, max = 10, value = 2) |
382 |
), |
|
383 | ! |
teal.widgets::panel_item( |
384 | ! |
title = "Plot settings", |
385 | ! |
selectInput( |
386 | ! |
inputId = ns("ggtheme"), |
387 | ! |
label = "Theme (by ggplot):", |
388 | ! |
choices = ggplot_themes, |
389 | ! |
selected = args$ggtheme, |
390 | ! |
multiple = FALSE |
391 |
) |
|
392 |
) |
|
393 |
), |
|
394 | ! |
forms = tagList( |
395 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
396 |
), |
|
397 | ! |
pre_output = args$pre_output, |
398 | ! |
post_output = args$post_output |
399 |
) |
|
400 |
} |
|
401 | ||
402 |
# Server function for the distribution module |
|
403 |
srv_distribution <- function(id, |
|
404 |
data, |
|
405 |
reporter, |
|
406 |
filter_panel_api, |
|
407 |
dist_var, |
|
408 |
strata_var, |
|
409 |
group_var, |
|
410 |
plot_height, |
|
411 |
plot_width, |
|
412 |
ggplot2_args, |
|
413 |
decorators) { |
|
414 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
415 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
416 | ! |
checkmate::assert_class(data, "reactive") |
417 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
418 | ! |
moduleServer(id, function(input, output, session) { |
419 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
420 | ||
421 | ! |
setBookmarkExclude("params_reset") |
422 | ||
423 | ! |
ns <- session$ns |
424 | ||
425 | ! |
rule_req <- function(value) { |
426 | ! |
if (isTRUE(input$dist_tests %in% c( |
427 | ! |
"Fligner-Killeen", |
428 | ! |
"t-test (two-samples, not paired)", |
429 | ! |
"F-test", |
430 | ! |
"Kolmogorov-Smirnov (two-samples)", |
431 | ! |
"one-way ANOVA" |
432 |
))) { |
|
433 | ! |
if (!shinyvalidate::input_provided(value)) { |
434 | ! |
"Please select stratify variable." |
435 |
} |
|
436 |
} |
|
437 |
} |
|
438 | ! |
rule_dupl <- function(...) { |
439 | ! |
if (identical(input$dist_tests, "Fligner-Killeen")) { |
440 | ! |
strata <- selector_list()$strata_i()$select |
441 | ! |
group <- selector_list()$group_i()$select |
442 | ! |
if (isTRUE(strata == group)) { |
443 | ! |
"Please select different variables for strata and group." |
444 |
} |
|
445 |
} |
|
446 |
} |
|
447 | ||
448 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
449 | ! |
data_extract = list( |
450 | ! |
dist_i = dist_var, |
451 | ! |
strata_i = strata_var, |
452 | ! |
group_i = group_var |
453 |
), |
|
454 | ! |
data, |
455 | ! |
select_validation_rule = list( |
456 | ! |
dist_i = shinyvalidate::sv_required("Please select a variable") |
457 |
), |
|
458 | ! |
filter_validation_rule = list( |
459 | ! |
strata_i = shinyvalidate::compose_rules( |
460 | ! |
rule_req, |
461 | ! |
rule_dupl |
462 |
), |
|
463 | ! |
group_i = rule_dupl |
464 |
) |
|
465 |
) |
|
466 | ||
467 | ! |
iv_r <- reactive({ |
468 | ! |
iv <- shinyvalidate::InputValidator$new() |
469 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list, validator_names = "dist_i") |
470 |
}) |
|
471 | ||
472 | ! |
iv_r_dist <- reactive({ |
473 | ! |
iv <- shinyvalidate::InputValidator$new() |
474 | ! |
teal.transform::compose_and_enable_validators( |
475 | ! |
iv, selector_list, |
476 | ! |
validator_names = c("strata_i", "group_i") |
477 |
) |
|
478 |
}) |
|
479 | ! |
rule_dist_1 <- function(value) { |
480 | ! |
if (!is.null(input$t_dist)) { |
481 | ! |
switch(input$t_dist, |
482 | ! |
"normal" = if (!shinyvalidate::input_provided(value)) "mean is required", |
483 | ! |
"lognormal" = if (!shinyvalidate::input_provided(value)) "meanlog is required", |
484 | ! |
"gamma" = { |
485 | ! |
if (!shinyvalidate::input_provided(value)) "shape is required" else if (value <= 0) "shape must be positive" |
486 |
}, |
|
487 | ! |
"unif" = NULL |
488 |
) |
|
489 |
} |
|
490 |
} |
|
491 | ! |
rule_dist_2 <- function(value) { |
492 | ! |
if (!is.null(input$t_dist)) { |
493 | ! |
switch(input$t_dist, |
494 | ! |
"normal" = { |
495 | ! |
if (!shinyvalidate::input_provided(value)) { |
496 | ! |
"sd is required" |
497 | ! |
} else if (value < 0) { |
498 | ! |
"sd must be non-negative" |
499 |
} |
|
500 |
}, |
|
501 | ! |
"lognormal" = { |
502 | ! |
if (!shinyvalidate::input_provided(value)) { |
503 | ! |
"sdlog is required" |
504 | ! |
} else if (value < 0) { |
505 | ! |
"sdlog must be non-negative" |
506 |
} |
|
507 |
}, |
|
508 | ! |
"gamma" = { |
509 | ! |
if (!shinyvalidate::input_provided(value)) { |
510 | ! |
"rate is required" |
511 | ! |
} else if (value <= 0) { |
512 | ! |
"rate must be positive" |
513 |
} |
|
514 |
}, |
|
515 | ! |
"unif" = NULL |
516 |
) |
|
517 |
} |
|
518 |
} |
|
519 | ||
520 | ! |
rule_dist <- function(value) { |
521 | ! |
if (isTRUE(input$tabs == "QQplot") || |
522 | ! |
isTRUE(input$dist_tests %in% c( |
523 | ! |
"Kolmogorov-Smirnov (one-sample)", |
524 | ! |
"Anderson-Darling (one-sample)", |
525 | ! |
"Cramer-von Mises (one-sample)" |
526 |
))) { |
|
527 | ! |
if (!shinyvalidate::input_provided(value)) { |
528 | ! |
"Please select the theoretical distribution." |
529 |
} |
|
530 |
} |
|
531 |
} |
|
532 | ||
533 | ! |
iv_dist <- shinyvalidate::InputValidator$new() |
534 | ! |
iv_dist$add_rule("t_dist", rule_dist) |
535 | ! |
iv_dist$add_rule("dist_param1", rule_dist_1) |
536 | ! |
iv_dist$add_rule("dist_param2", rule_dist_2) |
537 | ! |
iv_dist$enable() |
538 | ||
539 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
540 | ! |
selector_list = selector_list, |
541 | ! |
datasets = data |
542 |
) |
|
543 | ||
544 | ! |
anl_merged_q <- reactive({ |
545 | ! |
req(anl_merged_input()) |
546 | ! |
data() %>% |
547 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
548 |
}) |
|
549 | ||
550 | ! |
merged <- list( |
551 | ! |
anl_input_r = anl_merged_input, |
552 | ! |
anl_q_r = anl_merged_q |
553 |
) |
|
554 | ||
555 | ! |
output$scales_types_ui <- renderUI({ |
556 | ! |
if ("group_i" %in% names(selector_list()) && length(selector_list()$group_i()$filters[[1]]$selected) > 0) { |
557 | ! |
shinyWidgets::prettyRadioButtons( |
558 | ! |
ns("scales_type"), |
559 | ! |
label = "Scales:", |
560 | ! |
choices = c("Fixed", "Free"), |
561 | ! |
selected = "Fixed", |
562 | ! |
bigger = FALSE, |
563 | ! |
inline = TRUE |
564 |
) |
|
565 |
} |
|
566 |
}) |
|
567 | ||
568 | ! |
observeEvent( |
569 | ! |
eventExpr = list( |
570 | ! |
input$t_dist, |
571 | ! |
input$params_reset, |
572 | ! |
selector_list()$dist_i()$select |
573 |
), |
|
574 | ! |
handlerExpr = { |
575 | ! |
params <- |
576 | ! |
if (length(input$t_dist) != 0) { |
577 | ! |
get_dist_params <- function(x, dist) { |
578 | ! |
if (dist == "unif") { |
579 | ! |
return(stats::setNames(range(x, na.rm = TRUE), c("min", "max"))) |
580 |
} |
|
581 | ! |
tryCatch( |
582 | ! |
MASS::fitdistr(x, densfun = dist)$estimate, |
583 | ! |
error = function(e) c(param1 = NA_real_, param2 = NA_real_) |
584 |
) |
|
585 |
} |
|
586 | ||
587 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
588 | ! |
round(get_dist_params(as.numeric(stats::na.omit(ANL[[merge_vars()$dist_var]])), input$t_dist), 2) |
589 |
} else { |
|
590 | ! |
c("param1" = NA_real_, "param2" = NA_real_) |
591 |
} |
|
592 | ||
593 | ! |
params_vals <- unname(params) |
594 | ! |
params_names <- names(params) |
595 | ||
596 | ! |
updateNumericInput( |
597 | ! |
inputId = "dist_param1", |
598 | ! |
label = params_names[1], |
599 | ! |
value = restoreInput(ns("dist_param1"), params_vals[1]) |
600 |
) |
|
601 | ! |
updateNumericInput( |
602 | ! |
inputId = "dist_param2", |
603 | ! |
label = params_names[2], |
604 | ! |
value = restoreInput(ns("dist_param1"), params_vals[2]) |
605 |
) |
|
606 |
}, |
|
607 | ! |
ignoreInit = TRUE |
608 |
) |
|
609 | ||
610 | ! |
observeEvent(input$params_reset, { |
611 | ! |
updateActionButton(inputId = "params_reset", label = "Reset params") |
612 |
}) |
|
613 | ||
614 | ! |
merge_vars <- reactive({ |
615 | ! |
teal::validate_inputs(iv_r()) |
616 | ||
617 | ! |
dist_var <- as.vector(merged$anl_input_r()$columns_source$dist_i) |
618 | ! |
s_var <- as.vector(merged$anl_input_r()$columns_source$strata_i) |
619 | ! |
g_var <- as.vector(merged$anl_input_r()$columns_source$group_i) |
620 | ||
621 | ! |
dist_var_name <- if (length(dist_var)) as.name(dist_var) else NULL |
622 | ! |
s_var_name <- if (length(s_var)) as.name(s_var) else NULL |
623 | ! |
g_var_name <- if (length(g_var)) as.name(g_var) else NULL |
624 | ||
625 | ! |
list( |
626 | ! |
dist_var = dist_var, |
627 | ! |
s_var = s_var, |
628 | ! |
g_var = g_var, |
629 | ! |
dist_var_name = dist_var_name, |
630 | ! |
s_var_name = s_var_name, |
631 | ! |
g_var_name = g_var_name |
632 |
) |
|
633 |
}) |
|
634 | ||
635 |
# common qenv |
|
636 | ! |
common_q <- reactive({ |
637 |
# Create a private stack for this function only. |
|
638 | ||
639 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
640 | ! |
dist_var <- merge_vars()$dist_var |
641 | ! |
s_var <- merge_vars()$s_var |
642 | ! |
g_var <- merge_vars()$g_var |
643 | ||
644 | ! |
dist_var_name <- merge_vars()$dist_var_name |
645 | ! |
s_var_name <- merge_vars()$s_var_name |
646 | ! |
g_var_name <- merge_vars()$g_var_name |
647 | ||
648 | ! |
roundn <- input$roundn |
649 | ! |
dist_param1 <- input$dist_param1 |
650 | ! |
dist_param2 <- input$dist_param2 |
651 |
# isolated as dist_param1/dist_param2 already triggered the reactivity |
|
652 | ! |
t_dist <- isolate(input$t_dist) |
653 | ||
654 | ! |
qenv <- merged$anl_q_r() |
655 | ||
656 | ! |
if (length(g_var) > 0) { |
657 | ! |
validate( |
658 | ! |
need( |
659 | ! |
inherits(ANL[[g_var]], c("integer", "factor", "character")), |
660 | ! |
"Group by variable must be `factor`, `character`, or `integer`" |
661 |
) |
|
662 |
) |
|
663 | ! |
qenv <- teal.code::eval_code( |
664 | ! |
qenv, |
665 | ! |
substitute( |
666 | ! |
expr = ANL[[g_var]] <- forcats::fct_na_value_to_level(as.factor(ANL[[g_var]]), "NA"), |
667 | ! |
env = list(g_var = g_var) |
668 |
) |
|
669 |
) |
|
670 |
} |
|
671 | ||
672 | ! |
if (length(s_var) > 0) { |
673 | ! |
validate( |
674 | ! |
need( |
675 | ! |
inherits(ANL[[s_var]], c("integer", "factor", "character")), |
676 | ! |
"Stratify by variable must be `factor`, `character`, or `integer`" |
677 |
) |
|
678 |
) |
|
679 | ! |
qenv <- teal.code::eval_code( |
680 | ! |
qenv, |
681 | ! |
substitute( |
682 | ! |
expr = ANL[[s_var]] <- forcats::fct_na_value_to_level(as.factor(ANL[[s_var]]), "NA"), |
683 | ! |
env = list(s_var = s_var) |
684 |
) |
|
685 |
) |
|
686 |
} |
|
687 | ||
688 | ! |
validate(need(is.numeric(ANL[[dist_var]]), "Please select a numeric variable.")) |
689 | ! |
teal::validate_has_data(ANL, 1, complete = TRUE) |
690 | ||
691 | ! |
if (length(t_dist) != 0) { |
692 | ! |
map_distr_nams <- list( |
693 | ! |
normal = c("mean", "sd"), |
694 | ! |
lognormal = c("meanlog", "sdlog"), |
695 | ! |
gamma = c("shape", "rate"), |
696 | ! |
unif = c("min", "max") |
697 |
) |
|
698 | ! |
params_names_raw <- map_distr_nams[[t_dist]] |
699 | ||
700 | ! |
qenv <- teal.code::eval_code( |
701 | ! |
qenv, |
702 | ! |
substitute( |
703 | ! |
expr = { |
704 | ! |
params <- as.list(c(dist_param1, dist_param2)) |
705 | ! |
names(params) <- params_names_raw |
706 |
}, |
|
707 | ! |
env = list( |
708 | ! |
dist_param1 = dist_param1, |
709 | ! |
dist_param2 = dist_param2, |
710 | ! |
params_names_raw = params_names_raw |
711 |
) |
|
712 |
) |
|
713 |
) |
|
714 |
} |
|
715 | ||
716 | ! |
qenv <- if (length(s_var) == 0 && length(g_var) == 0) { |
717 | ! |
teal.code::eval_code( |
718 | ! |
qenv, |
719 | ! |
substitute( |
720 | ! |
expr = { |
721 | ! |
summary_table_data <- ANL %>% |
722 | ! |
dplyr::summarise( |
723 | ! |
min = round(min(dist_var_name, na.rm = TRUE), roundn), |
724 | ! |
median = round(stats::median(dist_var_name, na.rm = TRUE), roundn), |
725 | ! |
mean = round(mean(dist_var_name, na.rm = TRUE), roundn), |
726 | ! |
max = round(max(dist_var_name, na.rm = TRUE), roundn), |
727 | ! |
sd = round(stats::sd(dist_var_name, na.rm = TRUE), roundn), |
728 | ! |
count = dplyr::n() |
729 |
) |
|
730 |
}, |
|
731 | ! |
env = list( |
732 | ! |
dist_var_name = as.name(dist_var), |
733 | ! |
roundn = roundn |
734 |
) |
|
735 |
) |
|
736 |
) |
|
737 |
} else { |
|
738 | ! |
teal.code::eval_code( |
739 | ! |
qenv, |
740 | ! |
substitute( |
741 | ! |
expr = { |
742 | ! |
strata_vars <- strata_vars_raw |
743 | ! |
summary_table_data <- ANL %>% |
744 | ! |
dplyr::group_by_at(dplyr::vars(dplyr::any_of(strata_vars))) %>% |
745 | ! |
dplyr::summarise( |
746 | ! |
min = round(min(dist_var_name, na.rm = TRUE), roundn), |
747 | ! |
median = round(stats::median(dist_var_name, na.rm = TRUE), roundn), |
748 | ! |
mean = round(mean(dist_var_name, na.rm = TRUE), roundn), |
749 | ! |
max = round(max(dist_var_name, na.rm = TRUE), roundn), |
750 | ! |
sd = round(stats::sd(dist_var_name, na.rm = TRUE), roundn), |
751 | ! |
count = dplyr::n() |
752 |
) |
|
753 |
}, |
|
754 | ! |
env = list( |
755 | ! |
dist_var_name = dist_var_name, |
756 | ! |
strata_vars_raw = c(g_var, s_var), |
757 | ! |
roundn = roundn |
758 |
) |
|
759 |
) |
|
760 |
) |
|
761 |
} |
|
762 | ! |
if (iv_r()$is_valid()) { |
763 | ! |
within(qenv, { |
764 | ! |
summary_table <- DT::datatable( |
765 | ! |
summary_table_data, |
766 | ! |
options = list( |
767 | ! |
autoWidth = TRUE, |
768 | ! |
columnDefs = list(list(width = "200px", targets = "_all")) |
769 |
), |
|
770 | ! |
rownames = FALSE |
771 |
) |
|
772 |
}) |
|
773 |
} else { |
|
774 | ! |
within(qenv, summary_table <- NULL) |
775 |
} |
|
776 |
}) |
|
777 | ||
778 |
# distplot qenv ---- |
|
779 | ! |
dist_q <- eventReactive( |
780 | ! |
eventExpr = { |
781 | ! |
common_q() |
782 | ! |
input$scales_type |
783 | ! |
input$main_type |
784 | ! |
input$bins |
785 | ! |
input$add_dens |
786 | ! |
is.null(input$ggtheme) |
787 |
}, |
|
788 | ! |
valueExpr = { |
789 | ! |
dist_var <- merge_vars()$dist_var |
790 | ! |
s_var <- merge_vars()$s_var |
791 | ! |
g_var <- merge_vars()$g_var |
792 | ! |
dist_var_name <- merge_vars()$dist_var_name |
793 | ! |
s_var_name <- merge_vars()$s_var_name |
794 | ! |
g_var_name <- merge_vars()$g_var_name |
795 | ! |
t_dist <- input$t_dist |
796 | ! |
dist_param1 <- input$dist_param1 |
797 | ! |
dist_param2 <- input$dist_param2 |
798 | ||
799 | ! |
scales_type <- input$scales_type |
800 | ||
801 | ! |
ndensity <- 512 |
802 | ! |
main_type_var <- input$main_type |
803 | ! |
bins_var <- input$bins |
804 | ! |
add_dens_var <- input$add_dens |
805 | ! |
ggtheme <- input$ggtheme |
806 | ||
807 | ! |
teal::validate_inputs(iv_dist) |
808 | ||
809 | ! |
qenv <- common_q() |
810 | ||
811 | ! |
m_type <- if (main_type_var == "Density") "density" else "count" |
812 | ||
813 | ! |
plot_call <- if (length(s_var) == 0 && length(g_var) == 0) { |
814 | ! |
substitute( |
815 | ! |
expr = ggplot(ANL, aes(dist_var_name)) + |
816 | ! |
geom_histogram( |
817 | ! |
position = "identity", aes(y = after_stat(m_type)), bins = bins_var, alpha = 0.3 |
818 |
), |
|
819 | ! |
env = list( |
820 | ! |
m_type = as.name(m_type), bins_var = bins_var, dist_var_name = as.name(dist_var) |
821 |
) |
|
822 |
) |
|
823 | ! |
} else if (length(s_var) != 0 && length(g_var) == 0) { |
824 | ! |
substitute( |
825 | ! |
expr = ggplot(ANL, aes(dist_var_name, col = s_var_name)) + |
826 | ! |
geom_histogram( |
827 | ! |
position = "identity", aes(y = after_stat(m_type), fill = s_var), bins = bins_var, alpha = 0.3 |
828 |
), |
|
829 | ! |
env = list( |
830 | ! |
m_type = as.name(m_type), |
831 | ! |
bins_var = bins_var, |
832 | ! |
dist_var_name = dist_var_name, |
833 | ! |
s_var = as.name(s_var), |
834 | ! |
s_var_name = s_var_name |
835 |
) |
|
836 |
) |
|
837 | ! |
} else if (length(s_var) == 0 && length(g_var) != 0) { |
838 | ! |
req(scales_type) |
839 | ! |
substitute( |
840 | ! |
expr = ggplot(ANL[ANL[[g_var]] != "NA", ], aes(dist_var_name)) + |
841 | ! |
geom_histogram( |
842 | ! |
position = "identity", aes(y = after_stat(m_type)), bins = bins_var, alpha = 0.3 |
843 |
) + |
|
844 | ! |
facet_wrap(~g_var_name, ncol = 1, scales = scales_raw), |
845 | ! |
env = list( |
846 | ! |
m_type = as.name(m_type), |
847 | ! |
bins_var = bins_var, |
848 | ! |
dist_var_name = dist_var_name, |
849 | ! |
g_var = g_var, |
850 | ! |
g_var_name = g_var_name, |
851 | ! |
scales_raw = tolower(scales_type) |
852 |
) |
|
853 |
) |
|
854 |
} else { |
|
855 | ! |
req(scales_type) |
856 | ! |
substitute( |
857 | ! |
expr = ggplot(ANL[ANL[[g_var]] != "NA", ], aes(dist_var_name, col = s_var_name)) + |
858 | ! |
geom_histogram( |
859 | ! |
position = "identity", |
860 | ! |
aes(y = after_stat(m_type), fill = s_var), bins = bins_var, alpha = 0.3 |
861 |
) + |
|
862 | ! |
facet_wrap(~g_var_name, ncol = 1, scales = scales_raw), |
863 | ! |
env = list( |
864 | ! |
m_type = as.name(m_type), |
865 | ! |
bins_var = bins_var, |
866 | ! |
dist_var_name = dist_var_name, |
867 | ! |
g_var = g_var, |
868 | ! |
s_var = as.name(s_var), |
869 | ! |
g_var_name = g_var_name, |
870 | ! |
s_var_name = s_var_name, |
871 | ! |
scales_raw = tolower(scales_type) |
872 |
) |
|
873 |
) |
|
874 |
} |
|
875 | ||
876 | ! |
if (add_dens_var) { |
877 | ! |
plot_call <- substitute( |
878 | ! |
expr = plot_call + |
879 | ! |
stat_density( |
880 | ! |
aes(y = after_stat(const * m_type2)), |
881 | ! |
geom = "line", |
882 | ! |
position = "identity", |
883 | ! |
alpha = 0.5, |
884 | ! |
size = 2, |
885 | ! |
n = ndensity |
886 |
), |
|
887 | ! |
env = list( |
888 | ! |
plot_call = plot_call, |
889 | ! |
const = if (main_type_var == "Density") { |
890 | ! |
1 |
891 |
} else { |
|
892 | ! |
diff(range(qenv[["ANL"]][[dist_var]], na.rm = TRUE)) / bins_var |
893 |
}, |
|
894 | ! |
m_type2 = if (main_type_var == "Density") as.name("density") else as.name("count"), |
895 | ! |
ndensity = ndensity |
896 |
) |
|
897 |
) |
|
898 |
} |
|
899 | ||
900 | ! |
if (length(t_dist) != 0 && main_type_var == "Density" && length(g_var) == 0 && length(s_var) == 0) { |
901 | ! |
qenv <- teal.code::eval_code( |
902 | ! |
qenv, |
903 | ! |
substitute( |
904 | ! |
df_params <- as.data.frame(append(params, list(name = t_dist))), |
905 | ! |
env = list(t_dist = t_dist) |
906 |
) |
|
907 |
) |
|
908 | ! |
datas <- quote(data.frame(x = 0.7, y = 1, tb = I(list(df_params = df_params)))) |
909 | ! |
label <- quote(tb) |
910 | ||
911 | ! |
plot_call <- substitute( |
912 | ! |
expr = plot_call + ggpp::geom_table_npc( |
913 | ! |
data = data, |
914 | ! |
aes(npcx = x, npcy = y, label = label), |
915 | ! |
hjust = 0, vjust = 1, size = 4 |
916 |
), |
|
917 | ! |
env = list(plot_call = plot_call, data = datas, label = label) |
918 |
) |
|
919 |
} |
|
920 | ||
921 | ! |
if ( |
922 | ! |
length(s_var) == 0 && |
923 | ! |
length(g_var) == 0 && |
924 | ! |
main_type_var == "Density" && |
925 | ! |
length(t_dist) != 0 && |
926 | ! |
main_type_var == "Density" |
927 |
) { |
|
928 | ! |
map_dist <- stats::setNames( |
929 | ! |
c("dnorm", "dlnorm", "dgamma", "dunif"), |
930 | ! |
c("normal", "lognormal", "gamma", "unif") |
931 |
) |
|
932 | ! |
plot_call <- substitute( |
933 | ! |
expr = plot_call + stat_function( |
934 | ! |
data = data.frame(x = range(ANL[[dist_var]]), color = mapped_dist), |
935 | ! |
aes(x, color = color), |
936 | ! |
fun = mapped_dist_name, |
937 | ! |
n = ndensity, |
938 | ! |
size = 2, |
939 | ! |
args = params |
940 |
) + |
|
941 | ! |
scale_color_manual(values = stats::setNames("blue", mapped_dist), aesthetics = "color"), |
942 | ! |
env = list( |
943 | ! |
plot_call = plot_call, |
944 | ! |
dist_var = dist_var, |
945 | ! |
ndensity = ndensity, |
946 | ! |
mapped_dist = unname(map_dist[t_dist]), |
947 | ! |
mapped_dist_name = as.name(unname(map_dist[t_dist])) |
948 |
) |
|
949 |
) |
|
950 |
} |
|
951 | ||
952 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
953 | ! |
user_plot = ggplot2_args[["Histogram"]], |
954 | ! |
user_default = ggplot2_args$default |
955 |
) |
|
956 | ||
957 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
958 | ! |
all_ggplot2_args, |
959 | ! |
ggtheme = ggtheme |
960 |
) |
|
961 | ||
962 | ! |
teal.code::eval_code( |
963 | ! |
qenv, |
964 | ! |
substitute( |
965 | ! |
expr = histogram_plot <- plot_call, |
966 | ! |
env = list(plot_call = Reduce(function(x, y) call("+", x, y), c(plot_call, parsed_ggplot2_args))) |
967 |
) |
|
968 |
) |
|
969 |
} |
|
970 |
) |
|
971 | ||
972 |
# qqplot qenv ---- |
|
973 | ! |
qq_q <- eventReactive( |
974 | ! |
eventExpr = { |
975 | ! |
common_q() |
976 | ! |
input$scales_type |
977 | ! |
input$qq_line |
978 | ! |
is.null(input$ggtheme) |
979 | ! |
input$tabs |
980 |
}, |
|
981 | ! |
valueExpr = { |
982 | ! |
dist_var <- merge_vars()$dist_var |
983 | ! |
s_var <- merge_vars()$s_var |
984 | ! |
g_var <- merge_vars()$g_var |
985 | ! |
dist_var_name <- merge_vars()$dist_var_name |
986 | ! |
s_var_name <- merge_vars()$s_var_name |
987 | ! |
g_var_name <- merge_vars()$g_var_name |
988 | ! |
dist_param1 <- input$dist_param1 |
989 | ! |
dist_param2 <- input$dist_param2 |
990 | ||
991 | ! |
scales_type <- input$scales_type |
992 | ! |
ggtheme <- input$ggtheme |
993 | ||
994 | ! |
teal::validate_inputs(iv_r_dist(), iv_dist) |
995 | ! |
t_dist <- req(input$t_dist) # Not validated when tab is not selected |
996 | ! |
qenv <- common_q() |
997 | ||
998 | ! |
plot_call <- if (length(s_var) == 0 && length(g_var) == 0) { |
999 | ! |
substitute( |
1000 | ! |
expr = ggplot(ANL, aes_string(sample = dist_var)), |
1001 | ! |
env = list(dist_var = dist_var) |
1002 |
) |
|
1003 | ! |
} else if (length(s_var) != 0 && length(g_var) == 0) { |
1004 | ! |
substitute( |
1005 | ! |
expr = ggplot(ANL, aes_string(sample = dist_var, color = s_var)), |
1006 | ! |
env = list(dist_var = dist_var, s_var = s_var) |
1007 |
) |
|
1008 | ! |
} else if (length(s_var) == 0 && length(g_var) != 0) { |
1009 | ! |
substitute( |
1010 | ! |
expr = ggplot(ANL[ANL[[g_var]] != "NA", ], aes_string(sample = dist_var)) + |
1011 | ! |
facet_wrap(~g_var_name, ncol = 1, scales = scales_raw), |
1012 | ! |
env = list( |
1013 | ! |
dist_var = dist_var, |
1014 | ! |
g_var = g_var, |
1015 | ! |
g_var_name = g_var_name, |
1016 | ! |
scales_raw = tolower(scales_type) |
1017 |
) |
|
1018 |
) |
|
1019 |
} else { |
|
1020 | ! |
substitute( |
1021 | ! |
expr = ggplot(ANL[ANL[[g_var]] != "NA", ], aes_string(sample = dist_var, color = s_var)) + |
1022 | ! |
facet_wrap(~g_var_name, ncol = 1, scales = scales_raw), |
1023 | ! |
env = list( |
1024 | ! |
dist_var = dist_var, |
1025 | ! |
g_var = g_var, |
1026 | ! |
s_var = s_var, |
1027 | ! |
g_var_name = g_var_name, |
1028 | ! |
scales_raw = tolower(scales_type) |
1029 |
) |
|
1030 |
) |
|
1031 |
} |
|
1032 | ||
1033 | ! |
map_dist <- stats::setNames( |
1034 | ! |
c("qnorm", "qlnorm", "qgamma", "qunif"), |
1035 | ! |
c("normal", "lognormal", "gamma", "unif") |
1036 |
) |
|
1037 | ||
1038 | ! |
plot_call <- substitute( |
1039 | ! |
expr = plot_call + |
1040 | ! |
stat_qq(distribution = mapped_dist, dparams = params), |
1041 | ! |
env = list(plot_call = plot_call, mapped_dist = as.name(unname(map_dist[t_dist]))) |
1042 |
) |
|
1043 | ||
1044 | ! |
if (length(t_dist) != 0 && length(g_var) == 0 && length(s_var) == 0) { |
1045 | ! |
qenv <- teal.code::eval_code( |
1046 | ! |
qenv, |
1047 | ! |
substitute( |
1048 | ! |
df_params <- as.data.frame(append(params, list(name = t_dist))), |
1049 | ! |
env = list(t_dist = t_dist) |
1050 |
) |
|
1051 |
) |
|
1052 | ! |
datas <- quote(data.frame(x = 0.7, y = 1, tb = I(list(df_params = df_params)))) |
1053 | ! |
label <- quote(tb) |
1054 | ||
1055 | ! |
plot_call <- substitute( |
1056 | ! |
expr = plot_call + |
1057 | ! |
ggpp::geom_table_npc( |
1058 | ! |
data = data, |
1059 | ! |
aes(npcx = x, npcy = y, label = label), |
1060 | ! |
hjust = 0, |
1061 | ! |
vjust = 1, |
1062 | ! |
size = 4 |
1063 |
), |
|
1064 | ! |
env = list( |
1065 | ! |
plot_call = plot_call, |
1066 | ! |
data = datas, |
1067 | ! |
label = label |
1068 |
) |
|
1069 |
) |
|
1070 |
} |
|
1071 | ||
1072 | ! |
if (isTRUE(input$qq_line)) { |
1073 | ! |
plot_call <- substitute( |
1074 | ! |
expr = plot_call + |
1075 | ! |
stat_qq_line(distribution = mapped_dist, dparams = params), |
1076 | ! |
env = list(plot_call = plot_call, mapped_dist = as.name(unname(map_dist[t_dist]))) |
1077 |
) |
|
1078 |
} |
|
1079 | ||
1080 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
1081 | ! |
user_plot = ggplot2_args[["QQplot"]], |
1082 | ! |
user_default = ggplot2_args$default, |
1083 | ! |
module_plot = teal.widgets::ggplot2_args(labs = list(x = "theoretical", y = "sample")) |
1084 |
) |
|
1085 | ||
1086 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
1087 | ! |
all_ggplot2_args, |
1088 | ! |
ggtheme = ggtheme |
1089 |
) |
|
1090 | ||
1091 | ! |
teal.code::eval_code( |
1092 | ! |
qenv, |
1093 | ! |
substitute( |
1094 | ! |
expr = qq_plot <- plot_call, |
1095 | ! |
env = list(plot_call = Reduce(function(x, y) call("+", x, y), c(plot_call, parsed_ggplot2_args))) |
1096 |
) |
|
1097 |
) |
|
1098 |
} |
|
1099 |
) |
|
1100 | ||
1101 |
# test qenv ---- |
|
1102 | ! |
test_q <- eventReactive( |
1103 | ! |
ignoreNULL = FALSE, |
1104 | ! |
eventExpr = { |
1105 | ! |
common_q() |
1106 | ! |
input$dist_param1 |
1107 | ! |
input$dist_param2 |
1108 | ! |
input$dist_tests |
1109 |
}, |
|
1110 | ! |
valueExpr = { |
1111 |
# Create a private stack for this function only. |
|
1112 | ! |
ANL <- common_q()[["ANL"]] |
1113 | ||
1114 | ! |
dist_var <- merge_vars()$dist_var |
1115 | ! |
s_var <- merge_vars()$s_var |
1116 | ! |
g_var <- merge_vars()$g_var |
1117 | ||
1118 | ! |
dist_var_name <- merge_vars()$dist_var_name |
1119 | ! |
s_var_name <- merge_vars()$s_var_name |
1120 | ! |
g_var_name <- merge_vars()$g_var_name |
1121 | ||
1122 | ! |
dist_param1 <- input$dist_param1 |
1123 | ! |
dist_param2 <- input$dist_param2 |
1124 | ! |
dist_tests <- input$dist_tests |
1125 | ! |
t_dist <- input$t_dist |
1126 | ||
1127 | ! |
validate(need(dist_tests, "Please select a test")) |
1128 | ||
1129 | ! |
teal::validate_inputs(iv_dist) |
1130 | ||
1131 | ! |
if (length(s_var) > 0 || length(g_var) > 0) { |
1132 | ! |
counts <- ANL %>% |
1133 | ! |
dplyr::group_by_at(dplyr::vars(dplyr::any_of(c(s_var, g_var)))) %>% |
1134 | ! |
dplyr::summarise(n = dplyr::n()) |
1135 | ||
1136 | ! |
validate(need(all(counts$n > 5), "Please select strata*group with at least 5 observation each.")) |
1137 |
} |
|
1138 | ||
1139 | ||
1140 | ! |
if (dist_tests %in% c( |
1141 | ! |
"t-test (two-samples, not paired)", |
1142 | ! |
"F-test", |
1143 | ! |
"Kolmogorov-Smirnov (two-samples)" |
1144 |
)) { |
|
1145 | ! |
if (length(g_var) == 0 && length(s_var) > 0) { |
1146 | ! |
validate(need( |
1147 | ! |
length(unique(ANL[[s_var]])) == 2, |
1148 | ! |
"Please select stratify variable with 2 levels." |
1149 |
)) |
|
1150 |
} |
|
1151 | ! |
if (length(g_var) > 0 && length(s_var) > 0) { |
1152 | ! |
validate(need( |
1153 | ! |
all(stats::na.omit(as.vector( |
1154 | ! |
tapply(ANL[[s_var]], list(ANL[[g_var]]), function(x) length(unique(x))) == 2 |
1155 |
))), |
|
1156 | ! |
"Please select stratify variable with 2 levels, per each group." |
1157 |
)) |
|
1158 |
} |
|
1159 |
} |
|
1160 | ||
1161 | ! |
map_dist <- stats::setNames( |
1162 | ! |
c("pnorm", "plnorm", "pgamma", "punif"), |
1163 | ! |
c("normal", "lognormal", "gamma", "unif") |
1164 |
) |
|
1165 | ! |
sks_args <- list( |
1166 | ! |
test = quote(stats::ks.test), |
1167 | ! |
args = bquote(append(list(.[[.(dist_var)]], .(map_dist[t_dist])), params)), |
1168 | ! |
groups = c(g_var, s_var) |
1169 |
) |
|
1170 | ! |
ssw_args <- list( |
1171 | ! |
test = quote(stats::shapiro.test), |
1172 | ! |
args = bquote(list(.[[.(dist_var)]])), |
1173 | ! |
groups = c(g_var, s_var) |
1174 |
) |
|
1175 | ! |
mfil_args <- list( |
1176 | ! |
test = quote(stats::fligner.test), |
1177 | ! |
args = bquote(list(.[[.(dist_var)]], .[[.(s_var)]])), |
1178 | ! |
groups = c(g_var) |
1179 |
) |
|
1180 | ! |
sad_args <- list( |
1181 | ! |
test = quote(goftest::ad.test), |
1182 | ! |
args = bquote(append(list(.[[.(dist_var)]], .(map_dist[t_dist])), params)), |
1183 | ! |
groups = c(g_var, s_var) |
1184 |
) |
|
1185 | ! |
scvm_args <- list( |
1186 | ! |
test = quote(goftest::cvm.test), |
1187 | ! |
args = bquote(append(list(.[[.(dist_var)]], .(map_dist[t_dist])), params)), |
1188 | ! |
groups = c(g_var, s_var) |
1189 |
) |
|
1190 | ! |
manov_args <- list( |
1191 | ! |
test = quote(stats::aov), |
1192 | ! |
args = bquote(list(stats::formula(.(dist_var_name) ~ .(s_var_name)), .)), |
1193 | ! |
groups = c(g_var) |
1194 |
) |
|
1195 | ! |
mt_args <- list( |
1196 | ! |
test = quote(stats::t.test), |
1197 | ! |
args = bquote(unname(split(.[[.(dist_var)]], .[[.(s_var)]], drop = TRUE))), |
1198 | ! |
groups = c(g_var) |
1199 |
) |
|
1200 | ! |
mv_args <- list( |
1201 | ! |
test = quote(stats::var.test), |
1202 | ! |
args = bquote(unname(split(.[[.(dist_var)]], .[[.(s_var)]], drop = TRUE))), |
1203 | ! |
groups = c(g_var) |
1204 |
) |
|
1205 | ! |
mks_args <- list( |
1206 | ! |
test = quote(stats::ks.test), |
1207 | ! |
args = bquote(unname(split(.[[.(dist_var)]], .[[.(s_var)]], drop = TRUE))), |
1208 | ! |
groups = c(g_var) |
1209 |
) |
|
1210 | ||
1211 | ! |
tests_base <- switch(dist_tests, |
1212 | ! |
"Kolmogorov-Smirnov (one-sample)" = sks_args, |
1213 | ! |
"Shapiro-Wilk" = ssw_args, |
1214 | ! |
"Fligner-Killeen" = mfil_args, |
1215 | ! |
"one-way ANOVA" = manov_args, |
1216 | ! |
"t-test (two-samples, not paired)" = mt_args, |
1217 | ! |
"F-test" = mv_args, |
1218 | ! |
"Kolmogorov-Smirnov (two-samples)" = mks_args, |
1219 | ! |
"Anderson-Darling (one-sample)" = sad_args, |
1220 | ! |
"Cramer-von Mises (one-sample)" = scvm_args |
1221 |
) |
|
1222 | ||
1223 | ! |
env <- list( |
1224 | ! |
t_test = t_dist, |
1225 | ! |
dist_var = dist_var, |
1226 | ! |
g_var = g_var, |
1227 | ! |
s_var = s_var, |
1228 | ! |
args = tests_base$args, |
1229 | ! |
groups = tests_base$groups, |
1230 | ! |
test = tests_base$test, |
1231 | ! |
dist_var_name = dist_var_name, |
1232 | ! |
g_var_name = g_var_name, |
1233 | ! |
s_var_name = s_var_name |
1234 |
) |
|
1235 | ||
1236 | ! |
qenv <- common_q() |
1237 | ||
1238 | ! |
if (length(s_var) == 0 && length(g_var) == 0) { |
1239 | ! |
qenv <- teal.code::eval_code( |
1240 | ! |
qenv, |
1241 | ! |
substitute( |
1242 | ! |
expr = { |
1243 | ! |
test_table_data <- ANL %>% |
1244 | ! |
dplyr::select(dist_var) %>% |
1245 | ! |
with(., broom::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( |
1253 | ! |
qenv, |
1254 | ! |
substitute( |
1255 | ! |
expr = { |
1256 | ! |
test_table_data <- ANL %>% |
1257 | ! |
dplyr::select(dist_var, s_var, g_var) %>% |
1258 | ! |
dplyr::group_by_at(dplyr::vars(dplyr::any_of(groups))) %>% |
1259 | ! |
dplyr::do(tests = broom::glance(do.call(test, args))) %>% |
1260 | ! |
tidyr::unnest(tests) %>% |
1261 | ! |
dplyr::mutate_if(is.numeric, round, 3) |
1262 |
}, |
|
1263 | ! |
env = env |
1264 |
) |
|
1265 |
) |
|
1266 |
} |
|
1267 |
} |
|
1268 |
) |
|
1269 | ||
1270 |
# outputs ---- |
|
1271 |
## building main qenv |
|
1272 | ! |
output_common_q <- reactive({ |
1273 |
# wrapped in if since could lead into validate error - we do want to continue |
|
1274 | ! |
test_q_out <- try(test_q(), silent = TRUE) |
1275 | ! |
if (!inherits(test_q_out, c("try-error", "error"))) { |
1276 | ! |
c( |
1277 | ! |
common_q(), |
1278 | ! |
within(test_q_out, { |
1279 | ! |
test_table <- DT::datatable( |
1280 | ! |
test_table_data, |
1281 | ! |
options = list(scrollX = TRUE), |
1282 | ! |
rownames = FALSE |
1283 |
) |
|
1284 |
}) |
|
1285 |
) |
|
1286 |
} else { |
|
1287 | ! |
within(common_q(), test_table <- NULL) |
1288 |
} |
|
1289 |
}) |
|
1290 | ||
1291 | ! |
output_dist_q <- reactive(c(output_common_q(), req(dist_q()))) |
1292 | ! |
output_qq_q <- reactive(c(output_common_q(), req(qq_q()))) |
1293 | ||
1294 | ! |
decorated_output_dist_q <- srv_decorate_teal_data( |
1295 | ! |
"d_density", |
1296 | ! |
data = output_dist_q, |
1297 | ! |
decorators = select_decorators(decorators, "histogram_plot"), |
1298 | ! |
expr = print(histogram_plot) |
1299 |
) |
|
1300 | ||
1301 | ! |
decorated_output_qq_q <- srv_decorate_teal_data( |
1302 | ! |
"d_qq", |
1303 | ! |
data = output_qq_q, |
1304 | ! |
decorators = select_decorators(decorators, "qq_plot"), |
1305 | ! |
expr = print(qq_plot) |
1306 |
) |
|
1307 | ||
1308 | ! |
decorated_output_summary_q <- srv_decorate_teal_data( |
1309 | ! |
"d_summary", |
1310 | ! |
data = output_common_q, |
1311 | ! |
decorators = select_decorators(decorators, "summary_table"), |
1312 | ! |
expr = summary_table |
1313 |
) |
|
1314 | ||
1315 | ! |
decorated_output_test_q <- srv_decorate_teal_data( |
1316 | ! |
"d_test", |
1317 | ! |
data = output_common_q, |
1318 | ! |
decorators = select_decorators(decorators, "test_table"), |
1319 | ! |
expr = test_table |
1320 |
) |
|
1321 | ||
1322 | ! |
decorated_output_q <- reactive({ |
1323 | ! |
tab <- req(input$tabs) # tab is NULL upon app launch, hence will crash without this statement |
1324 | ! |
test_q_out <- try(test_q(), silent = TRUE) |
1325 | ! |
decorated_test_q_out <- if (inherits(test_q_out, c("try-error", "error"))) { |
1326 | ! |
teal.code::qenv() |
1327 |
} else { |
|
1328 | ! |
decorated_output_test_q() |
1329 |
} |
|
1330 | ||
1331 | ! |
out_q <- switch(tab, |
1332 | ! |
Histogram = decorated_output_dist_q(), |
1333 | ! |
QQplot = decorated_output_qq_q() |
1334 |
) |
|
1335 | ! |
c(out_q, decorated_output_summary_q(), decorated_test_q_out) |
1336 |
}) |
|
1337 | ||
1338 | ! |
dist_r <- reactive(req(decorated_output_dist_q())[["histogram_plot"]]) |
1339 | ||
1340 | ! |
qq_r <- reactive(req(decorated_output_qq_q())[["qq_plot"]]) |
1341 | ||
1342 | ! |
output$summary_table <- DT::renderDataTable(expr = decorated_output_summary_q()[["summary_table"]]) |
1343 | ||
1344 | ! |
tests_r <- reactive({ |
1345 | ! |
req(iv_r()$is_valid()) |
1346 | ! |
teal::validate_inputs(iv_r_dist()) |
1347 | ! |
req(test_q()) # Ensure original errors are displayed |
1348 | ! |
decorated_output_test_q()[["test_table"]] |
1349 |
}) |
|
1350 | ||
1351 | ! |
pws1 <- teal.widgets::plot_with_settings_srv( |
1352 | ! |
id = "hist_plot", |
1353 | ! |
plot_r = dist_r, |
1354 | ! |
height = plot_height, |
1355 | ! |
width = plot_width, |
1356 | ! |
brushing = FALSE |
1357 |
) |
|
1358 | ||
1359 | ! |
pws2 <- teal.widgets::plot_with_settings_srv( |
1360 | ! |
id = "qq_plot", |
1361 | ! |
plot_r = qq_r, |
1362 | ! |
height = plot_height, |
1363 | ! |
width = plot_width, |
1364 | ! |
brushing = FALSE |
1365 |
) |
|
1366 | ||
1367 | ! |
output$t_stats <- DT::renderDataTable( |
1368 | ! |
expr = tests_r() |
1369 |
) |
|
1370 | ||
1371 | ! |
teal.widgets::verbatim_popup_srv( |
1372 | ! |
id = "rcode", |
1373 | ! |
verbatim_content = reactive(teal.code::get_code(req(decorated_output_q()))), |
1374 | ! |
title = "R Code for distribution" |
1375 |
) |
|
1376 | ||
1377 |
### REPORTER |
|
1378 | ! |
if (with_reporter) { |
1379 | ! |
card_fun <- function(comment, label) { |
1380 | ! |
card <- teal::report_card_template( |
1381 | ! |
title = "Distribution Plot", |
1382 | ! |
label = label, |
1383 | ! |
with_filter = with_filter, |
1384 | ! |
filter_panel_api = filter_panel_api |
1385 |
) |
|
1386 | ! |
card$append_text("Plot", "header3") |
1387 | ! |
if (input$tabs == "Histogram") { |
1388 | ! |
card$append_plot(dist_r(), dim = pws1$dim()) |
1389 | ! |
} else if (input$tabs == "QQplot") { |
1390 | ! |
card$append_plot(qq_r(), dim = pws2$dim()) |
1391 |
} |
|
1392 | ! |
card$append_text("Statistics table", "header3") |
1393 | ||
1394 | ! |
card$append_table(common_q()[["summary_table"]]) |
1395 | ! |
tests_error <- tryCatch(expr = tests_r(), error = function(e) "error") |
1396 | ! |
if (inherits(tests_error, "data.frame")) { |
1397 | ! |
card$append_text("Tests table", "header3") |
1398 | ! |
card$append_table(tests_r()) |
1399 |
} |
|
1400 | ||
1401 | ! |
if (!comment == "") { |
1402 | ! |
card$append_text("Comment", "header3") |
1403 | ! |
card$append_text(comment) |
1404 |
} |
|
1405 | ! |
card$append_src(teal.code::get_code(req(decorated_output_q()))) |
1406 | ! |
card |
1407 |
} |
|
1408 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
1409 |
} |
|
1410 |
### |
|
1411 |
}) |
|
1412 |
} |
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 |
#' @param decorators `r roxygen_decorators_param("tm_g_scatterplot")` |
|
31 |
#' |
|
32 |
#' @inherit shared_params return |
|
33 |
#' |
|
34 |
#' @section Decorating `tm_g_scatterplot`: |
|
35 |
#' |
|
36 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
37 |
#' - `plot` (`ggplot2`) |
|
38 |
#' |
|
39 |
#' For additional details and examples of decorators, refer to the vignette |
|
40 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
41 |
#' |
|
42 |
#' |
|
43 |
#' @examplesShinylive |
|
44 |
#' library(teal.modules.general) |
|
45 |
#' interactive <- function() TRUE |
|
46 |
#' {{ next_example }} |
|
47 |
# nolint start: line_length_linter. |
|
48 |
#' @examplesIf require("ggpmisc", quietly = TRUE) && require("ggExtra", quietly = TRUE) && require("colourpicker", quietly = TRUE) |
|
49 |
# nolint end: line_length_linter. |
|
50 |
#' # general data example |
|
51 |
#' data <- teal_data() |
|
52 |
#' data <- within(data, { |
|
53 |
#' require(nestcolor) |
|
54 |
#' CO2 <- CO2 |
|
55 |
#' }) |
|
56 |
#' |
|
57 |
#' app <- init( |
|
58 |
#' data = data, |
|
59 |
#' modules = modules( |
|
60 |
#' tm_g_scatterplot( |
|
61 |
#' label = "Scatterplot Choices", |
|
62 |
#' x = data_extract_spec( |
|
63 |
#' dataname = "CO2", |
|
64 |
#' select = select_spec( |
|
65 |
#' label = "Select variable:", |
|
66 |
#' choices = variable_choices(data[["CO2"]], c("conc", "uptake")), |
|
67 |
#' selected = "conc", |
|
68 |
#' multiple = FALSE, |
|
69 |
#' fixed = FALSE |
|
70 |
#' ) |
|
71 |
#' ), |
|
72 |
#' y = data_extract_spec( |
|
73 |
#' dataname = "CO2", |
|
74 |
#' select = select_spec( |
|
75 |
#' label = "Select variable:", |
|
76 |
#' choices = variable_choices(data[["CO2"]], c("conc", "uptake")), |
|
77 |
#' selected = "uptake", |
|
78 |
#' multiple = FALSE, |
|
79 |
#' fixed = FALSE |
|
80 |
#' ) |
|
81 |
#' ), |
|
82 |
#' color_by = data_extract_spec( |
|
83 |
#' dataname = "CO2", |
|
84 |
#' select = select_spec( |
|
85 |
#' label = "Select variable:", |
|
86 |
#' choices = variable_choices( |
|
87 |
#' data[["CO2"]], |
|
88 |
#' c("Plant", "Type", "Treatment", "conc", "uptake") |
|
89 |
#' ), |
|
90 |
#' selected = NULL, |
|
91 |
#' multiple = FALSE, |
|
92 |
#' fixed = FALSE |
|
93 |
#' ) |
|
94 |
#' ), |
|
95 |
#' size_by = data_extract_spec( |
|
96 |
#' dataname = "CO2", |
|
97 |
#' select = select_spec( |
|
98 |
#' label = "Select variable:", |
|
99 |
#' choices = variable_choices(data[["CO2"]], c("conc", "uptake")), |
|
100 |
#' selected = "uptake", |
|
101 |
#' multiple = FALSE, |
|
102 |
#' fixed = FALSE |
|
103 |
#' ) |
|
104 |
#' ), |
|
105 |
#' row_facet = data_extract_spec( |
|
106 |
#' dataname = "CO2", |
|
107 |
#' select = select_spec( |
|
108 |
#' label = "Select variable:", |
|
109 |
#' choices = variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment")), |
|
110 |
#' selected = NULL, |
|
111 |
#' multiple = FALSE, |
|
112 |
#' fixed = FALSE |
|
113 |
#' ) |
|
114 |
#' ), |
|
115 |
#' col_facet = data_extract_spec( |
|
116 |
#' dataname = "CO2", |
|
117 |
#' select = select_spec( |
|
118 |
#' label = "Select variable:", |
|
119 |
#' choices = variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment")), |
|
120 |
#' selected = NULL, |
|
121 |
#' multiple = FALSE, |
|
122 |
#' fixed = FALSE |
|
123 |
#' ) |
|
124 |
#' ) |
|
125 |
#' ) |
|
126 |
#' ) |
|
127 |
#' ) |
|
128 |
#' if (interactive()) { |
|
129 |
#' shinyApp(app$ui, app$server) |
|
130 |
#' } |
|
131 |
#' |
|
132 |
#' @examplesShinylive |
|
133 |
#' library(teal.modules.general) |
|
134 |
#' interactive <- function() TRUE |
|
135 |
#' {{ next_example }} |
|
136 |
# nolint start: line_length_linter. |
|
137 |
#' @examplesIf require("ggpmisc", quietly = TRUE) && require("ggExtra", quietly = TRUE) && require("colourpicker", quietly = TRUE) |
|
138 |
# nolint end: line_length_linter. |
|
139 |
#' # CDISC data example |
|
140 |
#' data <- teal_data() |
|
141 |
#' data <- within(data, { |
|
142 |
#' require(nestcolor) |
|
143 |
#' ADSL <- teal.data::rADSL |
|
144 |
#' }) |
|
145 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
146 |
#' |
|
147 |
#' app <- init( |
|
148 |
#' data = data, |
|
149 |
#' modules = modules( |
|
150 |
#' tm_g_scatterplot( |
|
151 |
#' label = "Scatterplot Choices", |
|
152 |
#' x = data_extract_spec( |
|
153 |
#' dataname = "ADSL", |
|
154 |
#' select = select_spec( |
|
155 |
#' label = "Select variable:", |
|
156 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1", "BMRKR2")), |
|
157 |
#' selected = "AGE", |
|
158 |
#' multiple = FALSE, |
|
159 |
#' fixed = FALSE |
|
160 |
#' ) |
|
161 |
#' ), |
|
162 |
#' y = data_extract_spec( |
|
163 |
#' dataname = "ADSL", |
|
164 |
#' select = select_spec( |
|
165 |
#' label = "Select variable:", |
|
166 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1", "BMRKR2")), |
|
167 |
#' selected = "BMRKR1", |
|
168 |
#' multiple = FALSE, |
|
169 |
#' fixed = FALSE |
|
170 |
#' ) |
|
171 |
#' ), |
|
172 |
#' color_by = data_extract_spec( |
|
173 |
#' dataname = "ADSL", |
|
174 |
#' select = select_spec( |
|
175 |
#' label = "Select variable:", |
|
176 |
#' choices = variable_choices( |
|
177 |
#' data[["ADSL"]], |
|
178 |
#' c("AGE", "BMRKR1", "BMRKR2", "RACE", "REGION1") |
|
179 |
#' ), |
|
180 |
#' selected = NULL, |
|
181 |
#' multiple = FALSE, |
|
182 |
#' fixed = FALSE |
|
183 |
#' ) |
|
184 |
#' ), |
|
185 |
#' size_by = data_extract_spec( |
|
186 |
#' dataname = "ADSL", |
|
187 |
#' select = select_spec( |
|
188 |
#' label = "Select variable:", |
|
189 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1")), |
|
190 |
#' selected = "AGE", |
|
191 |
#' multiple = FALSE, |
|
192 |
#' fixed = FALSE |
|
193 |
#' ) |
|
194 |
#' ), |
|
195 |
#' row_facet = data_extract_spec( |
|
196 |
#' dataname = "ADSL", |
|
197 |
#' select = select_spec( |
|
198 |
#' label = "Select variable:", |
|
199 |
#' choices = variable_choices(data[["ADSL"]], c("BMRKR2", "RACE", "REGION1")), |
|
200 |
#' selected = NULL, |
|
201 |
#' multiple = FALSE, |
|
202 |
#' fixed = FALSE |
|
203 |
#' ) |
|
204 |
#' ), |
|
205 |
#' col_facet = data_extract_spec( |
|
206 |
#' dataname = "ADSL", |
|
207 |
#' select = select_spec( |
|
208 |
#' label = "Select variable:", |
|
209 |
#' choices = variable_choices(data[["ADSL"]], c("BMRKR2", "RACE", "REGION1")), |
|
210 |
#' selected = NULL, |
|
211 |
#' multiple = FALSE, |
|
212 |
#' fixed = FALSE |
|
213 |
#' ) |
|
214 |
#' ) |
|
215 |
#' ) |
|
216 |
#' ) |
|
217 |
#' ) |
|
218 |
#' if (interactive()) { |
|
219 |
#' shinyApp(app$ui, app$server) |
|
220 |
#' } |
|
221 |
#' |
|
222 |
#' @export |
|
223 |
#' |
|
224 |
tm_g_scatterplot <- function(label = "Scatterplot", |
|
225 |
x, |
|
226 |
y, |
|
227 |
color_by = NULL, |
|
228 |
size_by = NULL, |
|
229 |
row_facet = NULL, |
|
230 |
col_facet = NULL, |
|
231 |
plot_height = c(600, 200, 2000), |
|
232 |
plot_width = NULL, |
|
233 |
alpha = c(1, 0, 1), |
|
234 |
shape = shape_names, |
|
235 |
size = c(5, 1, 15), |
|
236 |
max_deg = 5L, |
|
237 |
rotate_xaxis_labels = FALSE, |
|
238 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
239 |
pre_output = NULL, |
|
240 |
post_output = NULL, |
|
241 |
table_dec = 4, |
|
242 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
243 |
decorators = NULL) { |
|
244 | ! |
message("Initializing tm_g_scatterplot") |
245 | ||
246 |
# Requires Suggested packages |
|
247 | ! |
extra_packages <- c("ggpmisc", "ggExtra", "colourpicker") |
248 | ! |
missing_packages <- Filter(function(x) !requireNamespace(x, quietly = TRUE), extra_packages) |
249 | ! |
if (length(missing_packages) > 0L) { |
250 | ! |
stop(sprintf( |
251 | ! |
"Cannot load package(s): %s.\nInstall or restart your session.", |
252 | ! |
toString(missing_packages) |
253 |
)) |
|
254 |
} |
|
255 | ||
256 |
# Normalize the parameters |
|
257 | ! |
if (inherits(x, "data_extract_spec")) x <- list(x) |
258 | ! |
if (inherits(y, "data_extract_spec")) y <- list(y) |
259 | ! |
if (inherits(color_by, "data_extract_spec")) color_by <- list(color_by) |
260 | ! |
if (inherits(size_by, "data_extract_spec")) size_by <- list(size_by) |
261 | ! |
if (inherits(row_facet, "data_extract_spec")) row_facet <- list(row_facet) |
262 | ! |
if (inherits(col_facet, "data_extract_spec")) col_facet <- list(col_facet) |
263 | ! |
if (is.double(max_deg)) max_deg <- as.integer(max_deg) |
264 | ||
265 |
# Start of assertions |
|
266 | ! |
checkmate::assert_string(label) |
267 | ! |
checkmate::assert_list(x, types = "data_extract_spec") |
268 | ! |
checkmate::assert_list(y, types = "data_extract_spec") |
269 | ! |
checkmate::assert_list(color_by, types = "data_extract_spec", null.ok = TRUE) |
270 | ! |
checkmate::assert_list(size_by, types = "data_extract_spec", null.ok = TRUE) |
271 | ||
272 | ! |
checkmate::assert_list(row_facet, types = "data_extract_spec", null.ok = TRUE) |
273 | ! |
assert_single_selection(row_facet) |
274 | ||
275 | ! |
checkmate::assert_list(col_facet, types = "data_extract_spec", null.ok = TRUE) |
276 | ! |
assert_single_selection(col_facet) |
277 | ||
278 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
279 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
280 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
281 | ! |
checkmate::assert_numeric( |
282 | ! |
plot_width[1], |
283 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
284 |
) |
|
285 | ||
286 | ! |
if (length(alpha) == 1) { |
287 | ! |
checkmate::assert_numeric(alpha, any.missing = FALSE, finite = TRUE) |
288 |
} else { |
|
289 | ! |
checkmate::assert_numeric(alpha, len = 3, any.missing = FALSE, finite = TRUE) |
290 | ! |
checkmate::assert_numeric(alpha[1], lower = alpha[2], upper = alpha[3], .var.name = "alpha") |
291 |
} |
|
292 | ||
293 | ! |
checkmate::assert_character(shape) |
294 | ||
295 | ! |
if (length(size) == 1) { |
296 | ! |
checkmate::assert_numeric(size, any.missing = FALSE, finite = TRUE) |
297 |
} else { |
|
298 | ! |
checkmate::assert_numeric(size, len = 3, any.missing = FALSE, finite = TRUE) |
299 | ! |
checkmate::assert_numeric(size[1], lower = size[2], upper = size[3], .var.name = "size") |
300 |
} |
|
301 | ||
302 | ! |
checkmate::assert_int(max_deg, lower = 1L) |
303 | ! |
checkmate::assert_flag(rotate_xaxis_labels) |
304 | ! |
ggtheme <- match.arg(ggtheme) |
305 | ||
306 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
307 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
308 | ||
309 | ! |
checkmate::assert_scalar(table_dec) |
310 | ! |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
311 | ||
312 | ! |
decorators <- normalize_decorators(decorators) |
313 | ! |
assert_decorators(decorators, null.ok = TRUE, "plot") |
314 | ||
315 |
# End of assertions |
|
316 | ||
317 |
# Make UI args |
|
318 | ! |
args <- as.list(environment()) |
319 | ||
320 | ! |
data_extract_list <- list( |
321 | ! |
x = x, |
322 | ! |
y = y, |
323 | ! |
color_by = color_by, |
324 | ! |
size_by = size_by, |
325 | ! |
row_facet = row_facet, |
326 | ! |
col_facet = col_facet |
327 |
) |
|
328 | ||
329 | ! |
ans <- module( |
330 | ! |
label = label, |
331 | ! |
server = srv_g_scatterplot, |
332 | ! |
ui = ui_g_scatterplot, |
333 | ! |
ui_args = args, |
334 | ! |
server_args = c( |
335 | ! |
data_extract_list, |
336 | ! |
list( |
337 | ! |
plot_height = plot_height, |
338 | ! |
plot_width = plot_width, |
339 | ! |
table_dec = table_dec, |
340 | ! |
ggplot2_args = ggplot2_args, |
341 | ! |
decorators = decorators |
342 |
) |
|
343 |
), |
|
344 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
345 |
) |
|
346 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
347 | ! |
ans |
348 |
} |
|
349 | ||
350 |
# UI function for the scatterplot module |
|
351 |
ui_g_scatterplot <- function(id, ...) { |
|
352 | ! |
args <- list(...) |
353 | ! |
ns <- NS(id) |
354 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset( |
355 | ! |
args$x, args$y, args$color_by, args$size_by, args$row_facet, args$col_facet |
356 |
) |
|
357 | ||
358 | ! |
tagList( |
359 | ! |
include_css_files("custom"), |
360 | ! |
teal.widgets::standard_layout( |
361 | ! |
output = teal.widgets::white_small_well( |
362 | ! |
teal.widgets::plot_with_settings_ui(id = ns("scatter_plot")), |
363 | ! |
tags$h1(tags$strong("Selected points:"), class = "text-center font-150p"), |
364 | ! |
teal.widgets::get_dt_rows(ns("data_table"), ns("data_table_rows")), |
365 | ! |
DT::dataTableOutput(ns("data_table"), width = "100%") |
366 |
), |
|
367 | ! |
encoding = tags$div( |
368 |
### Reporter |
|
369 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
370 |
### |
|
371 | ! |
tags$label("Encodings", class = "text-primary"), |
372 | ! |
teal.transform::datanames_input(args[c("x", "y", "color_by", "size_by", "row_facet", "col_facet")]), |
373 | ! |
teal.transform::data_extract_ui( |
374 | ! |
id = ns("x"), |
375 | ! |
label = "X variable", |
376 | ! |
data_extract_spec = args$x, |
377 | ! |
is_single_dataset = is_single_dataset_value |
378 |
), |
|
379 | ! |
checkboxInput(ns("log_x"), "Use log transformation", value = FALSE), |
380 | ! |
conditionalPanel( |
381 | ! |
condition = paste0("input['", ns("log_x"), "'] == true"), |
382 | ! |
radioButtons( |
383 | ! |
ns("log_x_base"), |
384 | ! |
label = NULL, |
385 | ! |
inline = TRUE, |
386 | ! |
choices = c("Natural" = "log", "Base 10" = "log10", "Base 2" = "log2") |
387 |
) |
|
388 |
), |
|
389 | ! |
teal.transform::data_extract_ui( |
390 | ! |
id = ns("y"), |
391 | ! |
label = "Y variable", |
392 | ! |
data_extract_spec = args$y, |
393 | ! |
is_single_dataset = is_single_dataset_value |
394 |
), |
|
395 | ! |
checkboxInput(ns("log_y"), "Use log transformation", value = FALSE), |
396 | ! |
conditionalPanel( |
397 | ! |
condition = paste0("input['", ns("log_y"), "'] == true"), |
398 | ! |
radioButtons( |
399 | ! |
ns("log_y_base"), |
400 | ! |
label = NULL, |
401 | ! |
inline = TRUE, |
402 | ! |
choices = c("Natural" = "log", "Base 10" = "log10", "Base 2" = "log2") |
403 |
) |
|
404 |
), |
|
405 | ! |
if (!is.null(args$color_by)) { |
406 | ! |
teal.transform::data_extract_ui( |
407 | ! |
id = ns("color_by"), |
408 | ! |
label = "Color by variable", |
409 | ! |
data_extract_spec = args$color_by, |
410 | ! |
is_single_dataset = is_single_dataset_value |
411 |
) |
|
412 |
}, |
|
413 | ! |
if (!is.null(args$size_by)) { |
414 | ! |
teal.transform::data_extract_ui( |
415 | ! |
id = ns("size_by"), |
416 | ! |
label = "Size by variable", |
417 | ! |
data_extract_spec = args$size_by, |
418 | ! |
is_single_dataset = is_single_dataset_value |
419 |
) |
|
420 |
}, |
|
421 | ! |
if (!is.null(args$row_facet)) { |
422 | ! |
teal.transform::data_extract_ui( |
423 | ! |
id = ns("row_facet"), |
424 | ! |
label = "Row facetting", |
425 | ! |
data_extract_spec = args$row_facet, |
426 | ! |
is_single_dataset = is_single_dataset_value |
427 |
) |
|
428 |
}, |
|
429 | ! |
if (!is.null(args$col_facet)) { |
430 | ! |
teal.transform::data_extract_ui( |
431 | ! |
id = ns("col_facet"), |
432 | ! |
label = "Column facetting", |
433 | ! |
data_extract_spec = args$col_facet, |
434 | ! |
is_single_dataset = is_single_dataset_value |
435 |
) |
|
436 |
}, |
|
437 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")), |
438 | ! |
teal.widgets::panel_group( |
439 | ! |
teal.widgets::panel_item( |
440 | ! |
title = "Plot settings", |
441 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("alpha"), "Opacity:", args$alpha, ticks = FALSE), |
442 | ! |
teal.widgets::optionalSelectInput( |
443 | ! |
inputId = ns("shape"), |
444 | ! |
label = "Points shape:", |
445 | ! |
choices = args$shape, |
446 | ! |
selected = args$shape[1], |
447 | ! |
multiple = FALSE |
448 |
), |
|
449 | ! |
colourpicker::colourInput(ns("color"), "Points color:", "black"), |
450 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("size"), "Points size:", args$size, ticks = FALSE, step = .1), |
451 | ! |
checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = args$rotate_xaxis_labels), |
452 | ! |
checkboxInput(ns("add_density"), "Add marginal density", value = FALSE), |
453 | ! |
checkboxInput(ns("rug_plot"), "Include rug plot", value = FALSE), |
454 | ! |
checkboxInput(ns("show_count"), "Show N (number of observations)", value = FALSE), |
455 | ! |
shinyjs::hidden(helpText(id = ns("line_msg"), "Trendline needs numeric X and Y variables")), |
456 | ! |
teal.widgets::optionalSelectInput(ns("smoothing_degree"), "Smoothing degree", seq_len(args$max_deg)), |
457 | ! |
shinyjs::hidden(teal.widgets::optionalSelectInput(ns("color_sub"), label = "", multiple = TRUE)), |
458 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("ci"), "Confidence", c(.95, .8, .99), ticks = FALSE), |
459 | ! |
shinyjs::hidden(checkboxInput(ns("show_form"), "Show formula", value = TRUE)), |
460 | ! |
shinyjs::hidden(checkboxInput(ns("show_r2"), "Show adj-R Squared", value = TRUE)), |
461 | ! |
uiOutput(ns("num_na_removed")), |
462 | ! |
tags$div( |
463 | ! |
id = ns("label_pos"), |
464 | ! |
tags$div(tags$strong("Stats position")), |
465 | ! |
tags$div(class = "inline-block w-10", helpText("Left")), |
466 | ! |
tags$div( |
467 | ! |
class = "inline-block w-70", |
468 | ! |
teal.widgets::optionalSliderInput( |
469 | ! |
ns("pos"), |
470 | ! |
label = NULL, |
471 | ! |
min = 0, max = 1, value = .99, ticks = FALSE, step = .01 |
472 |
) |
|
473 |
), |
|
474 | ! |
tags$div(class = "inline-block w-10", helpText("Right")) |
475 |
), |
|
476 | ! |
teal.widgets::optionalSliderInput( |
477 | ! |
ns("label_size"), "Stats font size", |
478 | ! |
min = 3, max = 10, value = 5, ticks = FALSE, step = .1 |
479 |
), |
|
480 | ! |
if (!is.null(args$row_facet) || !is.null(args$col_facet)) { |
481 | ! |
checkboxInput(ns("free_scales"), "Free scales", value = FALSE) |
482 |
}, |
|
483 | ! |
selectInput( |
484 | ! |
inputId = ns("ggtheme"), |
485 | ! |
label = "Theme (by ggplot):", |
486 | ! |
choices = ggplot_themes, |
487 | ! |
selected = args$ggtheme, |
488 | ! |
multiple = FALSE |
489 |
) |
|
490 |
) |
|
491 |
) |
|
492 |
), |
|
493 | ! |
forms = tagList( |
494 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
495 |
), |
|
496 | ! |
pre_output = args$pre_output, |
497 | ! |
post_output = args$post_output |
498 |
) |
|
499 |
) |
|
500 |
} |
|
501 | ||
502 |
# Server function for the scatterplot module |
|
503 |
srv_g_scatterplot <- function(id, |
|
504 |
data, |
|
505 |
reporter, |
|
506 |
filter_panel_api, |
|
507 |
x, |
|
508 |
y, |
|
509 |
color_by, |
|
510 |
size_by, |
|
511 |
row_facet, |
|
512 |
col_facet, |
|
513 |
plot_height, |
|
514 |
plot_width, |
|
515 |
table_dec, |
|
516 |
ggplot2_args, |
|
517 |
decorators) { |
|
518 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
519 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
520 | ! |
checkmate::assert_class(data, "reactive") |
521 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
522 | ! |
moduleServer(id, function(input, output, session) { |
523 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
524 | ||
525 | ! |
data_extract <- list( |
526 | ! |
x = x, |
527 | ! |
y = y, |
528 | ! |
color_by = color_by, |
529 | ! |
size_by = size_by, |
530 | ! |
row_facet = row_facet, |
531 | ! |
col_facet = col_facet |
532 |
) |
|
533 | ||
534 | ! |
rule_diff <- function(other) { |
535 | ! |
function(value) { |
536 | ! |
othervalue <- selector_list()[[other]]()[["select"]] |
537 | ! |
if (!is.null(othervalue)) { |
538 | ! |
if (identical(value, othervalue)) { |
539 | ! |
"Row and column facetting variables must be different." |
540 |
} |
|
541 |
} |
|
542 |
} |
|
543 |
} |
|
544 | ||
545 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
546 | ! |
data_extract = data_extract, |
547 | ! |
datasets = data, |
548 | ! |
select_validation_rule = list( |
549 | ! |
x = ~ if (length(.) != 1) "Please select exactly one x var.", |
550 | ! |
y = ~ if (length(.) != 1) "Please select exactly one y var.", |
551 | ! |
color_by = ~ if (length(.) > 1) "There cannot be more than 1 color variable.", |
552 | ! |
size_by = ~ if (length(.) > 1) "There cannot be more than 1 size variable.", |
553 | ! |
row_facet = shinyvalidate::compose_rules( |
554 | ! |
shinyvalidate::sv_optional(), |
555 | ! |
rule_diff("col_facet") |
556 |
), |
|
557 | ! |
col_facet = shinyvalidate::compose_rules( |
558 | ! |
shinyvalidate::sv_optional(), |
559 | ! |
rule_diff("row_facet") |
560 |
) |
|
561 |
) |
|
562 |
) |
|
563 | ||
564 | ! |
iv_r <- reactive({ |
565 | ! |
iv_facet <- shinyvalidate::InputValidator$new() |
566 | ! |
iv <- shinyvalidate::InputValidator$new() |
567 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
568 |
}) |
|
569 | ! |
iv_facet <- shinyvalidate::InputValidator$new() |
570 | ! |
iv_facet$add_rule("add_density", ~ if ( |
571 | ! |
isTRUE(.) && |
572 |
( |
|
573 | ! |
length(selector_list()$row_facet()$select) > 0L || |
574 | ! |
length(selector_list()$col_facet()$select) > 0L |
575 |
) |
|
576 |
) { |
|
577 | ! |
"Cannot add marginal density when Row or Column facetting has been selected" |
578 |
}) |
|
579 | ! |
iv_facet$enable() |
580 | ||
581 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
582 | ! |
selector_list = selector_list, |
583 | ! |
datasets = data, |
584 | ! |
merge_function = "dplyr::inner_join" |
585 |
) |
|
586 | ||
587 | ! |
anl_merged_q <- reactive({ |
588 | ! |
req(anl_merged_input()) |
589 | ! |
data() %>% |
590 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) %>% |
591 | ! |
teal.code::eval_code(quote(ANL)) # used to display table when running show-r-code code |
592 |
}) |
|
593 | ||
594 | ! |
merged <- list( |
595 | ! |
anl_input_r = anl_merged_input, |
596 | ! |
anl_q_r = anl_merged_q |
597 |
) |
|
598 | ||
599 | ! |
trend_line_is_applicable <- reactive({ |
600 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
601 | ! |
x_var <- as.vector(merged$anl_input_r()$columns_source$x) |
602 | ! |
y_var <- as.vector(merged$anl_input_r()$columns_source$y) |
603 | ! |
length(x_var) > 0 && length(y_var) > 0 && is.numeric(ANL[[x_var]]) && is.numeric(ANL[[y_var]]) |
604 |
}) |
|
605 | ||
606 | ! |
add_trend_line <- reactive({ |
607 | ! |
smoothing_degree <- as.integer(input$smoothing_degree) |
608 | ! |
trend_line_is_applicable() && length(smoothing_degree) > 0 |
609 |
}) |
|
610 | ||
611 | ! |
if (!is.null(color_by)) { |
612 | ! |
observeEvent( |
613 | ! |
eventExpr = merged$anl_input_r()$columns_source$color_by, |
614 | ! |
handlerExpr = { |
615 | ! |
color_by_var <- as.vector(merged$anl_input_r()$columns_source$color_by) |
616 | ! |
if (length(color_by_var) > 0) { |
617 | ! |
shinyjs::hide("color") |
618 |
} else { |
|
619 | ! |
shinyjs::show("color") |
620 |
} |
|
621 |
} |
|
622 |
) |
|
623 |
} |
|
624 | ||
625 | ! |
output$num_na_removed <- renderUI({ |
626 | ! |
if (add_trend_line()) { |
627 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
628 | ! |
x_var <- as.vector(merged$anl_input_r()$columns_source$x) |
629 | ! |
y_var <- as.vector(merged$anl_input_r()$columns_source$y) |
630 | ! |
if ((num_total_na <- nrow(ANL) - nrow(stats::na.omit(ANL[, c(x_var, y_var)]))) > 0) { |
631 | ! |
tags$div(paste(num_total_na, "row(s) with missing values were removed"), tags$hr()) |
632 |
} |
|
633 |
} |
|
634 |
}) |
|
635 | ||
636 | ! |
observeEvent( |
637 | ! |
eventExpr = merged$anl_input_r()$columns_source[c("col_facet", "row_facet")], |
638 | ! |
handlerExpr = { |
639 | ! |
if ( |
640 | ! |
length(merged$anl_input_r()$columns_source$col_facet) == 0 && |
641 | ! |
length(merged$anl_input_r()$columns_source$row_facet) == 0 |
642 |
) { |
|
643 | ! |
shinyjs::hide("free_scales") |
644 |
} else { |
|
645 | ! |
shinyjs::show("free_scales") |
646 |
} |
|
647 |
} |
|
648 |
) |
|
649 | ||
650 | ! |
output_q <- reactive({ |
651 | ! |
teal::validate_inputs(iv_r(), iv_facet) |
652 | ||
653 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
654 | ||
655 | ! |
x_var <- as.vector(merged$anl_input_r()$columns_source$x) |
656 | ! |
y_var <- as.vector(merged$anl_input_r()$columns_source$y) |
657 | ! |
color_by_var <- as.vector(merged$anl_input_r()$columns_source$color_by) |
658 | ! |
size_by_var <- as.vector(merged$anl_input_r()$columns_source$size_by) |
659 | ! |
row_facet_name <- if (length(merged$anl_input_r()$columns_source$row_facet) == 0) { |
660 | ! |
character(0) |
661 |
} else { |
|
662 | ! |
as.vector(merged$anl_input_r()$columns_source$row_facet) |
663 |
} |
|
664 | ! |
col_facet_name <- if (length(merged$anl_input_r()$columns_source$col_facet) == 0) { |
665 | ! |
character(0) |
666 |
} else { |
|
667 | ! |
as.vector(merged$anl_input_r()$columns_source$col_facet) |
668 |
} |
|
669 | ! |
alpha <- input$alpha |
670 | ! |
size <- input$size |
671 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
672 | ! |
add_density <- input$add_density |
673 | ! |
ggtheme <- input$ggtheme |
674 | ! |
rug_plot <- input$rug_plot |
675 | ! |
color <- input$color |
676 | ! |
shape <- `if`(is.null(input$shape) || identical(input$shape, ""), "circle", input$shape) |
677 | ! |
smoothing_degree <- as.integer(input$smoothing_degree) |
678 | ! |
ci <- input$ci |
679 | ||
680 | ! |
log_x <- input$log_x |
681 | ! |
log_y <- input$log_y |
682 | ||
683 | ! |
validate(need( |
684 | ! |
length(row_facet_name) == 0 || inherits(ANL[[row_facet_name]], c("character", "factor", "Date", "integer")), |
685 | ! |
"`Row facetting` variable must be of class `character`, `factor`, `Date`, or `integer`" |
686 |
)) |
|
687 | ! |
validate(need( |
688 | ! |
length(col_facet_name) == 0 || inherits(ANL[[col_facet_name]], c("character", "factor", "Date", "integer")), |
689 | ! |
"`Column facetting` variable must be of class `character`, `factor`, `Date`, or `integer`" |
690 |
)) |
|
691 | ||
692 | ! |
if (add_density && length(color_by_var) > 0) { |
693 | ! |
validate(need( |
694 | ! |
!is.numeric(ANL[[color_by_var]]), |
695 | ! |
"Marginal plots cannot be produced when the points are colored by numeric variables. |
696 | ! |
\n Uncheck the 'Add marginal density' checkbox to display the plot." |
697 |
)) |
|
698 | ! |
validate(need( |
699 |
!( |
|
700 | ! |
inherits(ANL[[color_by_var]], "Date") || |
701 | ! |
inherits(ANL[[color_by_var]], "POSIXct") || |
702 | ! |
inherits(ANL[[color_by_var]], "POSIXlt") |
703 |
), |
|
704 | ! |
"Marginal plots cannot be produced when the points are colored by Date or POSIX variables. |
705 | ! |
\n Uncheck the 'Add marginal density' checkbox to display the plot." |
706 |
)) |
|
707 |
} |
|
708 | ||
709 | ! |
teal::validate_has_data(ANL[, c(x_var, y_var)], 10, complete = TRUE, allow_inf = FALSE) |
710 | ||
711 | ! |
if (log_x) { |
712 | ! |
validate( |
713 | ! |
need( |
714 | ! |
is.numeric(ANL[[x_var]]) && all( |
715 | ! |
ANL[[x_var]] > 0 | is.na(ANL[[x_var]]) |
716 |
), |
|
717 | ! |
"X variable can only be log transformed if variable is numeric and all values are positive." |
718 |
) |
|
719 |
) |
|
720 |
} |
|
721 | ! |
if (log_y) { |
722 | ! |
validate( |
723 | ! |
need( |
724 | ! |
is.numeric(ANL[[y_var]]) && all( |
725 | ! |
ANL[[y_var]] > 0 | is.na(ANL[[y_var]]) |
726 |
), |
|
727 | ! |
"Y variable can only be log transformed if variable is numeric and all values are positive." |
728 |
) |
|
729 |
) |
|
730 |
} |
|
731 | ||
732 | ! |
facet_cl <- facet_ggplot_call( |
733 | ! |
row_facet_name, |
734 | ! |
col_facet_name, |
735 | ! |
free_x_scales = isTRUE(input$free_scales), |
736 | ! |
free_y_scales = isTRUE(input$free_scales) |
737 |
) |
|
738 | ||
739 | ! |
point_sizes <- if (length(size_by_var) > 0) { |
740 | ! |
validate(need(is.numeric(ANL[[size_by_var]]), "Variable to size by must be numeric")) |
741 | ! |
substitute( |
742 | ! |
expr = size * ANL[[size_by_var]] / max(ANL[[size_by_var]], na.rm = TRUE), |
743 | ! |
env = list(size = size, size_by_var = size_by_var) |
744 |
) |
|
745 |
} else { |
|
746 | ! |
size |
747 |
} |
|
748 | ||
749 | ! |
plot_q <- merged$anl_q_r() |
750 | ||
751 | ! |
if (log_x) { |
752 | ! |
log_x_fn <- input$log_x_base |
753 | ! |
plot_q <- teal.code::eval_code( |
754 | ! |
object = plot_q, |
755 | ! |
code = substitute( |
756 | ! |
expr = ANL[, log_x_var] <- log_x_fn(ANL[, x_var]), |
757 | ! |
env = list( |
758 | ! |
x_var = x_var, |
759 | ! |
log_x_fn = as.name(log_x_fn), |
760 | ! |
log_x_var = paste0(log_x_fn, "_", x_var) |
761 |
) |
|
762 |
) |
|
763 |
) |
|
764 |
} |
|
765 | ||
766 | ! |
if (log_y) { |
767 | ! |
log_y_fn <- input$log_y_base |
768 | ! |
plot_q <- teal.code::eval_code( |
769 | ! |
object = plot_q, |
770 | ! |
code = substitute( |
771 | ! |
expr = ANL[, log_y_var] <- log_y_fn(ANL[, y_var]), |
772 | ! |
env = list( |
773 | ! |
y_var = y_var, |
774 | ! |
log_y_fn = as.name(log_y_fn), |
775 | ! |
log_y_var = paste0(log_y_fn, "_", y_var) |
776 |
) |
|
777 |
) |
|
778 |
) |
|
779 |
} |
|
780 | ||
781 | ! |
pre_pro_anl <- if (input$show_count) { |
782 | ! |
paste0( |
783 | ! |
"ANL %>% dplyr::group_by(", |
784 | ! |
paste( |
785 | ! |
c( |
786 | ! |
if (length(color_by_var) > 0 && inherits(ANL[[color_by_var]], c("factor", "character"))) color_by_var, |
787 | ! |
row_facet_name, |
788 | ! |
col_facet_name |
789 |
), |
|
790 | ! |
collapse = ", " |
791 |
), |
|
792 | ! |
") %>% dplyr::mutate(n = dplyr::n()) %>% dplyr::ungroup()" |
793 |
) |
|
794 |
} else { |
|
795 | ! |
"ANL" |
796 |
} |
|
797 | ||
798 | ! |
plot_call <- substitute(expr = pre_pro_anl %>% ggplot(), env = list(pre_pro_anl = str2lang(pre_pro_anl))) |
799 | ||
800 | ! |
plot_call <- if (length(color_by_var) == 0) { |
801 | ! |
substitute( |
802 | ! |
expr = plot_call + |
803 | ! |
ggplot2::aes(x = x_name, y = y_name) + |
804 | ! |
ggplot2::geom_point(alpha = alpha_value, size = point_sizes, shape = shape_value, color = color_value), |
805 | ! |
env = list( |
806 | ! |
plot_call = plot_call, |
807 | ! |
x_name = if (log_x) as.name(paste0(log_x_fn, "_", x_var)) else as.name(x_var), |
808 | ! |
y_name = if (log_y) as.name(paste0(log_y_fn, "_", y_var)) else as.name(y_var), |
809 | ! |
alpha_value = alpha, |
810 | ! |
point_sizes = point_sizes, |
811 | ! |
shape_value = shape, |
812 | ! |
color_value = color |
813 |
) |
|
814 |
) |
|
815 |
} else { |
|
816 | ! |
substitute( |
817 | ! |
expr = plot_call + |
818 | ! |
ggplot2::aes(x = x_name, y = y_name, color = color_by_var_name) + |
819 | ! |
ggplot2::geom_point(alpha = alpha_value, size = point_sizes, shape = shape_value), |
820 | ! |
env = list( |
821 | ! |
plot_call = plot_call, |
822 | ! |
x_name = if (log_x) as.name(paste0(log_x_fn, "_", x_var)) else as.name(x_var), |
823 | ! |
y_name = if (log_y) as.name(paste0(log_y_fn, "_", y_var)) else as.name(y_var), |
824 | ! |
color_by_var_name = as.name(color_by_var), |
825 | ! |
alpha_value = alpha, |
826 | ! |
point_sizes = point_sizes, |
827 | ! |
shape_value = shape |
828 |
) |
|
829 |
) |
|
830 |
} |
|
831 | ||
832 | ! |
if (rug_plot) plot_call <- substitute(expr = plot_call + geom_rug(), env = list(plot_call = plot_call)) |
833 | ||
834 | ! |
plot_label_generator <- function(rhs_formula = quote(y ~ 1), |
835 | ! |
show_form = input$show_form, |
836 | ! |
show_r2 = input$show_r2, |
837 | ! |
show_count = input$show_count, |
838 | ! |
pos = input$pos, |
839 | ! |
label_size = input$label_size) { |
840 | ! |
stopifnot(sum(show_form, show_r2, show_count) >= 1) |
841 | ! |
aes_label <- paste0( |
842 | ! |
"aes(", |
843 | ! |
if (show_count) "n = n, ", |
844 | ! |
"label = ", |
845 | ! |
if (sum(show_form, show_r2, show_count) > 1) "paste(", |
846 | ! |
paste( |
847 | ! |
c( |
848 | ! |
if (show_form) "stat(eq.label)", |
849 | ! |
if (show_r2) "stat(adj.rr.label)", |
850 | ! |
if (show_count) "paste('N ~`=`~', n)" |
851 |
), |
|
852 | ! |
collapse = ", " |
853 |
), |
|
854 | ! |
if (sum(show_form, show_r2, show_count) > 1) ", sep = '*\", \"*'))" else ")" |
855 |
) |
|
856 | ! |
label_geom <- substitute( |
857 | ! |
expr = ggpmisc::stat_poly_eq( |
858 | ! |
mapping = aes_label, |
859 | ! |
formula = rhs_formula, |
860 | ! |
parse = TRUE, |
861 | ! |
label.x = pos, |
862 | ! |
size = label_size |
863 |
), |
|
864 | ! |
env = list( |
865 | ! |
rhs_formula = rhs_formula, |
866 | ! |
pos = pos, |
867 | ! |
aes_label = str2lang(aes_label), |
868 | ! |
label_size = label_size |
869 |
) |
|
870 |
) |
|
871 | ! |
substitute( |
872 | ! |
expr = plot_call + label_geom, |
873 | ! |
env = list( |
874 | ! |
plot_call = plot_call, |
875 | ! |
label_geom = label_geom |
876 |
) |
|
877 |
) |
|
878 |
} |
|
879 | ||
880 | ! |
if (trend_line_is_applicable()) { |
881 | ! |
shinyjs::hide("line_msg") |
882 | ! |
shinyjs::show("smoothing_degree") |
883 | ! |
if (!add_trend_line()) { |
884 | ! |
shinyjs::hide("ci") |
885 | ! |
shinyjs::hide("color_sub") |
886 | ! |
shinyjs::hide("show_form") |
887 | ! |
shinyjs::hide("show_r2") |
888 | ! |
if (input$show_count) { |
889 | ! |
plot_call <- plot_label_generator(show_form = FALSE, show_r2 = FALSE) |
890 | ! |
shinyjs::show("label_pos") |
891 | ! |
shinyjs::show("label_size") |
892 |
} else { |
|
893 | ! |
shinyjs::hide("label_pos") |
894 | ! |
shinyjs::hide("label_size") |
895 |
} |
|
896 |
} else { |
|
897 | ! |
shinyjs::show("ci") |
898 | ! |
shinyjs::show("show_form") |
899 | ! |
shinyjs::show("show_r2") |
900 | ! |
if (nrow(ANL) - nrow(stats::na.omit(ANL[, c(x_var, y_var)])) > 0) { |
901 | ! |
plot_q <- teal.code::eval_code( |
902 | ! |
plot_q, |
903 | ! |
substitute( |
904 | ! |
expr = ANL <- dplyr::filter(ANL, !is.na(x_var) & !is.na(y_var)), |
905 | ! |
env = list(x_var = as.name(x_var), y_var = as.name(y_var)) |
906 |
) |
|
907 |
) |
|
908 |
} |
|
909 | ! |
rhs_formula <- substitute( |
910 | ! |
expr = y ~ poly(x, smoothing_degree, raw = TRUE), |
911 | ! |
env = list(smoothing_degree = smoothing_degree) |
912 |
) |
|
913 | ! |
if (input$show_form || input$show_r2 || input$show_count) { |
914 | ! |
plot_call <- plot_label_generator(rhs_formula = rhs_formula) |
915 | ! |
shinyjs::show("label_pos") |
916 | ! |
shinyjs::show("label_size") |
917 |
} else { |
|
918 | ! |
shinyjs::hide("label_pos") |
919 | ! |
shinyjs::hide("label_size") |
920 |
} |
|
921 | ! |
plot_call <- substitute( |
922 | ! |
expr = plot_call + ggplot2::geom_smooth(formula = rhs_formula, se = TRUE, level = ci, method = "lm"), |
923 | ! |
env = list(plot_call = plot_call, rhs_formula = rhs_formula, ci = ci) |
924 |
) |
|
925 |
} |
|
926 |
} else { |
|
927 | ! |
shinyjs::hide("smoothing_degree") |
928 | ! |
shinyjs::hide("ci") |
929 | ! |
shinyjs::hide("color_sub") |
930 | ! |
shinyjs::hide("show_form") |
931 | ! |
shinyjs::hide("show_r2") |
932 | ! |
if (input$show_count) { |
933 | ! |
plot_call <- plot_label_generator(show_form = FALSE, show_r2 = FALSE) |
934 | ! |
shinyjs::show("label_pos") |
935 | ! |
shinyjs::show("label_size") |
936 |
} else { |
|
937 | ! |
shinyjs::hide("label_pos") |
938 | ! |
shinyjs::hide("label_size") |
939 |
} |
|
940 | ! |
shinyjs::show("line_msg") |
941 |
} |
|
942 | ||
943 | ! |
if (!is.null(facet_cl)) { |
944 | ! |
plot_call <- substitute(expr = plot_call + facet_cl, env = list(plot_call = plot_call, facet_cl = facet_cl)) |
945 |
} |
|
946 | ||
947 | ! |
y_label <- varname_w_label( |
948 | ! |
y_var, |
949 | ! |
ANL, |
950 | ! |
prefix = if (log_y) paste(log_y_fn, "(") else NULL, |
951 | ! |
suffix = if (log_y) ")" else NULL |
952 |
) |
|
953 | ! |
x_label <- varname_w_label( |
954 | ! |
x_var, |
955 | ! |
ANL, |
956 | ! |
prefix = if (log_x) paste(log_x_fn, "(") else NULL, |
957 | ! |
suffix = if (log_x) ")" else NULL |
958 |
) |
|
959 | ||
960 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
961 | ! |
labs = list(y = y_label, x = x_label), |
962 | ! |
theme = list(legend.position = "bottom") |
963 |
) |
|
964 | ||
965 | ! |
if (rotate_xaxis_labels) { |
966 | ! |
dev_ggplot2_args$theme[["axis.text.x"]] <- quote(element_text(angle = 45, hjust = 1)) |
967 |
} |
|
968 | ||
969 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
970 | ! |
user_plot = ggplot2_args, |
971 | ! |
module_plot = dev_ggplot2_args |
972 |
) |
|
973 | ||
974 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args(all_ggplot2_args, ggtheme = ggtheme) |
975 | ||
976 | ||
977 | ! |
if (add_density) { |
978 | ! |
plot_call <- substitute( |
979 | ! |
expr = ggExtra::ggMarginal( |
980 | ! |
plot_call + labs + ggthemes + themes, |
981 | ! |
type = "density", |
982 | ! |
groupColour = group_colour |
983 |
), |
|
984 | ! |
env = list( |
985 | ! |
plot_call = plot_call, |
986 | ! |
group_colour = if (length(color_by_var) > 0) TRUE else FALSE, |
987 | ! |
labs = parsed_ggplot2_args$labs, |
988 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
989 | ! |
themes = parsed_ggplot2_args$theme |
990 |
) |
|
991 |
) |
|
992 |
} else { |
|
993 | ! |
plot_call <- substitute( |
994 | ! |
expr = plot_call + |
995 | ! |
labs + |
996 | ! |
ggthemes + |
997 | ! |
themes, |
998 | ! |
env = list( |
999 | ! |
plot_call = plot_call, |
1000 | ! |
labs = parsed_ggplot2_args$labs, |
1001 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
1002 | ! |
themes = parsed_ggplot2_args$theme |
1003 |
) |
|
1004 |
) |
|
1005 |
} |
|
1006 | ||
1007 | ! |
plot_call <- substitute(expr = plot <- plot_call, env = list(plot_call = plot_call)) |
1008 | ||
1009 | ! |
teal.code::eval_code(plot_q, plot_call) |
1010 |
}) |
|
1011 | ||
1012 | ! |
decorated_output_plot_q <- srv_decorate_teal_data( |
1013 | ! |
id = "decorator", |
1014 | ! |
data = output_q, |
1015 | ! |
decorators = select_decorators(decorators, "plot"), |
1016 | ! |
expr = print(plot) |
1017 |
) |
|
1018 | ||
1019 | ! |
plot_r <- reactive(req(decorated_output_plot_q())[["plot"]]) |
1020 | ||
1021 |
# Insert the plot into a plot_with_settings module from teal.widgets |
|
1022 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
1023 | ! |
id = "scatter_plot", |
1024 | ! |
plot_r = plot_r, |
1025 | ! |
height = plot_height, |
1026 | ! |
width = plot_width, |
1027 | ! |
brushing = TRUE |
1028 |
) |
|
1029 | ||
1030 | ! |
output$data_table <- DT::renderDataTable({ |
1031 | ! |
plot_brush <- pws$brush() |
1032 | ||
1033 | ! |
if (!is.null(plot_brush)) { |
1034 | ! |
validate(need(!input$add_density, "Brushing feature is currently not supported when plot has marginal density")) |
1035 |
} |
|
1036 | ||
1037 | ! |
merged_data <- isolate(teal.code::dev_suppress(output_q()[["ANL"]])) |
1038 | ||
1039 | ! |
brushed_df <- teal.widgets::clean_brushedPoints(merged_data, plot_brush) |
1040 | ! |
numeric_cols <- names(brushed_df)[ |
1041 | ! |
vapply(brushed_df, function(x) is.numeric(x) && !is.integer(x), FUN.VALUE = logical(1)) |
1042 |
] |
|
1043 | ||
1044 | ! |
if (length(numeric_cols) > 0) { |
1045 | ! |
DT::formatRound( |
1046 | ! |
DT::datatable(brushed_df, |
1047 | ! |
rownames = FALSE, |
1048 | ! |
options = list(scrollX = TRUE, pageLength = input$data_table_rows) |
1049 |
), |
|
1050 | ! |
numeric_cols, |
1051 | ! |
table_dec |
1052 |
) |
|
1053 |
} else { |
|
1054 | ! |
DT::datatable(brushed_df, rownames = FALSE, options = list(scrollX = TRUE, pageLength = input$data_table_rows)) |
1055 |
} |
|
1056 |
}) |
|
1057 | ||
1058 | ! |
teal.widgets::verbatim_popup_srv( |
1059 | ! |
id = "rcode", |
1060 | ! |
verbatim_content = reactive(teal.code::get_code(req(decorated_output_plot_q()))), |
1061 | ! |
title = "R Code for scatterplot" |
1062 |
) |
|
1063 | ||
1064 |
### REPORTER |
|
1065 | ! |
if (with_reporter) { |
1066 | ! |
card_fun <- function(comment, label) { |
1067 | ! |
card <- teal::report_card_template( |
1068 | ! |
title = "Scatter Plot", |
1069 | ! |
label = label, |
1070 | ! |
with_filter = with_filter, |
1071 | ! |
filter_panel_api = filter_panel_api |
1072 |
) |
|
1073 | ! |
card$append_text("Plot", "header3") |
1074 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
1075 | ! |
if (!comment == "") { |
1076 | ! |
card$append_text("Comment", "header3") |
1077 | ! |
card$append_text(comment) |
1078 |
} |
|
1079 | ! |
card$append_src(teal.code::get_code(req(decorated_output_plot_q()))) |
1080 | ! |
card |
1081 |
} |
|
1082 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
1083 |
} |
|
1084 |
### |
|
1085 |
}) |
|
1086 |
} |
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 | ! |
include_css_files("custom"), |
107 | ! |
teal.widgets::standard_layout( |
108 | ! |
output = tags$div( |
109 | ! |
uiOutput(ns("output")) |
110 |
), |
|
111 | ! |
encoding = tags$div( |
112 | ! |
class = "file_viewer_encoding", |
113 | ! |
tags$label("Encodings", class = "text-primary"), |
114 | ! |
shinyTree::shinyTree( |
115 | ! |
ns("tree"), |
116 | ! |
dragAndDrop = FALSE, |
117 | ! |
sort = FALSE, |
118 | ! |
wholerow = TRUE, |
119 | ! |
theme = "proton", |
120 | ! |
multiple = FALSE |
121 |
) |
|
122 |
) |
|
123 |
) |
|
124 |
) |
|
125 |
} |
|
126 | ||
127 |
# Server function for the file viewer module |
|
128 |
srv_viewer <- function(id, input_path) { |
|
129 | ! |
moduleServer(id, function(input, output, session) { |
130 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
131 | ||
132 | ! |
temp_dir <- tempfile() |
133 | ! |
if (!dir.exists(temp_dir)) { |
134 | ! |
dir.create(temp_dir, recursive = TRUE) |
135 |
} |
|
136 | ! |
addResourcePath(basename(temp_dir), temp_dir) |
137 | ||
138 | ! |
test_path_text <- function(selected_path, type) { |
139 | ! |
out <- tryCatch( |
140 | ! |
expr = { |
141 | ! |
if (type != "url") { |
142 | ! |
selected_path <- normalizePath(selected_path, winslash = "/") |
143 |
} |
|
144 | ! |
readLines(con = selected_path) |
145 |
}, |
|
146 | ! |
error = function(cond) FALSE, |
147 | ! |
warning = function(cond) { |
148 | ! |
`if`(grepl("^incomplete final line found on", cond[[1]]), suppressWarnings(eval(cond[[2]])), FALSE) |
149 |
} |
|
150 |
) |
|
151 |
} |
|
152 | ||
153 | ! |
handle_connection_type <- function(selected_path) { |
154 | ! |
file_extension <- tools::file_ext(selected_path) |
155 | ! |
file_class <- suppressWarnings(file(selected_path)) |
156 | ! |
close(file_class) |
157 | ||
158 | ! |
output_text <- test_path_text(selected_path, type = class(file_class)[1]) |
159 | ||
160 | ! |
if (class(file_class)[1] == "url") { |
161 | ! |
list(selected_path = selected_path, output_text = output_text) |
162 |
} else { |
|
163 | ! |
file.copy(normalizePath(selected_path, winslash = "/"), temp_dir) |
164 | ! |
selected_path <- file.path(basename(temp_dir), basename(selected_path)) |
165 | ! |
list(selected_path = selected_path, output_text = output_text) |
166 |
} |
|
167 |
} |
|
168 | ||
169 | ! |
display_file <- function(selected_path) { |
170 | ! |
con_type <- handle_connection_type(selected_path) |
171 | ! |
file_extension <- tools::file_ext(selected_path) |
172 | ! |
if (file_extension %in% c("png", "apng", "jpg", "jpeg", "svg", "gif", "webp", "bmp")) { |
173 | ! |
tags$img(src = con_type$selected_path, alt = "file does not exist") |
174 | ! |
} else if (file_extension == "pdf") { |
175 | ! |
tags$embed( |
176 | ! |
class = "embed_pdf", |
177 | ! |
src = con_type$selected_path |
178 |
) |
|
179 | ! |
} else if (!isFALSE(con_type$output_text[1])) { |
180 | ! |
tags$pre(paste0(con_type$output_text, collapse = "\n")) |
181 |
} else { |
|
182 | ! |
tags$p("Please select a supported format.") |
183 |
} |
|
184 |
} |
|
185 | ||
186 | ! |
tree_list <- function(file_or_dir) { |
187 | ! |
nested_list <- lapply(file_or_dir, function(path) { |
188 | ! |
file_class <- suppressWarnings(file(path)) |
189 | ! |
close(file_class) |
190 | ! |
if (class(file_class)[[1]] != "url") { |
191 | ! |
isdir <- file.info(path)$isdir |
192 | ! |
if (!isdir) { |
193 | ! |
structure(path, ancestry = path, sticon = "file") |
194 |
} else { |
|
195 | ! |
files <- list.files(path, full.names = TRUE, include.dirs = TRUE) |
196 | ! |
out <- lapply(files, function(x) tree_list(x)) |
197 | ! |
out <- unlist(out, recursive = FALSE) |
198 | ! |
if (length(files) > 0) names(out) <- basename(files) |
199 | ! |
out |
200 |
} |
|
201 |
} else { |
|
202 | ! |
structure(path, ancestry = path, sticon = "file") |
203 |
} |
|
204 |
}) |
|
205 | ||
206 | ! |
missing_labels <- if (is.null(names(nested_list))) seq_along(nested_list) else which(names(nested_list) == "") |
207 | ! |
names(nested_list)[missing_labels] <- file_or_dir[missing_labels] |
208 | ! |
nested_list |
209 |
} |
|
210 | ||
211 | ! |
output$tree <- shinyTree::renderTree({ |
212 | ! |
if (length(input_path) > 0) { |
213 | ! |
tree_list(input_path) |
214 |
} else { |
|
215 | ! |
list("Empty Path" = NULL) |
216 |
} |
|
217 |
}) |
|
218 | ||
219 | ! |
output$output <- renderUI({ |
220 | ! |
validate( |
221 | ! |
need( |
222 | ! |
length(shinyTree::get_selected(input$tree)) > 0, |
223 | ! |
"Please select a file." |
224 |
) |
|
225 |
) |
|
226 | ||
227 | ! |
obj <- shinyTree::get_selected(input$tree, format = "names")[[1]] |
228 | ! |
repo <- attr(obj, "ancestry") |
229 | ! |
repo_collapsed <- if (length(repo) > 1) paste0(repo, collapse = "/") else repo |
230 | ! |
is_not_named <- file.exists(file.path(c(repo_collapsed, obj[1])))[1] |
231 | ||
232 | ! |
if (is_not_named) { |
233 | ! |
selected_path <- do.call("file.path", as.list(c(repo, obj[1]))) |
234 |
} else { |
|
235 | ! |
if (length(repo) == 0) { |
236 | ! |
selected_path <- do.call("file.path", as.list(attr(input$tree[[obj[1]]], "ancestry"))) |
237 |
} else { |
|
238 | ! |
selected_path <- do.call("file.path", as.list(attr(input$tree[[repo]][[obj[1]]], "ancestry"))) |
239 |
} |
|
240 |
} |
|
241 | ||
242 | ! |
validate( |
243 | ! |
need( |
244 | ! |
!isTRUE(file.info(selected_path)$isdir) && length(selected_path) > 0, |
245 | ! |
"Please select a single file." |
246 |
) |
|
247 |
) |
|
248 | ! |
display_file(selected_path) |
249 |
}) |
|
250 | ||
251 | ! |
onStop(function() { |
252 | ! |
removeResourcePath(basename(temp_dir)) |
253 | ! |
unlink(temp_dir) |
254 |
}) |
|
255 |
}) |
|
256 |
} |
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 |
#' @param decorators `r roxygen_decorators_param("tm_a_regression")` |
|
44 |
#' |
|
45 |
#' @inherit shared_params return |
|
46 |
#' |
|
47 |
#' @section Decorating `tm_a_regression`: |
|
48 |
#' |
|
49 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
50 |
#' - `plot` (`ggplot2`) |
|
51 |
#' |
|
52 |
#' For additional details and examples of decorators, refer to the vignette |
|
53 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
54 |
#' |
|
55 |
#' @examplesShinylive |
|
56 |
#' library(teal.modules.general) |
|
57 |
#' interactive <- function() TRUE |
|
58 |
#' {{ next_example }} |
|
59 |
#' @examples |
|
60 |
#' |
|
61 |
#' # general data example |
|
62 |
#' data <- teal_data() |
|
63 |
#' data <- within(data, { |
|
64 |
#' require(nestcolor) |
|
65 |
#' CO2 <- CO2 |
|
66 |
#' }) |
|
67 |
#' |
|
68 |
#' app <- init( |
|
69 |
#' data = data, |
|
70 |
#' modules = modules( |
|
71 |
#' tm_a_regression( |
|
72 |
#' label = "Regression", |
|
73 |
#' response = data_extract_spec( |
|
74 |
#' dataname = "CO2", |
|
75 |
#' select = select_spec( |
|
76 |
#' label = "Select variable:", |
|
77 |
#' choices = "uptake", |
|
78 |
#' selected = "uptake", |
|
79 |
#' multiple = FALSE, |
|
80 |
#' fixed = TRUE |
|
81 |
#' ) |
|
82 |
#' ), |
|
83 |
#' regressor = data_extract_spec( |
|
84 |
#' dataname = "CO2", |
|
85 |
#' select = select_spec( |
|
86 |
#' label = "Select variables:", |
|
87 |
#' choices = variable_choices(data[["CO2"]], c("conc", "Treatment")), |
|
88 |
#' selected = "conc", |
|
89 |
#' multiple = TRUE, |
|
90 |
#' fixed = FALSE |
|
91 |
#' ) |
|
92 |
#' ) |
|
93 |
#' ) |
|
94 |
#' ) |
|
95 |
#' ) |
|
96 |
#' if (interactive()) { |
|
97 |
#' shinyApp(app$ui, app$server) |
|
98 |
#' } |
|
99 |
#' |
|
100 |
#' @examplesShinylive |
|
101 |
#' library(teal.modules.general) |
|
102 |
#' interactive <- function() TRUE |
|
103 |
#' {{ next_example }} |
|
104 |
#' @examples |
|
105 |
#' # CDISC data example |
|
106 |
#' data <- teal_data() |
|
107 |
#' data <- within(data, { |
|
108 |
#' require(nestcolor) |
|
109 |
#' ADSL <- teal.data::rADSL |
|
110 |
#' }) |
|
111 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
112 |
#' |
|
113 |
#' app <- init( |
|
114 |
#' data = data, |
|
115 |
#' modules = modules( |
|
116 |
#' tm_a_regression( |
|
117 |
#' label = "Regression", |
|
118 |
#' response = data_extract_spec( |
|
119 |
#' dataname = "ADSL", |
|
120 |
#' select = select_spec( |
|
121 |
#' label = "Select variable:", |
|
122 |
#' choices = "BMRKR1", |
|
123 |
#' selected = "BMRKR1", |
|
124 |
#' multiple = FALSE, |
|
125 |
#' fixed = TRUE |
|
126 |
#' ) |
|
127 |
#' ), |
|
128 |
#' regressor = data_extract_spec( |
|
129 |
#' dataname = "ADSL", |
|
130 |
#' select = select_spec( |
|
131 |
#' label = "Select variables:", |
|
132 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "SEX", "RACE")), |
|
133 |
#' selected = "AGE", |
|
134 |
#' multiple = TRUE, |
|
135 |
#' fixed = FALSE |
|
136 |
#' ) |
|
137 |
#' ) |
|
138 |
#' ) |
|
139 |
#' ) |
|
140 |
#' ) |
|
141 |
#' if (interactive()) { |
|
142 |
#' shinyApp(app$ui, app$server) |
|
143 |
#' } |
|
144 |
#' |
|
145 |
#' @export |
|
146 |
#' |
|
147 |
tm_a_regression <- function(label = "Regression Analysis", |
|
148 |
regressor, |
|
149 |
response, |
|
150 |
plot_height = c(600, 200, 2000), |
|
151 |
plot_width = NULL, |
|
152 |
alpha = c(1, 0, 1), |
|
153 |
size = c(2, 1, 8), |
|
154 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
155 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
156 |
pre_output = NULL, |
|
157 |
post_output = NULL, |
|
158 |
default_plot_type = 1, |
|
159 |
default_outlier_label = "USUBJID", |
|
160 |
label_segment_threshold = c(0.5, 0, 10), |
|
161 |
decorators = NULL) { |
|
162 | ! |
message("Initializing tm_a_regression") |
163 | ||
164 |
# Normalize the parameters |
|
165 | ! |
if (inherits(regressor, "data_extract_spec")) regressor <- list(regressor) |
166 | ! |
if (inherits(response, "data_extract_spec")) response <- list(response) |
167 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
168 | ||
169 |
# Start of assertions |
|
170 | ! |
checkmate::assert_string(label) |
171 | ! |
checkmate::assert_list(regressor, types = "data_extract_spec") |
172 | ||
173 | ! |
checkmate::assert_list(response, types = "data_extract_spec") |
174 | ! |
assert_single_selection(response) |
175 | ||
176 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
177 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
178 | ||
179 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
180 | ! |
checkmate::assert_numeric( |
181 | ! |
plot_width[1], |
182 | ! |
lower = plot_width[2], |
183 | ! |
upper = plot_width[3], |
184 | ! |
null.ok = TRUE, |
185 | ! |
.var.name = "plot_width" |
186 |
) |
|
187 | ||
188 | ! |
if (length(alpha) == 1) { |
189 | ! |
checkmate::assert_numeric(alpha, any.missing = FALSE, finite = TRUE) |
190 |
} else { |
|
191 | ! |
checkmate::assert_numeric(alpha, len = 3, any.missing = FALSE, finite = TRUE) |
192 | ! |
checkmate::assert_numeric(alpha[1], lower = alpha[2], upper = alpha[3], .var.name = "alpha") |
193 |
} |
|
194 | ||
195 | ! |
if (length(size) == 1) { |
196 | ! |
checkmate::assert_numeric(size, any.missing = FALSE, finite = TRUE) |
197 |
} else { |
|
198 | ! |
checkmate::assert_numeric(size, len = 3, any.missing = FALSE, finite = TRUE) |
199 | ! |
checkmate::assert_numeric(size[1], lower = size[2], upper = size[3], .var.name = "size") |
200 |
} |
|
201 | ||
202 | ! |
ggtheme <- match.arg(ggtheme) |
203 | ||
204 | ! |
plot_choices <- c( |
205 | ! |
"Response vs Regressor", "Residuals vs Fitted", "Normal Q-Q", "Scale-Location", |
206 | ! |
"Cook's distance", "Residuals vs Leverage", "Cook's dist vs Leverage" |
207 |
) |
|
208 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
209 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
210 | ||
211 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
212 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
213 | ! |
checkmate::assert_choice(default_plot_type, seq.int(1L, length(plot_choices))) |
214 | ! |
checkmate::assert_string(default_outlier_label) |
215 | ! |
checkmate::assert_list(decorators, "teal_transform_module", null.ok = TRUE) |
216 | ||
217 | ! |
if (length(label_segment_threshold) == 1) { |
218 | ! |
checkmate::assert_numeric(label_segment_threshold, any.missing = FALSE, finite = TRUE) |
219 |
} else { |
|
220 | ! |
checkmate::assert_numeric(label_segment_threshold, len = 3, any.missing = FALSE, finite = TRUE) |
221 | ! |
checkmate::assert_numeric( |
222 | ! |
label_segment_threshold[1], |
223 | ! |
lower = label_segment_threshold[2], |
224 | ! |
upper = label_segment_threshold[3], |
225 | ! |
.var.name = "label_segment_threshold" |
226 |
) |
|
227 |
} |
|
228 | ! |
decorators <- normalize_decorators(decorators) |
229 | ! |
assert_decorators(decorators, "plot", null.ok = TRUE) |
230 |
# End of assertions |
|
231 | ||
232 |
# Make UI args |
|
233 | ! |
args <- as.list(environment()) |
234 | ! |
args[["plot_choices"]] <- plot_choices |
235 | ! |
data_extract_list <- list( |
236 | ! |
regressor = regressor, |
237 | ! |
response = response |
238 |
) |
|
239 | ||
240 | ! |
ans <- module( |
241 | ! |
label = label, |
242 | ! |
server = srv_a_regression, |
243 | ! |
ui = ui_a_regression, |
244 | ! |
ui_args = args, |
245 | ! |
server_args = c( |
246 | ! |
data_extract_list, |
247 | ! |
list( |
248 | ! |
plot_height = plot_height, |
249 | ! |
plot_width = plot_width, |
250 | ! |
default_outlier_label = default_outlier_label, |
251 | ! |
ggplot2_args = ggplot2_args, |
252 | ! |
decorators = decorators |
253 |
) |
|
254 |
), |
|
255 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
256 |
) |
|
257 | ! |
attr(ans, "teal_bookmarkable") <- FALSE |
258 | ! |
ans |
259 |
} |
|
260 | ||
261 |
# UI function for the regression module |
|
262 |
ui_a_regression <- function(id, ...) { |
|
263 | ! |
ns <- NS(id) |
264 | ! |
args <- list(...) |
265 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$regressor, args$response) |
266 | ! |
teal.widgets::standard_layout( |
267 | ! |
output = teal.widgets::white_small_well(tags$div( |
268 | ! |
teal.widgets::plot_with_settings_ui(id = ns("myplot")), |
269 | ! |
tags$div(verbatimTextOutput(ns("text"))) |
270 |
)), |
|
271 | ! |
encoding = tags$div( |
272 |
### Reporter |
|
273 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
274 |
### |
|
275 | ! |
tags$label("Encodings", class = "text-primary"), |
276 | ! |
teal.transform::datanames_input(args[c("response", "regressor")]), |
277 | ! |
teal.transform::data_extract_ui( |
278 | ! |
id = ns("response"), |
279 | ! |
label = "Response variable", |
280 | ! |
data_extract_spec = args$response, |
281 | ! |
is_single_dataset = is_single_dataset_value |
282 |
), |
|
283 | ! |
teal.transform::data_extract_ui( |
284 | ! |
id = ns("regressor"), |
285 | ! |
label = "Regressor variables", |
286 | ! |
data_extract_spec = args$regressor, |
287 | ! |
is_single_dataset = is_single_dataset_value |
288 |
), |
|
289 | ! |
radioButtons( |
290 | ! |
ns("plot_type"), |
291 | ! |
label = "Plot type:", |
292 | ! |
choices = args$plot_choices, |
293 | ! |
selected = args$plot_choices[args$default_plot_type] |
294 |
), |
|
295 | ! |
checkboxInput(ns("show_outlier"), label = "Display outlier labels", value = TRUE), |
296 | ! |
conditionalPanel( |
297 | ! |
condition = "input['show_outlier']", |
298 | ! |
ns = ns, |
299 | ! |
teal.widgets::optionalSliderInput( |
300 | ! |
ns("outlier"), |
301 | ! |
tags$div( |
302 | ! |
class = "teal-tooltip", |
303 | ! |
tagList( |
304 | ! |
"Outlier definition:", |
305 | ! |
icon("circle-info"), |
306 | ! |
tags$span( |
307 | ! |
class = "tooltiptext", |
308 | ! |
paste( |
309 | ! |
"Use the slider to choose the cut-off value to define outliers.", |
310 | ! |
"Points with a Cook's distance greater than", |
311 | ! |
"the value on the slider times the mean of the Cook's distance of the dataset will have labels." |
312 |
) |
|
313 |
) |
|
314 |
) |
|
315 |
), |
|
316 | ! |
min = 1, max = 10, value = 9, ticks = FALSE, step = .1 |
317 |
), |
|
318 | ! |
teal.widgets::optionalSelectInput( |
319 | ! |
ns("label_var"), |
320 | ! |
multiple = FALSE, |
321 | ! |
label = "Outlier label" |
322 |
) |
|
323 |
), |
|
324 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")), |
325 | ! |
teal.widgets::panel_group( |
326 | ! |
teal.widgets::panel_item( |
327 | ! |
title = "Plot settings", |
328 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("alpha"), "Opacity:", args$alpha, ticks = FALSE), |
329 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("size"), "Points size:", args$size, ticks = FALSE), |
330 | ! |
teal.widgets::optionalSliderInputValMinMax( |
331 | ! |
inputId = ns("label_min_segment"), |
332 | ! |
label = tags$div( |
333 | ! |
class = "teal-tooltip", |
334 | ! |
tagList( |
335 | ! |
"Label min. segment:", |
336 | ! |
icon("circle-info"), |
337 | ! |
tags$span( |
338 | ! |
class = "tooltiptext", |
339 | ! |
paste( |
340 | ! |
"Use the slider to choose the cut-off value to define minimum distance between label and point", |
341 | ! |
"that generates a line segment.", |
342 | ! |
"It's only valid when 'Display outlier labels' is checked." |
343 |
) |
|
344 |
) |
|
345 |
) |
|
346 |
), |
|
347 | ! |
value_min_max = args$label_segment_threshold, |
348 |
# Extra parameters to sliderInput |
|
349 | ! |
ticks = FALSE, |
350 | ! |
step = .1, |
351 | ! |
round = FALSE |
352 |
), |
|
353 | ! |
selectInput( |
354 | ! |
inputId = ns("ggtheme"), |
355 | ! |
label = "Theme (by ggplot):", |
356 | ! |
choices = ggplot_themes, |
357 | ! |
selected = args$ggtheme, |
358 | ! |
multiple = FALSE |
359 |
) |
|
360 |
) |
|
361 |
) |
|
362 |
), |
|
363 | ! |
forms = tagList( |
364 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
365 |
), |
|
366 | ! |
pre_output = args$pre_output, |
367 | ! |
post_output = args$post_output |
368 |
) |
|
369 |
} |
|
370 | ||
371 |
# Server function for the regression module |
|
372 |
srv_a_regression <- function(id, |
|
373 |
data, |
|
374 |
reporter, |
|
375 |
filter_panel_api, |
|
376 |
response, |
|
377 |
regressor, |
|
378 |
plot_height, |
|
379 |
plot_width, |
|
380 |
ggplot2_args, |
|
381 |
default_outlier_label, |
|
382 |
decorators) { |
|
383 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
384 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
385 | ! |
checkmate::assert_class(data, "reactive") |
386 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
387 | ! |
moduleServer(id, function(input, output, session) { |
388 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
389 | ||
390 | ! |
ns <- session$ns |
391 | ||
392 | ! |
rule_rvr1 <- function(value) { |
393 | ! |
if (isTRUE(input$plot_type == "Response vs Regressor")) { |
394 | ! |
if (length(value) > 1L) { |
395 | ! |
"This plot can only have one regressor." |
396 |
} |
|
397 |
} |
|
398 |
} |
|
399 | ! |
rule_rvr2 <- function(other) { |
400 | ! |
function(value) { |
401 | ! |
if (isTRUE(input$plot_type == "Response vs Regressor")) { |
402 | ! |
otherval <- selector_list()[[other]]()$select |
403 | ! |
if (isTRUE(value == otherval)) { |
404 | ! |
"Response and Regressor must be different." |
405 |
} |
|
406 |
} |
|
407 |
} |
|
408 |
} |
|
409 | ||
410 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
411 | ! |
data_extract = list(response = response, regressor = regressor), |
412 | ! |
datasets = data, |
413 | ! |
select_validation_rule = list( |
414 | ! |
regressor = shinyvalidate::compose_rules( |
415 | ! |
shinyvalidate::sv_required("At least one regressor should be selected."), |
416 | ! |
rule_rvr1, |
417 | ! |
rule_rvr2("response") |
418 |
), |
|
419 | ! |
response = shinyvalidate::compose_rules( |
420 | ! |
shinyvalidate::sv_required("At least one response should be selected."), |
421 | ! |
rule_rvr2("regressor") |
422 |
) |
|
423 |
) |
|
424 |
) |
|
425 | ||
426 | ! |
iv_r <- reactive({ |
427 | ! |
iv <- shinyvalidate::InputValidator$new() |
428 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
429 |
}) |
|
430 | ||
431 | ! |
iv_out <- shinyvalidate::InputValidator$new() |
432 | ! |
iv_out$condition(~ isTRUE(input$show_outlier)) |
433 | ! |
iv_out$add_rule("label_var", shinyvalidate::sv_required("Please provide an `Outlier label` variable")) |
434 | ! |
iv_out$enable() |
435 | ||
436 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
437 | ! |
selector_list = selector_list, |
438 | ! |
datasets = data |
439 |
) |
|
440 | ||
441 | ! |
regression_var <- reactive({ |
442 | ! |
teal::validate_inputs(iv_r()) |
443 | ||
444 | ! |
list( |
445 | ! |
response = as.vector(anl_merged_input()$columns_source$response), |
446 | ! |
regressor = as.vector(anl_merged_input()$columns_source$regressor) |
447 |
) |
|
448 |
}) |
|
449 | ||
450 | ! |
anl_merged_q <- reactive({ |
451 | ! |
req(anl_merged_input()) |
452 | ! |
data() %>% |
453 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
454 |
}) |
|
455 | ||
456 |
# sets qenv object and populates it with data merge call and fit expression |
|
457 | ! |
fit_r <- reactive({ |
458 | ! |
ANL <- anl_merged_q()[["ANL"]] |
459 | ! |
teal::validate_has_data(ANL, 10) |
460 | ||
461 | ! |
validate(need(is.numeric(ANL[regression_var()$response][[1]]), "Response variable should be numeric.")) |
462 | ||
463 | ! |
teal::validate_has_data( |
464 | ! |
ANL[, c(regression_var()$response, regression_var()$regressor)], 10, |
465 | ! |
complete = TRUE, allow_inf = FALSE |
466 |
) |
|
467 | ||
468 | ! |
form <- stats::as.formula( |
469 | ! |
paste( |
470 | ! |
regression_var()$response, |
471 | ! |
paste( |
472 | ! |
regression_var()$regressor, |
473 | ! |
collapse = " + " |
474 |
), |
|
475 | ! |
sep = " ~ " |
476 |
) |
|
477 |
) |
|
478 | ||
479 | ! |
if (input$show_outlier) { |
480 | ! |
opts <- teal.transform::variable_choices(ANL) |
481 | ! |
selected <- if (!is.null(isolate(input$label_var)) && isolate(input$label_var) %in% as.character(opts)) { |
482 | ! |
isolate(input$label_var) |
483 |
} else { |
|
484 | ! |
if (length(opts[as.character(opts) == default_outlier_label]) == 0) { |
485 | ! |
opts[[1]] |
486 |
} else { |
|
487 | ! |
opts[as.character(opts) == default_outlier_label] |
488 |
} |
|
489 |
} |
|
490 | ! |
teal.widgets::updateOptionalSelectInput( |
491 | ! |
session = session, |
492 | ! |
inputId = "label_var", |
493 | ! |
choices = opts, |
494 | ! |
selected = restoreInput(ns("label_var"), selected) |
495 |
) |
|
496 | ||
497 | ! |
data <- fortify(stats::lm(form, data = ANL)) |
498 | ! |
cooksd <- data$.cooksd[!is.nan(data$.cooksd)] |
499 | ! |
max_outlier <- max(ceiling(max(cooksd) / mean(cooksd)), 2) |
500 | ! |
cur_outlier <- isolate(input$outlier) |
501 | ! |
updateSliderInput( |
502 | ! |
session = session, |
503 | ! |
inputId = "outlier", |
504 | ! |
min = 1, |
505 | ! |
max = max_outlier, |
506 | ! |
value = restoreInput(ns("outlier"), if (cur_outlier < max_outlier) cur_outlier else max_outlier * .9) |
507 |
) |
|
508 |
} |
|
509 | ||
510 | ! |
anl_merged_q() %>% |
511 | ! |
teal.code::eval_code(substitute(fit <- stats::lm(form, data = ANL), env = list(form = form))) %>% |
512 | ! |
teal.code::eval_code(quote({ |
513 | ! |
for (regressor in names(fit$contrasts)) { |
514 | ! |
alts <- paste0(levels(ANL[[regressor]]), collapse = "|") |
515 | ! |
names(fit$coefficients) <- gsub( |
516 | ! |
paste0("^(", regressor, ")(", alts, ")$"), paste0("\\1", ": ", "\\2"), names(fit$coefficients) |
517 |
) |
|
518 |
} |
|
519 |
})) %>% |
|
520 | ! |
teal.code::eval_code(quote(summary(fit))) |
521 |
}) |
|
522 | ||
523 | ! |
label_col <- reactive({ |
524 | ! |
teal::validate_inputs(iv_out) |
525 | ||
526 | ! |
substitute( |
527 | ! |
expr = dplyr::if_else( |
528 | ! |
data$.cooksd > outliers * mean(data$.cooksd, na.rm = TRUE), |
529 | ! |
as.character(stats::na.omit(ANL)[[label_var]]), |
530 |
"" |
|
531 |
) %>% |
|
532 | ! |
dplyr::if_else(is.na(.), "cooksd == NaN", .), |
533 | ! |
env = list(outliers = input$outlier, label_var = input$label_var) |
534 |
) |
|
535 |
}) |
|
536 | ||
537 | ! |
label_min_segment <- reactive({ |
538 | ! |
input$label_min_segment |
539 |
}) |
|
540 | ||
541 | ! |
outlier_label <- reactive({ |
542 | ! |
substitute( |
543 | ! |
expr = ggrepel::geom_text_repel( |
544 | ! |
label = label_col, |
545 | ! |
color = "red", |
546 | ! |
hjust = 0, |
547 | ! |
vjust = 1, |
548 | ! |
max.overlaps = Inf, |
549 | ! |
min.segment.length = label_min_segment, |
550 | ! |
segment.alpha = 0.5, |
551 | ! |
seed = 123 |
552 |
), |
|
553 | ! |
env = list(label_col = label_col(), label_min_segment = label_min_segment()) |
554 |
) |
|
555 |
}) |
|
556 | ||
557 | ! |
output_plot_base <- reactive({ |
558 | ! |
base_fit <- fit_r() |
559 | ! |
teal.code::eval_code( |
560 | ! |
base_fit, |
561 | ! |
quote({ |
562 | ! |
class(fit$residuals) <- NULL |
563 | ||
564 | ! |
data <- ggplot2::fortify(fit) |
565 | ||
566 | ! |
smooth <- function(x, y) { |
567 | ! |
as.data.frame(stats::lowess(x, y, f = 2 / 3, iter = 3)) |
568 |
} |
|
569 | ||
570 | ! |
smoothy_aes <- ggplot2::aes_string(x = "x", y = "y") |
571 | ||
572 | ! |
reg_form <- deparse(fit$call[[2]]) |
573 |
}) |
|
574 |
) |
|
575 |
}) |
|
576 | ||
577 | ! |
output_plot_0 <- reactive({ |
578 | ! |
fit <- fit_r()[["fit"]] |
579 | ! |
ANL <- anl_merged_q()[["ANL"]] |
580 | ||
581 | ! |
stopifnot(ncol(fit$model) == 2) |
582 | ||
583 | ! |
if (!is.factor(ANL[[regression_var()$regressor]])) { |
584 | ! |
shinyjs::show("size") |
585 | ! |
shinyjs::show("alpha") |
586 | ! |
plot <- substitute( |
587 | ! |
expr = ggplot(fit$model[, 2:1], aes_string(regressor, response)) + |
588 | ! |
geom_point(size = size, alpha = alpha) + |
589 | ! |
stat_smooth(method = "lm", formula = y ~ x, se = FALSE), |
590 | ! |
env = list( |
591 | ! |
regressor = regression_var()$regressor, |
592 | ! |
response = regression_var()$response, |
593 | ! |
size = input$size, |
594 | ! |
alpha = input$alpha |
595 |
) |
|
596 |
) |
|
597 | ! |
if (input$show_outlier) { |
598 | ! |
plot <- substitute( |
599 | ! |
expr = plot + outlier_label, |
600 | ! |
env = list(plot = plot, outlier_label = outlier_label()) |
601 |
) |
|
602 |
} |
|
603 |
} else { |
|
604 | ! |
shinyjs::hide("size") |
605 | ! |
shinyjs::hide("alpha") |
606 | ! |
plot <- substitute( |
607 | ! |
expr = ggplot(fit$model[, 2:1], aes_string(regressor, response)) + |
608 | ! |
geom_boxplot(), |
609 | ! |
env = list(regressor = regression_var()$regressor, response = regression_var()$response) |
610 |
) |
|
611 | ! |
if (input$show_outlier) { |
612 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
613 |
} |
|
614 |
} |
|
615 | ||
616 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
617 | ! |
teal.widgets::resolve_ggplot2_args( |
618 | ! |
user_plot = ggplot2_args[["Response vs Regressor"]], |
619 | ! |
user_default = ggplot2_args$default, |
620 | ! |
module_plot = teal.widgets::ggplot2_args( |
621 | ! |
labs = list( |
622 | ! |
title = "Response vs Regressor", |
623 | ! |
x = varname_w_label(regression_var()$regressor, ANL), |
624 | ! |
y = varname_w_label(regression_var()$response, ANL) |
625 |
), |
|
626 | ! |
theme = list() |
627 |
) |
|
628 |
), |
|
629 | ! |
ggtheme = input$ggtheme |
630 |
) |
|
631 | ||
632 | ! |
teal.code::eval_code( |
633 | ! |
fit_r(), |
634 | ! |
substitute( |
635 | ! |
expr = { |
636 | ! |
class(fit$residuals) <- NULL |
637 | ! |
data <- fortify(fit) |
638 | ! |
plot <- graph |
639 |
}, |
|
640 | ! |
env = list( |
641 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
642 |
) |
|
643 |
) |
|
644 |
) |
|
645 |
}) |
|
646 | ||
647 | ! |
output_plot_1 <- reactive({ |
648 | ! |
plot_base <- output_plot_base() |
649 | ! |
shinyjs::show("size") |
650 | ! |
shinyjs::show("alpha") |
651 | ! |
plot <- substitute( |
652 | ! |
expr = ggplot(data = data, aes(.fitted, .resid)) + |
653 | ! |
geom_point(size = size, alpha = alpha) + |
654 | ! |
geom_hline(yintercept = 0, linetype = "dashed", size = 1) + |
655 | ! |
geom_line(data = smoothy, mapping = smoothy_aes), |
656 | ! |
env = list(size = input$size, alpha = input$alpha) |
657 |
) |
|
658 | ! |
if (input$show_outlier) { |
659 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
660 |
} |
|
661 | ||
662 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
663 | ! |
teal.widgets::resolve_ggplot2_args( |
664 | ! |
user_plot = ggplot2_args[["Residuals vs Fitted"]], |
665 | ! |
user_default = ggplot2_args$default, |
666 | ! |
module_plot = teal.widgets::ggplot2_args( |
667 | ! |
labs = list( |
668 | ! |
x = quote(paste0("Fitted values\nlm(", reg_form, ")")), |
669 | ! |
y = "Residuals", |
670 | ! |
title = "Residuals vs Fitted" |
671 |
) |
|
672 |
) |
|
673 |
), |
|
674 | ! |
ggtheme = input$ggtheme |
675 |
) |
|
676 | ||
677 | ! |
teal.code::eval_code( |
678 | ! |
plot_base, |
679 | ! |
substitute( |
680 | ! |
expr = { |
681 | ! |
smoothy <- smooth(data$.fitted, data$.resid) |
682 | ! |
plot <- graph |
683 |
}, |
|
684 | ! |
env = list( |
685 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
686 |
) |
|
687 |
) |
|
688 |
) |
|
689 |
}) |
|
690 | ||
691 | ! |
output_plot_2 <- reactive({ |
692 | ! |
shinyjs::show("size") |
693 | ! |
shinyjs::show("alpha") |
694 | ! |
plot_base <- output_plot_base() |
695 | ! |
plot <- substitute( |
696 | ! |
expr = ggplot(data = data, aes(sample = .stdresid)) + |
697 | ! |
stat_qq(size = size, alpha = alpha) + |
698 | ! |
geom_abline(linetype = "dashed"), |
699 | ! |
env = list(size = input$size, alpha = input$alpha) |
700 |
) |
|
701 | ! |
if (input$show_outlier) { |
702 | ! |
plot <- substitute( |
703 | ! |
expr = plot + |
704 | ! |
stat_qq( |
705 | ! |
geom = ggrepel::GeomTextRepel, |
706 | ! |
label = label_col %>% |
707 | ! |
data.frame(label = .) %>% |
708 | ! |
dplyr::filter(label != "cooksd == NaN") %>% |
709 | ! |
unlist(), |
710 | ! |
color = "red", |
711 | ! |
hjust = 0, |
712 | ! |
vjust = 0, |
713 | ! |
max.overlaps = Inf, |
714 | ! |
min.segment.length = label_min_segment, |
715 | ! |
segment.alpha = .5, |
716 | ! |
seed = 123 |
717 |
), |
|
718 | ! |
env = list(plot = plot, label_col = label_col(), label_min_segment = label_min_segment()) |
719 |
) |
|
720 |
} |
|
721 | ||
722 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
723 | ! |
teal.widgets::resolve_ggplot2_args( |
724 | ! |
user_plot = ggplot2_args[["Normal Q-Q"]], |
725 | ! |
user_default = ggplot2_args$default, |
726 | ! |
module_plot = teal.widgets::ggplot2_args( |
727 | ! |
labs = list( |
728 | ! |
x = quote(paste0("Theoretical Quantiles\nlm(", reg_form, ")")), |
729 | ! |
y = "Standardized residuals", |
730 | ! |
title = "Normal Q-Q" |
731 |
) |
|
732 |
) |
|
733 |
), |
|
734 | ! |
ggtheme = input$ggtheme |
735 |
) |
|
736 | ||
737 | ! |
teal.code::eval_code( |
738 | ! |
plot_base, |
739 | ! |
substitute( |
740 | ! |
expr = { |
741 | ! |
plot <- graph |
742 |
}, |
|
743 | ! |
env = list( |
744 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
745 |
) |
|
746 |
) |
|
747 |
) |
|
748 |
}) |
|
749 | ||
750 | ! |
output_plot_3 <- reactive({ |
751 | ! |
shinyjs::show("size") |
752 | ! |
shinyjs::show("alpha") |
753 | ! |
plot_base <- output_plot_base() |
754 | ! |
plot <- substitute( |
755 | ! |
expr = ggplot(data = data, aes(.fitted, sqrt(abs(.stdresid)))) + |
756 | ! |
geom_point(size = size, alpha = alpha) + |
757 | ! |
geom_line(data = smoothy, mapping = smoothy_aes), |
758 | ! |
env = list(size = input$size, alpha = input$alpha) |
759 |
) |
|
760 | ! |
if (input$show_outlier) { |
761 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
762 |
} |
|
763 | ||
764 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
765 | ! |
teal.widgets::resolve_ggplot2_args( |
766 | ! |
user_plot = ggplot2_args[["Scale-Location"]], |
767 | ! |
user_default = ggplot2_args$default, |
768 | ! |
module_plot = teal.widgets::ggplot2_args( |
769 | ! |
labs = list( |
770 | ! |
x = quote(paste0("Fitted values\nlm(", reg_form, ")")), |
771 | ! |
y = quote(expression(sqrt(abs(`Standardized residuals`)))), |
772 | ! |
title = "Scale-Location" |
773 |
) |
|
774 |
) |
|
775 |
), |
|
776 | ! |
ggtheme = input$ggtheme |
777 |
) |
|
778 | ||
779 | ! |
teal.code::eval_code( |
780 | ! |
plot_base, |
781 | ! |
substitute( |
782 | ! |
expr = { |
783 | ! |
smoothy <- smooth(data$.fitted, sqrt(abs(data$.stdresid))) |
784 | ! |
plot <- graph |
785 |
}, |
|
786 | ! |
env = list( |
787 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
788 |
) |
|
789 |
) |
|
790 |
) |
|
791 |
}) |
|
792 | ||
793 | ! |
output_plot_4 <- reactive({ |
794 | ! |
shinyjs::hide("size") |
795 | ! |
shinyjs::show("alpha") |
796 | ! |
plot_base <- output_plot_base() |
797 | ! |
plot <- substitute( |
798 | ! |
expr = ggplot(data = data, aes(seq_along(.cooksd), .cooksd)) + |
799 | ! |
geom_col(alpha = alpha), |
800 | ! |
env = list(alpha = input$alpha) |
801 |
) |
|
802 | ! |
if (input$show_outlier) { |
803 | ! |
plot <- substitute( |
804 | ! |
expr = plot + |
805 | ! |
geom_hline( |
806 | ! |
yintercept = c( |
807 | ! |
outlier * mean(data$.cooksd, na.rm = TRUE), |
808 | ! |
mean(data$.cooksd, na.rm = TRUE) |
809 |
), |
|
810 | ! |
color = "red", |
811 | ! |
linetype = "dashed" |
812 |
) + |
|
813 | ! |
geom_text( |
814 | ! |
aes( |
815 | ! |
x = 0, |
816 | ! |
y = mean(data$.cooksd, na.rm = TRUE), |
817 | ! |
label = paste("mu", "=", round(mean(data$.cooksd, na.rm = TRUE), 4)), |
818 | ! |
vjust = -1, |
819 | ! |
hjust = 0, |
820 | ! |
color = "red", |
821 | ! |
angle = 90 |
822 |
), |
|
823 | ! |
parse = TRUE, |
824 | ! |
show.legend = FALSE |
825 |
) + |
|
826 | ! |
outlier_label, |
827 | ! |
env = list(plot = plot, outlier = input$outlier, outlier_label = outlier_label()) |
828 |
) |
|
829 |
} |
|
830 | ||
831 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
832 | ! |
teal.widgets::resolve_ggplot2_args( |
833 | ! |
user_plot = ggplot2_args[["Cook's distance"]], |
834 | ! |
user_default = ggplot2_args$default, |
835 | ! |
module_plot = teal.widgets::ggplot2_args( |
836 | ! |
labs = list( |
837 | ! |
x = quote(paste0("Obs. number\nlm(", reg_form, ")")), |
838 | ! |
y = "Cook's distance", |
839 | ! |
title = "Cook's distance" |
840 |
) |
|
841 |
) |
|
842 |
), |
|
843 | ! |
ggtheme = input$ggtheme |
844 |
) |
|
845 | ||
846 | ! |
teal.code::eval_code( |
847 | ! |
plot_base, |
848 | ! |
substitute( |
849 | ! |
expr = { |
850 | ! |
plot <- graph |
851 |
}, |
|
852 | ! |
env = list( |
853 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
854 |
) |
|
855 |
) |
|
856 |
) |
|
857 |
}) |
|
858 | ||
859 | ! |
output_plot_5 <- reactive({ |
860 | ! |
shinyjs::show("size") |
861 | ! |
shinyjs::show("alpha") |
862 | ! |
plot_base <- output_plot_base() |
863 | ! |
plot <- substitute( |
864 | ! |
expr = ggplot(data = data, aes(.hat, .stdresid)) + |
865 | ! |
geom_vline( |
866 | ! |
size = 1, |
867 | ! |
colour = "black", |
868 | ! |
linetype = "dashed", |
869 | ! |
xintercept = 0 |
870 |
) + |
|
871 | ! |
geom_hline( |
872 | ! |
size = 1, |
873 | ! |
colour = "black", |
874 | ! |
linetype = "dashed", |
875 | ! |
yintercept = 0 |
876 |
) + |
|
877 | ! |
geom_point(size = size, alpha = alpha) + |
878 | ! |
geom_line(data = smoothy, mapping = smoothy_aes), |
879 | ! |
env = list(size = input$size, alpha = input$alpha) |
880 |
) |
|
881 | ! |
if (input$show_outlier) { |
882 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
883 |
} |
|
884 | ||
885 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
886 | ! |
teal.widgets::resolve_ggplot2_args( |
887 | ! |
user_plot = ggplot2_args[["Residuals vs Leverage"]], |
888 | ! |
user_default = ggplot2_args$default, |
889 | ! |
module_plot = teal.widgets::ggplot2_args( |
890 | ! |
labs = list( |
891 | ! |
x = quote(paste0("Standardized residuals\nlm(", reg_form, ")")), |
892 | ! |
y = "Leverage", |
893 | ! |
title = "Residuals vs Leverage" |
894 |
) |
|
895 |
) |
|
896 |
), |
|
897 | ! |
ggtheme = input$ggtheme |
898 |
) |
|
899 | ||
900 | ! |
teal.code::eval_code( |
901 | ! |
plot_base, |
902 | ! |
substitute( |
903 | ! |
expr = { |
904 | ! |
smoothy <- smooth(data$.hat, data$.stdresid) |
905 | ! |
plot <- graph |
906 |
}, |
|
907 | ! |
env = list( |
908 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
909 |
) |
|
910 |
) |
|
911 |
) |
|
912 |
}) |
|
913 | ||
914 | ! |
output_plot_6 <- reactive({ |
915 | ! |
shinyjs::show("size") |
916 | ! |
shinyjs::show("alpha") |
917 | ! |
plot_base <- output_plot_base() |
918 | ! |
plot <- substitute( |
919 | ! |
expr = ggplot(data = data, aes(.hat, .cooksd)) + |
920 | ! |
geom_vline(xintercept = 0, colour = NA) + |
921 | ! |
geom_abline( |
922 | ! |
slope = seq(0, 3, by = 0.5), |
923 | ! |
colour = "black", |
924 | ! |
linetype = "dashed", |
925 | ! |
size = 1 |
926 |
) + |
|
927 | ! |
geom_line(data = smoothy, mapping = smoothy_aes) + |
928 | ! |
geom_point(size = size, alpha = alpha), |
929 | ! |
env = list(size = input$size, alpha = input$alpha) |
930 |
) |
|
931 | ! |
if (input$show_outlier) { |
932 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
933 |
} |
|
934 | ||
935 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
936 | ! |
teal.widgets::resolve_ggplot2_args( |
937 | ! |
user_plot = ggplot2_args[["Cook's dist vs Leverage"]], |
938 | ! |
user_default = ggplot2_args$default, |
939 | ! |
module_plot = teal.widgets::ggplot2_args( |
940 | ! |
labs = list( |
941 | ! |
x = quote(paste0("Leverage\nlm(", reg_form, ")")), |
942 | ! |
y = "Cooks's distance", |
943 | ! |
title = "Cook's dist vs Leverage" |
944 |
) |
|
945 |
) |
|
946 |
), |
|
947 | ! |
ggtheme = input$ggtheme |
948 |
) |
|
949 | ||
950 | ! |
teal.code::eval_code( |
951 | ! |
plot_base, |
952 | ! |
substitute( |
953 | ! |
expr = { |
954 | ! |
smoothy <- smooth(data$.hat, data$.cooksd) |
955 | ! |
plot <- graph |
956 |
}, |
|
957 | ! |
env = list( |
958 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
959 |
) |
|
960 |
) |
|
961 |
) |
|
962 |
}) |
|
963 | ||
964 | ! |
output_q <- reactive({ |
965 | ! |
teal::validate_inputs(iv_r()) |
966 | ! |
switch(input$plot_type, |
967 | ! |
"Response vs Regressor" = output_plot_0(), |
968 | ! |
"Residuals vs Fitted" = output_plot_1(), |
969 | ! |
"Normal Q-Q" = output_plot_2(), |
970 | ! |
"Scale-Location" = output_plot_3(), |
971 | ! |
"Cook's distance" = output_plot_4(), |
972 | ! |
"Residuals vs Leverage" = output_plot_5(), |
973 | ! |
"Cook's dist vs Leverage" = output_plot_6() |
974 |
) |
|
975 |
}) |
|
976 | ||
977 | ! |
decorated_output_q <- srv_decorate_teal_data( |
978 | ! |
"decorator", |
979 | ! |
data = output_q, |
980 | ! |
decorators = select_decorators(decorators, "plot"), |
981 | ! |
expr = print(plot) |
982 |
) |
|
983 | ||
984 | ! |
fitted <- reactive({ |
985 | ! |
req(output_q()) |
986 | ! |
decorated_output_q()[["fit"]] |
987 |
}) |
|
988 | ! |
plot_r <- reactive({ |
989 | ! |
req(output_q()) |
990 | ! |
decorated_output_q()[["plot"]] |
991 |
}) |
|
992 | ||
993 |
# Insert the plot into a plot_with_settings module from teal.widgets |
|
994 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
995 | ! |
id = "myplot", |
996 | ! |
plot_r = plot_r, |
997 | ! |
height = plot_height, |
998 | ! |
width = plot_width |
999 |
) |
|
1000 | ||
1001 | ! |
output$text <- renderText({ |
1002 | ! |
req(iv_r()$is_valid()) |
1003 | ! |
req(iv_out$is_valid()) |
1004 | ! |
paste(utils::capture.output(summary(teal.code::dev_suppress(fitted())))[-1], |
1005 | ! |
collapse = "\n" |
1006 |
) |
|
1007 |
}) |
|
1008 | ||
1009 | ! |
teal.widgets::verbatim_popup_srv( |
1010 | ! |
id = "rcode", |
1011 | ! |
verbatim_content = reactive(teal.code::get_code(req(decorated_output_q()))), |
1012 | ! |
title = "R code for the regression plot", |
1013 |
) |
|
1014 | ||
1015 |
### REPORTER |
|
1016 | ! |
if (with_reporter) { |
1017 | ! |
card_fun <- function(comment, label) { |
1018 | ! |
card <- teal::report_card_template( |
1019 | ! |
title = "Linear Regression Plot", |
1020 | ! |
label = label, |
1021 | ! |
with_filter = with_filter, |
1022 | ! |
filter_panel_api = filter_panel_api |
1023 |
) |
|
1024 | ! |
card$append_text("Plot", "header3") |
1025 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
1026 | ! |
if (!comment == "") { |
1027 | ! |
card$append_text("Comment", "header3") |
1028 | ! |
card$append_text(comment) |
1029 |
} |
|
1030 | ! |
card$append_src(teal.code::get_code(req(decorated_output_q()))) |
1031 | ! |
card |
1032 |
} |
|
1033 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
1034 |
} |
|
1035 |
### |
|
1036 |
}) |
|
1037 |
} |
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 |
#' @param decorators `r roxygen_decorators_param("tm_missing_data")` |
|
18 |
#' |
|
19 |
#' @inherit shared_params return |
|
20 |
#' |
|
21 |
#' @section Decorating `tm_missing_data`: |
|
22 |
#' |
|
23 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
24 |
#' - `summary_plot` (`grob` created with [ggplot2::ggplotGrob()]) |
|
25 |
#' - `combination_plot` (`grob` created with [ggplot2::ggplotGrob()]) |
|
26 |
#' - `by_subject_plot` (`ggplot2`) |
|
27 |
#' - `table` ([DT::datatable()]) |
|
28 |
#' |
|
29 |
#' Decorators can be applied to all outputs or only to specific objects using a |
|
30 |
#' named list of `teal_transform_module` objects. |
|
31 |
#' The `"default"` name is reserved for decorators that are applied to all outputs. |
|
32 |
#' See code snippet below: |
|
33 |
#' |
|
34 |
#' ``` |
|
35 |
#' tm_missing_data( |
|
36 |
#' ..., # arguments for module |
|
37 |
#' decorators = list( |
|
38 |
#' default = list(teal_transform_module(...)), # applied to all outputs |
|
39 |
#' summary_plot = list(teal_transform_module(...)), # applied only to `summary_plot` output |
|
40 |
#' combination_plot = list(teal_transform_module(...)) # applied only to `combination_plot` output |
|
41 |
#' by_subject_plot = list(teal_transform_module(...)) # applied only to `by_subject_plot` output |
|
42 |
#' table = list(teal_transform_module(...)) # applied only to `table` output |
|
43 |
#' ) |
|
44 |
#' ) |
|
45 |
#' ``` |
|
46 |
#' |
|
47 |
#' For additional details and examples of decorators, refer to the vignette |
|
48 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
49 |
#' |
|
50 |
#' @examplesShinylive |
|
51 |
#' library(teal.modules.general) |
|
52 |
#' interactive <- function() TRUE |
|
53 |
#' {{ next_example }} |
|
54 |
#' @examplesIf require("gridExtra", quietly = TRUE) && require("rlang", quietly = TRUE) |
|
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() |
|
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 |
#' @examplesIf require("gridExtra", quietly = TRUE) && require("rlang", quietly = TRUE) |
|
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 |
parent_dataname = "ADSL", |
|
114 |
ggtheme = c("classic", "gray", "bw", "linedraw", "light", "dark", "minimal", "void"), |
|
115 |
ggplot2_args = list( |
|
116 |
"Combinations Hist" = teal.widgets::ggplot2_args(labs = list(caption = NULL)), |
|
117 |
"Combinations Main" = teal.widgets::ggplot2_args(labs = list(title = NULL)) |
|
118 |
), |
|
119 |
pre_output = NULL, |
|
120 |
post_output = NULL, |
|
121 |
decorators = NULL) { |
|
122 | ! |
message("Initializing tm_missing_data") |
123 | ||
124 |
# Requires Suggested packages |
|
125 | ! |
if (!requireNamespace("gridExtra", quietly = TRUE)) { |
126 | ! |
stop("Cannot load gridExtra - please install the package or restart your session.") |
127 |
} |
|
128 | ! |
if (!requireNamespace("rlang", quietly = TRUE)) { |
129 | ! |
stop("Cannot load rlang - please install the package or restart your session.") |
130 |
} |
|
131 | ||
132 |
# Normalize the parameters |
|
133 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
134 | ||
135 |
# Start of assertions |
|
136 | ! |
checkmate::assert_string(label) |
137 | ||
138 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
139 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
140 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
141 | ! |
checkmate::assert_numeric( |
142 | ! |
plot_width[1], |
143 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
144 |
) |
|
145 | ||
146 | ! |
checkmate::assert_character(parent_dataname, min.len = 0, max.len = 1) |
147 | ! |
ggtheme <- match.arg(ggtheme) |
148 | ||
149 | ! |
plot_choices <- c("Summary Obs", "Summary Patients", "Combinations Main", "Combinations Hist", "By Subject") |
150 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
151 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
152 | ||
153 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
154 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
155 | ||
156 | ! |
available_decorators <- c("summary_plot", "combination_plot", "by_subject_plot", "summary_table") |
157 | ! |
decorators <- normalize_decorators(decorators) |
158 | ! |
assert_decorators(decorators, null.ok = TRUE, names = available_decorators) |
159 |
# End of assertions |
|
160 | ||
161 | ! |
ans <- module( |
162 | ! |
label, |
163 | ! |
server = srv_page_missing_data, |
164 | ! |
server_args = list( |
165 | ! |
parent_dataname = parent_dataname, |
166 | ! |
plot_height = plot_height, |
167 | ! |
plot_width = plot_width, |
168 | ! |
ggplot2_args = ggplot2_args, |
169 | ! |
ggtheme = ggtheme, |
170 | ! |
decorators = decorators |
171 |
), |
|
172 | ! |
ui = ui_page_missing_data, |
173 | ! |
datanames = "all", |
174 | ! |
ui_args = list(pre_output = pre_output, post_output = post_output) |
175 |
) |
|
176 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
177 | ! |
ans |
178 |
} |
|
179 | ||
180 |
# UI function for the missing data module (all datasets) |
|
181 |
ui_page_missing_data <- function(id, pre_output = NULL, post_output = NULL) { |
|
182 | ! |
ns <- NS(id) |
183 | ! |
tagList( |
184 | ! |
include_css_files("custom"), |
185 | ! |
teal.widgets::standard_layout( |
186 | ! |
output = teal.widgets::white_small_well( |
187 | ! |
tags$div( |
188 | ! |
class = "flex", |
189 | ! |
column( |
190 | ! |
width = 12, |
191 | ! |
uiOutput(ns("dataset_tabs")) |
192 |
) |
|
193 |
) |
|
194 |
), |
|
195 | ! |
encoding = tags$div( |
196 | ! |
uiOutput(ns("dataset_encodings")) |
197 |
), |
|
198 | ! |
uiOutput(ns("dataset_reporter")), |
199 | ! |
pre_output = pre_output, |
200 | ! |
post_output = post_output |
201 |
) |
|
202 |
) |
|
203 |
} |
|
204 | ||
205 |
# Server function for the missing data module (all datasets) |
|
206 |
srv_page_missing_data <- function(id, data, reporter, filter_panel_api, parent_dataname, |
|
207 |
plot_height, plot_width, ggplot2_args, ggtheme, decorators) { |
|
208 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
209 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
210 | ! |
moduleServer(id, function(input, output, session) { |
211 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
212 | ||
213 | ! |
datanames <- isolate(names(data())) |
214 | ! |
datanames <- Filter( |
215 | ! |
function(name) is.data.frame(isolate(data())[[name]]), |
216 | ! |
datanames |
217 |
) |
|
218 | ! |
if_subject_plot <- length(parent_dataname) > 0 && parent_dataname %in% datanames |
219 | ||
220 | ! |
ns <- session$ns |
221 | ||
222 | ! |
output$dataset_tabs <- renderUI({ |
223 | ! |
do.call( |
224 | ! |
tabsetPanel, |
225 | ! |
c( |
226 | ! |
id = ns("dataname_tab"), |
227 | ! |
lapply( |
228 | ! |
datanames, |
229 | ! |
function(x) { |
230 | ! |
tabPanel( |
231 | ! |
title = x, |
232 | ! |
column( |
233 | ! |
width = 12, |
234 | ! |
tags$div( |
235 | ! |
class = "mt-4", |
236 | ! |
ui_missing_data(id = ns(x), by_subject_plot = if_subject_plot) |
237 |
) |
|
238 |
) |
|
239 |
) |
|
240 |
} |
|
241 |
) |
|
242 |
) |
|
243 |
) |
|
244 |
}) |
|
245 | ||
246 | ! |
output$dataset_encodings <- renderUI({ |
247 | ! |
tagList( |
248 | ! |
lapply( |
249 | ! |
datanames, |
250 | ! |
function(x) { |
251 | ! |
conditionalPanel( |
252 | ! |
is_tab_active_js(ns("dataname_tab"), x), |
253 | ! |
encoding_missing_data( |
254 | ! |
id = ns(x), |
255 | ! |
summary_per_patient = if_subject_plot, |
256 | ! |
ggtheme = ggtheme, |
257 | ! |
datanames = datanames, |
258 | ! |
decorators = decorators |
259 |
) |
|
260 |
) |
|
261 |
} |
|
262 |
) |
|
263 |
) |
|
264 |
}) |
|
265 | ||
266 | ! |
output$dataset_reporter <- renderUI({ |
267 | ! |
lapply(datanames, function(x) { |
268 | ! |
dataname_ns <- NS(ns(x)) |
269 | ||
270 | ! |
conditionalPanel( |
271 | ! |
is_tab_active_js(ns("dataname_tab"), x), |
272 | ! |
tagList( |
273 | ! |
teal.widgets::verbatim_popup_ui(dataname_ns("rcode"), "Show R code") |
274 |
) |
|
275 |
) |
|
276 |
}) |
|
277 |
}) |
|
278 | ||
279 | ! |
lapply( |
280 | ! |
datanames, |
281 | ! |
function(x) { |
282 | ! |
srv_missing_data( |
283 | ! |
id = x, |
284 | ! |
data = data, |
285 | ! |
reporter = if (with_reporter) reporter, |
286 | ! |
filter_panel_api = if (with_filter) filter_panel_api, |
287 | ! |
dataname = x, |
288 | ! |
parent_dataname = parent_dataname, |
289 | ! |
plot_height = plot_height, |
290 | ! |
plot_width = plot_width, |
291 | ! |
ggplot2_args = ggplot2_args, |
292 | ! |
decorators = decorators |
293 |
) |
|
294 |
} |
|
295 |
) |
|
296 |
}) |
|
297 |
} |
|
298 | ||
299 |
# UI function for the missing data module (single dataset) |
|
300 |
ui_missing_data <- function(id, by_subject_plot = FALSE) { |
|
301 | ! |
ns <- NS(id) |
302 | ||
303 | ! |
tab_list <- list( |
304 | ! |
tabPanel( |
305 | ! |
"Summary", |
306 | ! |
teal.widgets::plot_with_settings_ui(id = ns("summary_plot")), |
307 | ! |
helpText( |
308 | ! |
tags$p(paste( |
309 | ! |
'The "Summary" graph shows the number of missing values per variable (both absolute and percentage),', |
310 | ! |
"sorted by magnitude." |
311 |
)), |
|
312 | ! |
tags$p( |
313 | ! |
'The "summary per patients" graph is showing how many subjects have at least one missing observation', |
314 | ! |
"for each variable. It will be most useful for panel datasets." |
315 |
) |
|
316 |
) |
|
317 |
), |
|
318 | ! |
tabPanel( |
319 | ! |
"Combinations", |
320 | ! |
teal.widgets::plot_with_settings_ui(id = ns("combination_plot")), |
321 | ! |
helpText( |
322 | ! |
tags$p(paste( |
323 | ! |
'The "Combinations" graph is used to explore the relationship between the missing data within', |
324 | ! |
"different columns of the dataset.", |
325 | ! |
"It shows the different patterns of missingness in the rows of the data.", |
326 | ! |
'For example, suppose that 70 rows of the data have exactly columns "A" and "B" missing.', |
327 | ! |
"In this case there would be a bar of height 70 in the top graph and", |
328 | ! |
'the column below this in the second graph would have rows "A" and "B" cells shaded red.' |
329 |
)), |
|
330 | ! |
tags$p(paste( |
331 | ! |
"Due to the large number of missing data patterns possible, only those with a large set of observations", |
332 | ! |
'are shown in the graph and the "Combination cut-off" slider can be used to adjust the number shown.' |
333 |
)) |
|
334 |
) |
|
335 |
), |
|
336 | ! |
tabPanel( |
337 | ! |
"By Variable Levels", |
338 | ! |
teal.widgets::get_dt_rows(ns("levels_table"), ns("levels_table_rows")), |
339 | ! |
DT::dataTableOutput(ns("levels_table")) |
340 |
) |
|
341 |
) |
|
342 | ! |
if (isTRUE(by_subject_plot)) { |
343 | ! |
tab_list <- append( |
344 | ! |
tab_list, |
345 | ! |
list(tabPanel( |
346 | ! |
"Grouped by Subject", |
347 | ! |
teal.widgets::plot_with_settings_ui(id = ns("by_subject_plot")), |
348 | ! |
helpText( |
349 | ! |
tags$p(paste( |
350 | ! |
"This graph shows the missingness with respect to subjects rather than individual rows of the", |
351 | ! |
"dataset. Each row represents one dataset variable and each column a single subject. Only subjects", |
352 | ! |
"with at least one record in this dataset are shown. For a given subject, if they have any missing", |
353 | ! |
"values of a specific variable then the appropriate cell in the graph is marked as missing." |
354 |
)) |
|
355 |
) |
|
356 |
)) |
|
357 |
) |
|
358 |
} |
|
359 | ||
360 | ! |
do.call( |
361 | ! |
tabsetPanel, |
362 | ! |
c( |
363 | ! |
id = ns("summary_type"), |
364 | ! |
tab_list |
365 |
) |
|
366 |
) |
|
367 |
} |
|
368 | ||
369 |
# UI encoding for the missing data module (all datasets) |
|
370 |
encoding_missing_data <- function(id, summary_per_patient = FALSE, ggtheme, datanames, decorators) { |
|
371 | ! |
ns <- NS(id) |
372 | ||
373 | ! |
tagList( |
374 |
### Reporter |
|
375 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
376 |
### |
|
377 | ! |
tags$label("Encodings", class = "text-primary"), |
378 | ! |
helpText( |
379 | ! |
paste0("Dataset", `if`(length(datanames) > 1, "s", ""), ":"), |
380 | ! |
tags$code(paste(datanames, collapse = ", ")) |
381 |
), |
|
382 | ! |
uiOutput(ns("variables")), |
383 | ! |
actionButton( |
384 | ! |
ns("filter_na"), |
385 | ! |
tags$span("Select only vars with missings", class = "whitespace-normal"), |
386 | ! |
width = "100%", |
387 | ! |
class = "mb-4" |
388 |
), |
|
389 | ! |
conditionalPanel( |
390 | ! |
is_tab_active_js(ns("summary_type"), "Summary"), |
391 | ! |
checkboxInput( |
392 | ! |
ns("any_na"), |
393 | ! |
tags$div( |
394 | ! |
class = "teal-tooltip", |
395 | ! |
tagList( |
396 | ! |
"Add **anyna** variable", |
397 | ! |
icon("circle-info"), |
398 | ! |
tags$span( |
399 | ! |
class = "tooltiptext", |
400 | ! |
"Describes the number of observations with at least one missing value in any variable." |
401 |
) |
|
402 |
) |
|
403 |
), |
|
404 | ! |
value = FALSE |
405 |
), |
|
406 | ! |
if (summary_per_patient) { |
407 | ! |
checkboxInput( |
408 | ! |
ns("if_patients_plot"), |
409 | ! |
tags$div( |
410 | ! |
class = "teal-tooltip", |
411 | ! |
tagList( |
412 | ! |
"Add summary per patients", |
413 | ! |
icon("circle-info"), |
414 | ! |
tags$span( |
415 | ! |
class = "tooltiptext", |
416 | ! |
paste( |
417 | ! |
"Displays the number of missing values per observation,", |
418 | ! |
"where the x-axis is sorted by observation appearance in the table." |
419 |
) |
|
420 |
) |
|
421 |
) |
|
422 |
), |
|
423 | ! |
value = FALSE |
424 |
) |
|
425 |
}, |
|
426 | ! |
ui_decorate_teal_data(ns("dec_summary_plot"), decorators = select_decorators(decorators, "summary_plot")) |
427 |
), |
|
428 | ! |
conditionalPanel( |
429 | ! |
is_tab_active_js(ns("summary_type"), "Combinations"), |
430 | ! |
uiOutput(ns("cutoff")), |
431 | ! |
ui_decorate_teal_data(ns("dec_combination_plot"), decorators = select_decorators(decorators, "combination_plot")) |
432 |
), |
|
433 | ! |
conditionalPanel( |
434 | ! |
is_tab_active_js(ns("summary_type"), "Grouped by Subject"), |
435 | ! |
ui_decorate_teal_data(ns("dec_by_subject_plot"), decorators = select_decorators(decorators, "by_subject_plot")) |
436 |
), |
|
437 | ! |
conditionalPanel( |
438 | ! |
is_tab_active_js(ns("summary_type"), "By Variable Levels"), |
439 | ! |
uiOutput(ns("group_by_var_ui")), |
440 | ! |
uiOutput(ns("group_by_vals_ui")), |
441 | ! |
radioButtons( |
442 | ! |
ns("count_type"), |
443 | ! |
label = "Display missing as", |
444 | ! |
choices = c("counts", "proportions"), |
445 | ! |
selected = "counts", |
446 | ! |
inline = TRUE |
447 |
), |
|
448 | ! |
ui_decorate_teal_data(ns("dec_summary_table"), decorators = select_decorators(decorators, "summary_table")) |
449 |
), |
|
450 | ! |
teal.widgets::panel_item( |
451 | ! |
title = "Plot settings", |
452 | ! |
selectInput( |
453 | ! |
inputId = ns("ggtheme"), |
454 | ! |
label = "Theme (by ggplot):", |
455 | ! |
choices = ggplot_themes, |
456 | ! |
selected = ggtheme, |
457 | ! |
multiple = FALSE |
458 |
) |
|
459 |
) |
|
460 |
) |
|
461 |
} |
|
462 | ||
463 |
# Server function for the missing data (single dataset) |
|
464 |
srv_missing_data <- function(id, |
|
465 |
data, |
|
466 |
reporter, |
|
467 |
filter_panel_api, |
|
468 |
dataname, |
|
469 |
parent_dataname, |
|
470 |
plot_height, |
|
471 |
plot_width, |
|
472 |
ggplot2_args, |
|
473 |
decorators) { |
|
474 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
475 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
476 | ! |
checkmate::assert_class(data, "reactive") |
477 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
478 | ! |
moduleServer(id, function(input, output, session) { |
479 | ! |
ns <- session$ns |
480 | ||
481 | ! |
prev_group_by_var <- reactiveVal("") |
482 | ! |
data_r <- reactive(data()[[dataname]]) |
483 | ! |
data_keys <- reactive(unlist(teal.data::join_keys(data())[[dataname]])) |
484 | ||
485 | ! |
iv_r <- reactive({ |
486 | ! |
iv <- shinyvalidate::InputValidator$new() |
487 | ! |
iv$add_rule( |
488 | ! |
"variables_select", |
489 | ! |
shinyvalidate::sv_required("At least one reference variable needs to be selected.") |
490 |
) |
|
491 | ! |
iv$add_rule( |
492 | ! |
"variables_select", |
493 | ! |
~ if (length(setdiff((.), data_keys())) < 1) "Please also select non-key columns." |
494 |
) |
|
495 | ! |
iv_summary_table <- shinyvalidate::InputValidator$new() |
496 | ! |
iv_summary_table$condition(~ isTRUE(input$summary_type == "By Variable Levels")) |
497 | ! |
iv_summary_table$add_rule("count_type", shinyvalidate::sv_required("Please select type of counts")) |
498 | ! |
iv_summary_table$add_rule( |
499 | ! |
"group_by_vals", |
500 | ! |
shinyvalidate::sv_required("Please select both group-by variable and values") |
501 |
) |
|
502 | ! |
iv_summary_table$add_rule( |
503 | ! |
"group_by_var", |
504 | ! |
~ if (length(.) > 0 && length(input$variables_select) == 1 && (.) == input$variables_select) { |
505 | ! |
"If only one reference variable is selected it must not be the grouping variable." |
506 |
} |
|
507 |
) |
|
508 | ! |
iv_summary_table$add_rule( |
509 | ! |
"variables_select", |
510 | ! |
~ if (length(input$group_by_var) > 0 && length(.) == 1 && (.) == input$group_by_var) { |
511 | ! |
"If only one reference variable is selected it must not be the grouping variable." |
512 |
} |
|
513 |
) |
|
514 | ! |
iv$add_validator(iv_summary_table) |
515 | ! |
iv$enable() |
516 | ! |
iv |
517 |
}) |
|
518 | ||
519 | ! |
data_parent_keys <- reactive({ |
520 | ! |
if (length(parent_dataname) > 0 && parent_dataname %in% names(data())) { |
521 | ! |
keys <- teal.data::join_keys(data())[[dataname]] |
522 | ! |
if (parent_dataname %in% names(keys)) { |
523 | ! |
keys[[parent_dataname]] |
524 |
} else { |
|
525 | ! |
keys[[dataname]] |
526 |
} |
|
527 |
} else { |
|
528 | ! |
NULL |
529 |
} |
|
530 |
}) |
|
531 | ||
532 | ! |
common_code_q <- reactive({ |
533 | ! |
teal::validate_inputs(iv_r()) |
534 | ||
535 | ! |
group_var <- input$group_by_var |
536 | ! |
anl <- data_r() |
537 | ||
538 | ! |
qenv <- if (!is.null(selected_vars()) && length(selected_vars()) != ncol(anl)) { |
539 | ! |
teal.code::eval_code( |
540 | ! |
data(), |
541 | ! |
substitute( |
542 | ! |
expr = ANL <- anl_name[, selected_vars, drop = FALSE], |
543 | ! |
env = list(anl_name = as.name(dataname), selected_vars = selected_vars()) |
544 |
) |
|
545 |
) |
|
546 |
} else { |
|
547 | ! |
teal.code::eval_code( |
548 | ! |
data(), |
549 | ! |
substitute(expr = ANL <- anl_name, env = list(anl_name = as.name(dataname))) |
550 |
) |
|
551 |
} |
|
552 | ||
553 | ! |
if (input$summary_type == "By Variable Levels" && !is.null(group_var) && !(group_var %in% selected_vars())) { |
554 | ! |
qenv <- teal.code::eval_code( |
555 | ! |
qenv, |
556 | ! |
substitute( |
557 | ! |
expr = ANL[[group_var]] <- anl_name[[group_var]], |
558 | ! |
env = list(group_var = group_var, anl_name = as.name(dataname)) |
559 |
) |
|
560 |
) |
|
561 |
} |
|
562 | ||
563 | ! |
new_col_name <- "**anyna**" |
564 | ||
565 | ! |
qenv <- teal.code::eval_code( |
566 | ! |
qenv, |
567 | ! |
substitute( |
568 | ! |
expr = |
569 | ! |
create_cols_labels <- function(cols, just_label = FALSE) { |
570 | ! |
column_labels <- column_labels_value |
571 | ! |
column_labels[is.na(column_labels) | length(column_labels) == 0] <- "" |
572 | ! |
if (just_label) { |
573 | ! |
labels <- column_labels[cols] |
574 |
} else { |
|
575 | ! |
labels <- ifelse(cols == new_col_name | cols == "", cols, paste0(column_labels[cols], " [", cols, "]")) |
576 |
} |
|
577 | ! |
labels |
578 |
}, |
|
579 | ! |
env = list( |
580 | ! |
new_col_name = new_col_name, |
581 | ! |
column_labels_value = c(teal.data::col_labels(data_r())[selected_vars()], |
582 | ! |
new_col_name = new_col_name |
583 |
) |
|
584 |
) |
|
585 |
) |
|
586 |
) |
|
587 | ! |
qenv |
588 |
}) |
|
589 | ||
590 | ! |
selected_vars <- reactive({ |
591 | ! |
req(input$variables_select) |
592 | ! |
keys <- data_keys() |
593 | ! |
vars <- unique(c(keys, input$variables_select)) |
594 | ! |
vars |
595 |
}) |
|
596 | ||
597 | ! |
vars_summary <- reactive({ |
598 | ! |
na_count <- data_r() %>% |
599 | ! |
sapply(function(x) mean(is.na(x)), USE.NAMES = TRUE) %>% |
600 | ! |
sort(decreasing = TRUE) |
601 | ||
602 | ! |
tibble::tibble( |
603 | ! |
key = names(na_count), |
604 | ! |
value = unname(na_count), |
605 | ! |
label = cut(na_count, breaks = seq(from = 0, to = 1, by = 0.1), include.lowest = TRUE) |
606 |
) |
|
607 |
}) |
|
608 | ||
609 |
# Keep encoding panel up-to-date |
|
610 | ! |
output$variables <- renderUI({ |
611 | ! |
choices <- split(x = vars_summary()$key, f = vars_summary()$label, drop = TRUE) %>% rev() |
612 | ! |
selected <- choices <- unname(unlist(choices)) |
613 | ||
614 | ! |
teal.widgets::optionalSelectInput( |
615 | ! |
ns("variables_select"), |
616 | ! |
label = "Select variables", |
617 | ! |
label_help = HTML(paste0("Dataset: ", tags$code(dataname))), |
618 | ! |
choices = teal.transform::variable_choices(data_r(), choices), |
619 | ! |
selected = selected, |
620 | ! |
multiple = TRUE |
621 |
) |
|
622 |
}) |
|
623 | ||
624 | ! |
observeEvent(input$filter_na, { |
625 | ! |
choices <- vars_summary() %>% |
626 | ! |
dplyr::select(!!as.name("key")) %>% |
627 | ! |
getElement(name = 1) |
628 | ||
629 | ! |
selected <- vars_summary() %>% |
630 | ! |
dplyr::filter(!!as.name("value") > 0) %>% |
631 | ! |
dplyr::select(!!as.name("key")) %>% |
632 | ! |
getElement(name = 1) |
633 | ||
634 | ! |
teal.widgets::updateOptionalSelectInput( |
635 | ! |
session = session, |
636 | ! |
inputId = "variables_select", |
637 | ! |
choices = teal.transform::variable_choices(data_r()), |
638 | ! |
selected = restoreInput(ns("variables_select"), selected) |
639 |
) |
|
640 |
}) |
|
641 | ||
642 | ! |
output$group_by_var_ui <- renderUI({ |
643 | ! |
all_choices <- teal.transform::variable_choices(data_r()) |
644 | ! |
cat_choices <- all_choices[!sapply(data_r(), function(x) is.numeric(x) || inherits(x, "POSIXct"))] |
645 | ! |
validate( |
646 | ! |
need(cat_choices, "Dataset does not have any non-numeric or non-datetime variables to use to group data with") |
647 |
) |
|
648 | ! |
teal.widgets::optionalSelectInput( |
649 | ! |
ns("group_by_var"), |
650 | ! |
label = "Group by variable", |
651 | ! |
choices = cat_choices, |
652 | ! |
selected = `if`( |
653 | ! |
is.null(isolate(input$group_by_var)), |
654 | ! |
cat_choices[1], |
655 | ! |
isolate(input$group_by_var) |
656 |
), |
|
657 | ! |
multiple = FALSE, |
658 | ! |
label_help = paste0("Dataset: ", dataname) |
659 |
) |
|
660 |
}) |
|
661 | ||
662 | ! |
output$group_by_vals_ui <- renderUI({ |
663 | ! |
req(input$group_by_var) |
664 | ||
665 | ! |
choices <- teal.transform::value_choices(data_r(), input$group_by_var, input$group_by_var) |
666 | ! |
prev_choices <- isolate(input$group_by_vals) |
667 | ||
668 |
# determine selected value based on filtered data |
|
669 |
# display those previously selected values that are still available |
|
670 | ! |
selected <- if (!is.null(prev_choices) && any(prev_choices %in% choices)) { |
671 | ! |
prev_choices[match(choices[choices %in% prev_choices], prev_choices)] |
672 | ! |
} else if ( |
673 | ! |
!is.null(prev_choices) && |
674 | ! |
!any(prev_choices %in% choices) && |
675 | ! |
isolate(prev_group_by_var()) == input$group_by_var |
676 |
) { |
|
677 |
# if not any previously selected value is available and the grouping variable is the same, |
|
678 |
# then display NULL |
|
679 | ! |
NULL |
680 |
} else { |
|
681 |
# if new grouping variable (i.e. not any previously selected value is available), |
|
682 |
# then display all choices |
|
683 | ! |
choices |
684 |
} |
|
685 | ||
686 | ! |
prev_group_by_var(input$group_by_var) # set current group_by_var |
687 | ! |
validate(need(length(choices) < 100, "Please select group-by variable with fewer than 100 unique values")) |
688 | ! |
teal.widgets::optionalSelectInput( |
689 | ! |
ns("group_by_vals"), |
690 | ! |
label = "Filter levels", |
691 | ! |
choices = choices, |
692 | ! |
selected = selected, |
693 | ! |
multiple = TRUE, |
694 | ! |
label_help = paste0("Dataset: ", dataname) |
695 |
) |
|
696 |
}) |
|
697 | ||
698 | ! |
combination_cutoff_q <- reactive({ |
699 | ! |
req(common_code_q()) |
700 | ! |
teal.code::eval_code( |
701 | ! |
common_code_q(), |
702 | ! |
quote( |
703 | ! |
combination_cutoff <- ANL %>% |
704 | ! |
dplyr::mutate_all(is.na) %>% |
705 | ! |
dplyr::group_by_all() %>% |
706 | ! |
dplyr::tally() %>% |
707 | ! |
dplyr::ungroup() |
708 |
) |
|
709 |
) |
|
710 |
}) |
|
711 | ||
712 | ! |
output$cutoff <- renderUI({ |
713 | ! |
x <- combination_cutoff_q()[["combination_cutoff"]]$n |
714 | ||
715 |
# select 10-th from the top |
|
716 | ! |
n <- length(x) |
717 | ! |
idx <- max(1, n - 10) |
718 | ! |
prev_value <- isolate(input$combination_cutoff) |
719 | ! |
value <- if (is.null(prev_value) || prev_value > max(x) || prev_value < min(x)) { |
720 | ! |
sort(x, partial = idx)[idx] |
721 |
} else { |
|
722 | ! |
prev_value |
723 |
} |
|
724 | ||
725 | ! |
teal.widgets::optionalSliderInputValMinMax( |
726 | ! |
ns("combination_cutoff"), |
727 | ! |
"Combination cut-off", |
728 | ! |
c(value, range(x)) |
729 |
) |
|
730 |
}) |
|
731 | ||
732 |
# Prepare qenvs for output objects |
|
733 | ||
734 | ! |
summary_plot_q <- reactive({ |
735 | ! |
req(input$summary_type == "Summary") # needed to trigger show r code update on tab change |
736 | ! |
teal::validate_has_data(data_r(), 1) |
737 | ||
738 | ! |
qenv <- common_code_q() |
739 | ! |
if (input$any_na) { |
740 | ! |
new_col_name <- "**anyna**" |
741 | ! |
qenv <- teal.code::eval_code( |
742 | ! |
qenv, |
743 | ! |
substitute( |
744 | ! |
expr = ANL[[new_col_name]] <- ifelse(rowSums(is.na(ANL)) > 0, NA, FALSE), |
745 | ! |
env = list(new_col_name = new_col_name) |
746 |
) |
|
747 |
) |
|
748 |
} |
|
749 | ||
750 | ! |
qenv <- teal.code::eval_code( |
751 | ! |
qenv, |
752 | ! |
substitute( |
753 | ! |
expr = analysis_vars <- setdiff(colnames(ANL), data_keys), |
754 | ! |
env = list(data_keys = data_keys()) |
755 |
) |
|
756 |
) %>% |
|
757 | ! |
teal.code::eval_code( |
758 | ! |
substitute( |
759 | ! |
expr = summary_plot_obs <- data_frame_call[, analysis_vars] %>% |
760 | ! |
dplyr::summarise_all(list(function(x) sum(is.na(x)))) %>% |
761 | ! |
tidyr::pivot_longer(dplyr::everything(), names_to = "col", values_to = "n_na") %>% |
762 | ! |
dplyr::mutate(n_not_na = nrow(ANL) - n_na) %>% |
763 | ! |
tidyr::pivot_longer(-col, names_to = "isna", values_to = "n") %>% |
764 | ! |
dplyr::mutate(isna = isna == "n_na", n_pct = n / nrow(ANL) * 100), |
765 | ! |
env = list(data_frame_call = if (!inherits(data_r(), "tbl_df")) { |
766 | ! |
quote(tibble::as_tibble(ANL)) |
767 |
} else { |
|
768 | ! |
quote(ANL) |
769 |
}) |
|
770 |
) |
|
771 |
) %>% |
|
772 |
# x axis ordering according to number of missing values and alphabet |
|
773 | ! |
teal.code::eval_code( |
774 | ! |
quote( |
775 | ! |
expr = x_levels <- dplyr::filter(summary_plot_obs, isna) %>% |
776 | ! |
dplyr::arrange(n_pct, dplyr::desc(col)) %>% |
777 | ! |
dplyr::pull(col) %>% |
778 | ! |
create_cols_labels() |
779 |
) |
|
780 |
) |
|
781 | ||
782 |
# always set "**anyna**" level as the last one |
|
783 | ! |
if (isolate(input$any_na)) { |
784 | ! |
qenv <- teal.code::eval_code( |
785 | ! |
qenv, |
786 | ! |
quote(x_levels <- c(setdiff(x_levels, "**anyna**"), "**anyna**")) |
787 |
) |
|
788 |
} |
|
789 | ||
790 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
791 | ! |
labs = list(x = "Variable", y = "Missing observations"), |
792 | ! |
theme = list(legend.position = "bottom", axis.text.x = quote(element_text(angle = 45, hjust = 1))) |
793 |
) |
|
794 | ||
795 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
796 | ! |
user_plot = ggplot2_args[["Summary Obs"]], |
797 | ! |
user_default = ggplot2_args$default, |
798 | ! |
module_plot = dev_ggplot2_args |
799 |
) |
|
800 | ||
801 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
802 | ! |
all_ggplot2_args, |
803 | ! |
ggtheme = input$ggtheme |
804 |
) |
|
805 | ||
806 | ! |
qenv <- teal.code::eval_code( |
807 | ! |
qenv, |
808 | ! |
substitute( |
809 | ! |
summary_plot_top <- summary_plot_obs %>% |
810 | ! |
ggplot() + |
811 | ! |
aes( |
812 | ! |
x = factor(create_cols_labels(col), levels = x_levels), |
813 | ! |
y = n_pct, |
814 | ! |
fill = isna |
815 |
) + |
|
816 | ! |
geom_bar(position = "fill", stat = "identity") + |
817 | ! |
scale_fill_manual( |
818 | ! |
name = "", |
819 | ! |
values = c("grey90", c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]), |
820 | ! |
labels = c("Present", "Missing") |
821 |
) + |
|
822 | ! |
scale_y_continuous( |
823 | ! |
labels = scales::percent_format(), |
824 | ! |
breaks = seq(0, 1, by = 0.1), |
825 | ! |
expand = c(0, 0) |
826 |
) + |
|
827 | ! |
geom_text( |
828 | ! |
aes(label = ifelse(isna == TRUE, sprintf("%d [%.02f%%]", n, n_pct), ""), y = 1), |
829 | ! |
hjust = 1, |
830 | ! |
color = "black" |
831 |
) + |
|
832 | ! |
labs + |
833 | ! |
ggthemes + |
834 | ! |
themes + |
835 | ! |
coord_flip(), |
836 | ! |
env = list( |
837 | ! |
labs = parsed_ggplot2_args$labs, |
838 | ! |
themes = parsed_ggplot2_args$theme, |
839 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
840 |
) |
|
841 |
) |
|
842 |
) |
|
843 | ||
844 | ! |
if (isTRUE(input$if_patients_plot)) { |
845 | ! |
qenv <- teal.code::eval_code( |
846 | ! |
qenv, |
847 | ! |
substitute( |
848 | ! |
expr = parent_keys <- keys, |
849 | ! |
env = list(keys = data_parent_keys()) |
850 |
) |
|
851 |
) %>% |
|
852 | ! |
teal.code::eval_code(quote(ndistinct_subjects <- dplyr::n_distinct(ANL[, parent_keys]))) %>% |
853 | ! |
teal.code::eval_code( |
854 | ! |
quote( |
855 | ! |
summary_plot_patients <- ANL[, c(parent_keys, analysis_vars)] %>% |
856 | ! |
dplyr::group_by_at(parent_keys) %>% |
857 | ! |
dplyr::summarise_all(anyNA) %>% |
858 | ! |
tidyr::pivot_longer(cols = !dplyr::all_of(parent_keys), names_to = "col", values_to = "anyna") %>% |
859 | ! |
dplyr::group_by_at(c("col")) %>% |
860 | ! |
dplyr::summarise(count_na = sum(anyna)) %>% |
861 | ! |
dplyr::mutate(count_not_na = ndistinct_subjects - count_na) %>% |
862 | ! |
tidyr::pivot_longer(-c(col), names_to = "isna", values_to = "n") %>% |
863 | ! |
dplyr::mutate(isna = isna == "count_na", n_pct = n / ndistinct_subjects * 100) %>% |
864 | ! |
dplyr::arrange_at(c("isna", "n"), .funs = dplyr::desc) |
865 |
) |
|
866 |
) |
|
867 | ||
868 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
869 | ! |
labs = list(x = "", y = "Missing patients"), |
870 | ! |
theme = list( |
871 | ! |
legend.position = "bottom", |
872 | ! |
axis.text.x = quote(element_text(angle = 45, hjust = 1)), |
873 | ! |
axis.text.y = quote(element_blank()) |
874 |
) |
|
875 |
) |
|
876 | ||
877 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
878 | ! |
user_plot = ggplot2_args[["Summary Patients"]], |
879 | ! |
user_default = ggplot2_args$default, |
880 | ! |
module_plot = dev_ggplot2_args |
881 |
) |
|
882 | ||
883 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
884 | ! |
all_ggplot2_args, |
885 | ! |
ggtheme = input$ggtheme |
886 |
) |
|
887 | ||
888 | ! |
qenv <- teal.code::eval_code( |
889 | ! |
qenv, |
890 | ! |
substitute( |
891 | ! |
summary_plot_bottom <- summary_plot_patients %>% |
892 | ! |
ggplot() + |
893 | ! |
aes_( |
894 | ! |
x = ~ factor(create_cols_labels(col), levels = x_levels), |
895 | ! |
y = ~n_pct, |
896 | ! |
fill = ~isna |
897 |
) + |
|
898 | ! |
geom_bar(alpha = 1, stat = "identity", position = "fill") + |
899 | ! |
scale_y_continuous( |
900 | ! |
labels = scales::percent_format(), |
901 | ! |
breaks = seq(0, 1, by = 0.1), |
902 | ! |
expand = c(0, 0) |
903 |
) + |
|
904 | ! |
scale_fill_manual( |
905 | ! |
name = "", |
906 | ! |
values = c("grey90", c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]), |
907 | ! |
labels = c("Present", "Missing") |
908 |
) + |
|
909 | ! |
geom_text( |
910 | ! |
aes(label = ifelse(isna == TRUE, sprintf("%d [%.02f%%]", n, n_pct), ""), y = 1), |
911 | ! |
hjust = 1, |
912 | ! |
color = "black" |
913 |
) + |
|
914 | ! |
labs + |
915 | ! |
ggthemes + |
916 | ! |
themes + |
917 | ! |
coord_flip(), |
918 | ! |
env = list( |
919 | ! |
labs = parsed_ggplot2_args$labs, |
920 | ! |
themes = parsed_ggplot2_args$theme, |
921 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
922 |
) |
|
923 |
) |
|
924 |
) |
|
925 |
} |
|
926 | ||
927 | ! |
if (isTRUE(input$if_patients_plot)) { |
928 | ! |
within(qenv, { |
929 | ! |
g1 <- ggplotGrob(summary_plot_top) |
930 | ! |
g2 <- ggplotGrob(summary_plot_bottom) |
931 | ! |
summary_plot <- gridExtra::gtable_cbind(g1, g2, size = "first") |
932 | ! |
summary_plot$heights <- grid::unit.pmax(g1$heights, g2$heights) |
933 |
}) |
|
934 |
} else { |
|
935 | ! |
within(qenv, { |
936 | ! |
g1 <- ggplotGrob(summary_plot_top) |
937 | ! |
summary_plot <- g1 |
938 |
}) |
|
939 |
} |
|
940 |
}) |
|
941 | ||
942 | ! |
combination_plot_q <- reactive({ |
943 | ! |
req(input$summary_type == "Combinations", input$combination_cutoff, combination_cutoff_q()) |
944 | ! |
teal::validate_has_data(data_r(), 1) |
945 | ||
946 | ! |
qenv <- teal.code::eval_code( |
947 | ! |
combination_cutoff_q(), |
948 | ! |
substitute( |
949 | ! |
expr = data_combination_plot_cutoff <- combination_cutoff %>% |
950 | ! |
dplyr::filter(n >= combination_cutoff_value) %>% |
951 | ! |
dplyr::mutate(id = rank(-n, ties.method = "first")) %>% |
952 | ! |
tidyr::pivot_longer(-c(n, id), names_to = "key", values_to = "value") %>% |
953 | ! |
dplyr::arrange(n), |
954 | ! |
env = list(combination_cutoff_value = input$combination_cutoff) |
955 |
) |
|
956 |
) |
|
957 | ||
958 |
# find keys in dataset not selected in the UI and remove them from dataset |
|
959 | ! |
keys_not_selected <- setdiff(data_keys(), input$variables_select) |
960 | ! |
if (length(keys_not_selected) > 0) { |
961 | ! |
qenv <- teal.code::eval_code( |
962 | ! |
qenv, |
963 | ! |
substitute( |
964 | ! |
expr = data_combination_plot_cutoff <- data_combination_plot_cutoff %>% |
965 | ! |
dplyr::filter(!key %in% keys_not_selected), |
966 | ! |
env = list(keys_not_selected = keys_not_selected) |
967 |
) |
|
968 |
) |
|
969 |
} |
|
970 | ||
971 | ! |
qenv <- teal.code::eval_code( |
972 | ! |
qenv, |
973 | ! |
quote( |
974 | ! |
labels <- data_combination_plot_cutoff %>% |
975 | ! |
dplyr::filter(key == key[[1]]) %>% |
976 | ! |
getElement(name = 1) |
977 |
) |
|
978 |
) |
|
979 | ||
980 | ! |
dev_ggplot2_args1 <- teal.widgets::ggplot2_args( |
981 | ! |
labs = list(x = "", y = ""), |
982 | ! |
theme = list( |
983 | ! |
legend.position = "bottom", |
984 | ! |
axis.text.x = quote(element_blank()) |
985 |
) |
|
986 |
) |
|
987 | ||
988 | ! |
all_ggplot2_args1 <- teal.widgets::resolve_ggplot2_args( |
989 | ! |
user_plot = ggplot2_args[["Combinations Hist"]], |
990 | ! |
user_default = ggplot2_args$default, |
991 | ! |
module_plot = dev_ggplot2_args1 |
992 |
) |
|
993 | ||
994 | ! |
parsed_ggplot2_args1 <- teal.widgets::parse_ggplot2_args( |
995 | ! |
all_ggplot2_args1, |
996 | ! |
ggtheme = "void" |
997 |
) |
|
998 | ||
999 | ! |
dev_ggplot2_args2 <- teal.widgets::ggplot2_args( |
1000 | ! |
labs = list(x = "", y = ""), |
1001 | ! |
theme = list( |
1002 | ! |
legend.position = "bottom", |
1003 | ! |
axis.text.x = quote(element_blank()), |
1004 | ! |
axis.ticks = quote(element_blank()), |
1005 | ! |
panel.grid.major = quote(element_blank()) |
1006 |
) |
|
1007 |
) |
|
1008 | ||
1009 | ! |
all_ggplot2_args2 <- teal.widgets::resolve_ggplot2_args( |
1010 | ! |
user_plot = ggplot2_args[["Combinations Main"]], |
1011 | ! |
user_default = ggplot2_args$default, |
1012 | ! |
module_plot = dev_ggplot2_args2 |
1013 |
) |
|
1014 | ||
1015 | ! |
parsed_ggplot2_args2 <- teal.widgets::parse_ggplot2_args( |
1016 | ! |
all_ggplot2_args2, |
1017 | ! |
ggtheme = input$ggtheme |
1018 |
) |
|
1019 | ||
1020 | ! |
qenv <- teal.code::eval_code( |
1021 | ! |
qenv, |
1022 | ! |
substitute( |
1023 | ! |
expr = { |
1024 | ! |
combination_plot_top <- data_combination_plot_cutoff %>% |
1025 | ! |
dplyr::select(id, n) %>% |
1026 | ! |
dplyr::distinct() %>% |
1027 | ! |
ggplot(aes(x = id, y = n)) + |
1028 | ! |
geom_bar(stat = "identity", fill = c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]) + |
1029 | ! |
geom_text( |
1030 | ! |
aes(label = n), |
1031 | ! |
position = position_dodge(width = 0.9), |
1032 | ! |
vjust = -0.25 |
1033 |
) + |
|
1034 | ! |
ylim(c(0, max(data_combination_plot_cutoff$n) * 1.5)) + |
1035 | ! |
labs1 + |
1036 | ! |
ggthemes1 + |
1037 | ! |
themes1 |
1038 | ||
1039 | ! |
graph_number_rows <- length(unique(data_combination_plot_cutoff$id)) |
1040 | ! |
graph_number_cols <- nrow(data_combination_plot_cutoff) / graph_number_rows |
1041 | ||
1042 | ! |
combination_plot_bottom <- data_combination_plot_cutoff %>% ggplot() + |
1043 | ! |
aes(x = create_cols_labels(key), y = id - 0.5, fill = value) + |
1044 | ! |
geom_tile(alpha = 0.85, height = 0.95) + |
1045 | ! |
scale_fill_manual( |
1046 | ! |
name = "", |
1047 | ! |
values = c("grey90", c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]), |
1048 | ! |
labels = c("Present", "Missing") |
1049 |
) + |
|
1050 | ! |
geom_hline(yintercept = seq_len(1 + graph_number_rows) - 1) + |
1051 | ! |
geom_vline(xintercept = seq_len(1 + graph_number_cols) - 0.5, linetype = "dotted") + |
1052 | ! |
coord_flip() + |
1053 | ! |
labs2 + |
1054 | ! |
ggthemes2 + |
1055 | ! |
themes2 |
1056 |
}, |
|
1057 | ! |
env = list( |
1058 | ! |
labs1 = parsed_ggplot2_args1$labs, |
1059 | ! |
themes1 = parsed_ggplot2_args1$theme, |
1060 | ! |
ggthemes1 = parsed_ggplot2_args1$ggtheme, |
1061 | ! |
labs2 = parsed_ggplot2_args2$labs, |
1062 | ! |
themes2 = parsed_ggplot2_args2$theme, |
1063 | ! |
ggthemes2 = parsed_ggplot2_args2$ggtheme |
1064 |
) |
|
1065 |
) |
|
1066 |
) |
|
1067 | ||
1068 | ! |
within(qenv, { |
1069 | ! |
g1 <- ggplotGrob(combination_plot_top) |
1070 | ! |
g2 <- ggplotGrob(combination_plot_bottom) |
1071 | ||
1072 | ! |
combination_plot <- gridExtra::gtable_rbind(g1, g2, size = "last") |
1073 | ! |
combination_plot$heights[7] <- grid::unit(0.2, "null") # rescale to get the bar chart smaller |
1074 |
}) |
|
1075 |
}) |
|
1076 | ||
1077 | ! |
summary_table_q <- reactive({ |
1078 | ! |
req( |
1079 | ! |
input$summary_type == "By Variable Levels", # needed to trigger show r code update on tab change |
1080 | ! |
common_code_q() |
1081 |
) |
|
1082 | ! |
teal::validate_has_data(data_r(), 1) |
1083 | ||
1084 |
# extract the ANL dataset for use in further validation |
|
1085 | ! |
anl <- common_code_q()[["ANL"]] |
1086 | ||
1087 | ! |
group_var <- input$group_by_var |
1088 | ! |
validate( |
1089 | ! |
need( |
1090 | ! |
is.null(group_var) || |
1091 | ! |
length(unique(anl[[group_var]])) < 100, |
1092 | ! |
"Please select group-by variable with fewer than 100 unique values" |
1093 |
) |
|
1094 |
) |
|
1095 | ||
1096 | ! |
group_vals <- input$group_by_vals |
1097 | ! |
variables_select <- input$variables_select |
1098 | ! |
vars <- unique(variables_select, group_var) |
1099 | ! |
count_type <- input$count_type |
1100 | ||
1101 | ! |
if (!is.null(selected_vars()) && length(selected_vars()) != ncol(anl)) { |
1102 | ! |
variables <- selected_vars() |
1103 |
} else { |
|
1104 | ! |
variables <- colnames(anl) |
1105 |
} |
|
1106 | ||
1107 | ! |
summ_fn <- if (input$count_type == "counts") { |
1108 | ! |
function(x) sum(is.na(x)) |
1109 |
} else { |
|
1110 | ! |
function(x) round(sum(is.na(x)) / length(x), 4) |
1111 |
} |
|
1112 | ||
1113 | ! |
qenv <- if (!is.null(group_var)) { |
1114 | ! |
teal.code::eval_code( |
1115 | ! |
common_code_q(), |
1116 | ! |
substitute( |
1117 | ! |
expr = { |
1118 | ! |
summary_data <- ANL %>% |
1119 | ! |
dplyr::mutate(group_var_name := forcats::fct_na_value_to_level(as.factor(group_var_name), "NA")) %>% |
1120 | ! |
dplyr::group_by_at(group_var) %>% |
1121 | ! |
dplyr::filter(group_var_name %in% group_vals) |
1122 | ||
1123 | ! |
count_data <- dplyr::summarise(summary_data, n = dplyr::n()) |
1124 | ||
1125 | ! |
summary_data <- dplyr::summarise_all(summary_data, summ_fn) %>% |
1126 | ! |
dplyr::mutate(group_var_name := paste0(group_var, ":", group_var_name, "(N=", count_data$n, ")")) %>% |
1127 | ! |
tidyr::pivot_longer(!dplyr::all_of(group_var), names_to = "Variable", values_to = "out") %>% |
1128 | ! |
tidyr::pivot_wider(names_from = group_var, values_from = "out") %>% |
1129 | ! |
dplyr::mutate(`Variable label` = create_cols_labels(Variable, just_label = TRUE), .after = Variable) |
1130 |
}, |
|
1131 | ! |
env = list( |
1132 | ! |
group_var = group_var, group_var_name = as.name(group_var), group_vals = group_vals, summ_fn = summ_fn |
1133 |
) |
|
1134 |
) |
|
1135 |
) |
|
1136 |
} else { |
|
1137 | ! |
teal.code::eval_code( |
1138 | ! |
common_code_q(), |
1139 | ! |
substitute( |
1140 | ! |
expr = summary_data <- ANL %>% |
1141 | ! |
dplyr::summarise_all(summ_fn) %>% |
1142 | ! |
tidyr::pivot_longer(dplyr::everything(), |
1143 | ! |
names_to = "Variable", |
1144 | ! |
values_to = paste0("Missing (N=", nrow(ANL), ")") |
1145 |
) %>% |
|
1146 | ! |
dplyr::mutate(`Variable label` = create_cols_labels(Variable), .after = Variable), |
1147 | ! |
env = list(summ_fn = summ_fn) |
1148 |
) |
|
1149 |
) |
|
1150 |
} |
|
1151 | ||
1152 | ! |
within(qenv, table <- DT::datatable(summary_data)) |
1153 |
}) |
|
1154 | ||
1155 | ! |
by_subject_plot_q <- reactive({ |
1156 |
# needed to trigger show r code update on tab change |
|
1157 | ! |
req(input$summary_type == "Grouped by Subject", common_code_q()) |
1158 | ||
1159 | ! |
teal::validate_has_data(data_r(), 1) |
1160 | ||
1161 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
1162 | ! |
labs = list(x = "", y = ""), |
1163 | ! |
theme = list(legend.position = "bottom", axis.text.x = quote(element_blank())) |
1164 |
) |
|
1165 | ||
1166 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
1167 | ! |
user_plot = ggplot2_args[["By Subject"]], |
1168 | ! |
user_default = ggplot2_args$default, |
1169 | ! |
module_plot = dev_ggplot2_args |
1170 |
) |
|
1171 | ||
1172 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
1173 | ! |
all_ggplot2_args, |
1174 | ! |
ggtheme = input$ggtheme |
1175 |
) |
|
1176 | ||
1177 | ! |
teal.code::eval_code( |
1178 | ! |
common_code_q(), |
1179 | ! |
substitute( |
1180 | ! |
expr = parent_keys <- keys, |
1181 | ! |
env = list(keys = data_parent_keys()) |
1182 |
) |
|
1183 |
) %>% |
|
1184 | ! |
teal.code::eval_code( |
1185 | ! |
substitute( |
1186 | ! |
expr = analysis_vars <- setdiff(colnames(ANL), data_keys), |
1187 | ! |
env = list(data_keys = data_keys()) |
1188 |
) |
|
1189 |
) %>% |
|
1190 | ! |
teal.code::eval_code( |
1191 | ! |
quote({ |
1192 | ! |
summary_plot_patients <- ANL[, c(parent_keys, analysis_vars)] %>% |
1193 | ! |
dplyr::group_by_at(parent_keys) %>% |
1194 | ! |
dplyr::mutate(id = dplyr::cur_group_id()) %>% |
1195 | ! |
dplyr::ungroup() %>% |
1196 | ! |
dplyr::group_by_at(c(parent_keys, "id")) %>% |
1197 | ! |
dplyr::summarise_all(anyNA) %>% |
1198 | ! |
dplyr::ungroup() |
1199 | ||
1200 |
# order subjects by decreasing number of missing and then by |
|
1201 |
# missingness pattern (defined using sha1) |
|
1202 | ! |
order_subjects <- summary_plot_patients %>% |
1203 | ! |
dplyr::select(-"id", -dplyr::all_of(parent_keys)) %>% |
1204 | ! |
dplyr::transmute( |
1205 | ! |
id = dplyr::row_number(), |
1206 | ! |
number_NA = apply(., 1, sum), |
1207 | ! |
sha = apply(., 1, rlang::hash) |
1208 |
) %>% |
|
1209 | ! |
dplyr::arrange(dplyr::desc(number_NA), sha) %>% |
1210 | ! |
getElement(name = "id") |
1211 | ||
1212 |
# order columns by decreasing percent of missing values |
|
1213 | ! |
ordered_columns <- summary_plot_patients %>% |
1214 | ! |
dplyr::select(-"id", -dplyr::all_of(parent_keys)) %>% |
1215 | ! |
dplyr::summarise( |
1216 | ! |
column = create_cols_labels(colnames(.)), |
1217 | ! |
na_count = apply(., MARGIN = 2, FUN = sum), |
1218 | ! |
na_percent = na_count / nrow(.) * 100 |
1219 |
) %>% |
|
1220 | ! |
dplyr::arrange(na_percent, dplyr::desc(column)) |
1221 | ||
1222 | ! |
summary_plot_patients <- summary_plot_patients %>% |
1223 | ! |
tidyr::gather("col", "isna", -"id", -dplyr::all_of(parent_keys)) %>% |
1224 | ! |
dplyr::mutate(col = create_cols_labels(col)) |
1225 |
}) |
|
1226 |
) %>% |
|
1227 | ! |
teal.code::eval_code( |
1228 | ! |
substitute( |
1229 | ! |
expr = { |
1230 | ! |
by_subject_plot <- ggplot(summary_plot_patients, aes( |
1231 | ! |
x = factor(id, levels = order_subjects), |
1232 | ! |
y = factor(col, levels = ordered_columns[["column"]]), |
1233 | ! |
fill = isna |
1234 |
)) + |
|
1235 | ! |
geom_raster() + |
1236 | ! |
annotate( |
1237 | ! |
"text", |
1238 | ! |
x = length(order_subjects), |
1239 | ! |
y = seq_len(nrow(ordered_columns)), |
1240 | ! |
hjust = 1, |
1241 | ! |
label = sprintf("%d [%.02f%%]", ordered_columns[["na_count"]], ordered_columns[["na_percent"]]) |
1242 |
) + |
|
1243 | ! |
scale_fill_manual( |
1244 | ! |
name = "", |
1245 | ! |
values = c("grey90", c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]), |
1246 | ! |
labels = c("Present", "Missing (at least one)") |
1247 |
) + |
|
1248 | ! |
labs + |
1249 | ! |
ggthemes + |
1250 | ! |
themes |
1251 |
}, |
|
1252 | ! |
env = list( |
1253 | ! |
labs = parsed_ggplot2_args$labs, |
1254 | ! |
themes = parsed_ggplot2_args$theme, |
1255 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
1256 |
) |
|
1257 |
) |
|
1258 |
) |
|
1259 |
}) |
|
1260 | ||
1261 |
# Decorated outputs |
|
1262 | ||
1263 |
# Summary_plot_q |
|
1264 | ! |
decorated_summary_plot_q <- srv_decorate_teal_data( |
1265 | ! |
id = "dec_summary_plot", |
1266 | ! |
data = summary_plot_q, |
1267 | ! |
decorators = select_decorators(decorators, "summary_plot"), |
1268 | ! |
expr = { |
1269 | ! |
grid::grid.newpage() |
1270 | ! |
grid::grid.draw(summary_plot) |
1271 |
} |
|
1272 |
) |
|
1273 | ||
1274 | ! |
decorated_combination_plot_q <- srv_decorate_teal_data( |
1275 | ! |
id = "dec_combination_plot", |
1276 | ! |
data = combination_plot_q, |
1277 | ! |
decorators = select_decorators(decorators, "combination_plot"), |
1278 | ! |
expr = { |
1279 | ! |
grid::grid.newpage() |
1280 | ! |
grid::grid.draw(combination_plot) |
1281 |
} |
|
1282 |
) |
|
1283 | ||
1284 | ! |
decorated_summary_table_q <- srv_decorate_teal_data( |
1285 | ! |
id = "dec_summary_table", |
1286 | ! |
data = summary_table_q, |
1287 | ! |
decorators = select_decorators(decorators, "summary_table"), |
1288 | ! |
expr = table |
1289 |
) |
|
1290 | ||
1291 | ! |
decorated_by_subject_plot_q <- srv_decorate_teal_data( |
1292 | ! |
id = "dec_by_subject_plot", |
1293 | ! |
data = by_subject_plot_q, |
1294 | ! |
decorators = select_decorators(decorators, "by_subject_plot"), |
1295 | ! |
expr = print(by_subject_plot) |
1296 |
) |
|
1297 | ||
1298 |
# Plots & tables reactives |
|
1299 | ||
1300 | ! |
summary_plot_r <- reactive({ |
1301 | ! |
req(decorated_summary_plot_q())[["summary_plot"]] |
1302 |
}) |
|
1303 | ||
1304 | ! |
combination_plot_r <- reactive({ |
1305 | ! |
req(decorated_combination_plot_q())[["combination_plot"]] |
1306 |
}) |
|
1307 | ||
1308 | ! |
summary_table_r <- reactive({ |
1309 | ! |
req(decorated_summary_table_q()) |
1310 | ||
1311 | ! |
if (length(input$variables_select) == 0) { |
1312 |
# so that zeroRecords message gets printed |
|
1313 |
# using tibble as it supports weird column names, such as " " |
|
1314 | ! |
DT::datatable( |
1315 | ! |
tibble::tibble(` ` = logical(0)), |
1316 | ! |
options = list(language = list(zeroRecords = "No variable selected."), pageLength = input$levels_table_rows) |
1317 |
) |
|
1318 |
} else { |
|
1319 | ! |
decorated_summary_table_q()[["table"]] |
1320 |
} |
|
1321 |
}) |
|
1322 | ||
1323 | ! |
by_subject_plot_r <- reactive({ |
1324 | ! |
req(decorated_by_subject_plot_q()[["by_subject_plot"]]) |
1325 |
}) |
|
1326 | ||
1327 |
# Generate output |
|
1328 | ! |
pws1 <- teal.widgets::plot_with_settings_srv( |
1329 | ! |
id = "summary_plot", |
1330 | ! |
plot_r = summary_plot_r, |
1331 | ! |
height = plot_height, |
1332 | ! |
width = plot_width |
1333 |
) |
|
1334 | ||
1335 | ! |
pws2 <- teal.widgets::plot_with_settings_srv( |
1336 | ! |
id = "combination_plot", |
1337 | ! |
plot_r = combination_plot_r, |
1338 | ! |
height = plot_height, |
1339 | ! |
width = plot_width |
1340 |
) |
|
1341 | ||
1342 | ! |
output$levels_table <- DT::renderDataTable(summary_table_r()) |
1343 | ||
1344 | ! |
pws3 <- teal.widgets::plot_with_settings_srv( |
1345 | ! |
id = "by_subject_plot", |
1346 | ! |
plot_r = by_subject_plot_r, |
1347 | ! |
height = plot_height, |
1348 | ! |
width = plot_width |
1349 |
) |
|
1350 | ||
1351 | ! |
decorated_final_q <- reactive({ |
1352 | ! |
sum_type <- req(input$summary_type) |
1353 | ! |
if (sum_type == "Summary") { |
1354 | ! |
decorated_summary_plot_q() |
1355 | ! |
} else if (sum_type == "Combinations") { |
1356 | ! |
decorated_combination_plot_q() |
1357 | ! |
} else if (sum_type == "By Variable Levels") { |
1358 | ! |
decorated_summary_table_q() |
1359 | ! |
} else if (sum_type == "Grouped by Subject") { |
1360 | ! |
decorated_by_subject_plot_q() |
1361 |
} |
|
1362 |
}) |
|
1363 | ||
1364 | ! |
teal.widgets::verbatim_popup_srv( |
1365 | ! |
id = "rcode", |
1366 | ! |
verbatim_content = reactive(teal.code::get_code(req(decorated_final_q()))), |
1367 | ! |
title = "Show R Code for Missing Data" |
1368 |
) |
|
1369 | ||
1370 |
### REPORTER |
|
1371 | ! |
if (with_reporter) { |
1372 | ! |
card_fun <- function(comment, label) { |
1373 | ! |
card <- teal::TealReportCard$new() |
1374 | ! |
sum_type <- input$summary_type |
1375 | ! |
title <- if (sum_type == "By Variable Levels") paste0(sum_type, " Table") else paste0(sum_type, " Plot") |
1376 | ! |
title_dataname <- paste(title, dataname, sep = " - ") |
1377 | ! |
label <- if (label == "") { |
1378 | ! |
paste("Missing Data", sum_type, dataname, sep = " - ") |
1379 |
} else { |
|
1380 | ! |
label |
1381 |
} |
|
1382 | ! |
card$set_name(label) |
1383 | ! |
card$append_text(title_dataname, "header2") |
1384 | ! |
if (with_filter) card$append_fs(filter_panel_api$get_filter_state()) |
1385 | ! |
if (sum_type == "Summary") { |
1386 | ! |
card$append_text("Plot", "header3") |
1387 | ! |
card$append_plot(summary_plot_r(), dim = pws1$dim()) |
1388 | ! |
} else if (sum_type == "Combinations") { |
1389 | ! |
card$append_text("Plot", "header3") |
1390 | ! |
card$append_plot(combination_plot_r(), dim = pws2$dim()) |
1391 | ! |
} else if (sum_type == "By Variable Levels") { |
1392 | ! |
card$append_text("Table", "header3") |
1393 | ! |
card$append_table(summary_table_r[["summary_data"]]) |
1394 | ! |
} else if (sum_type == "Grouped by Subject") { |
1395 | ! |
card$append_text("Plot", "header3") |
1396 | ! |
card$append_plot(by_subject_plot_r(), dim = pws3$dim()) |
1397 |
} |
|
1398 | ! |
if (!comment == "") { |
1399 | ! |
card$append_text("Comment", "header3") |
1400 | ! |
card$append_text(comment) |
1401 |
} |
|
1402 | ! |
card$append_src(teal.code::get_code(req(decorated_final_q()))) |
1403 | ! |
card |
1404 |
} |
|
1405 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
1406 |
} |
|
1407 |
### |
|
1408 |
}) |
|
1409 |
} |
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 |
#' @param decorators `r roxygen_decorators_param("tm_g_bivariate")` |
|
47 |
#' |
|
48 |
#' @inherit shared_params return |
|
49 |
#' |
|
50 |
#' @section Decorating `tm_g_bivariate`: |
|
51 |
#' |
|
52 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
53 |
#' - `plot` (`ggplot2`) |
|
54 |
#' |
|
55 |
#' For additional details and examples of decorators, refer to the vignette |
|
56 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
57 |
#' |
|
58 |
#' |
|
59 |
#' @examplesShinylive |
|
60 |
#' library(teal.modules.general) |
|
61 |
#' interactive <- function() TRUE |
|
62 |
#' {{ next_example }} |
|
63 |
#' @examples |
|
64 |
#' # general data example |
|
65 |
#' data <- teal_data() |
|
66 |
#' data <- within(data, { |
|
67 |
#' require(nestcolor) |
|
68 |
#' CO2 <- data.frame(CO2) |
|
69 |
#' }) |
|
70 |
#' |
|
71 |
#' app <- init( |
|
72 |
#' data = data, |
|
73 |
#' modules = tm_g_bivariate( |
|
74 |
#' x = data_extract_spec( |
|
75 |
#' dataname = "CO2", |
|
76 |
#' select = select_spec( |
|
77 |
#' label = "Select variable:", |
|
78 |
#' choices = variable_choices(data[["CO2"]]), |
|
79 |
#' selected = "conc", |
|
80 |
#' fixed = FALSE |
|
81 |
#' ) |
|
82 |
#' ), |
|
83 |
#' y = data_extract_spec( |
|
84 |
#' dataname = "CO2", |
|
85 |
#' select = select_spec( |
|
86 |
#' label = "Select variable:", |
|
87 |
#' choices = variable_choices(data[["CO2"]]), |
|
88 |
#' selected = "uptake", |
|
89 |
#' multiple = FALSE, |
|
90 |
#' fixed = FALSE |
|
91 |
#' ) |
|
92 |
#' ), |
|
93 |
#' row_facet = data_extract_spec( |
|
94 |
#' dataname = "CO2", |
|
95 |
#' select = select_spec( |
|
96 |
#' label = "Select variable:", |
|
97 |
#' choices = variable_choices(data[["CO2"]]), |
|
98 |
#' selected = "Type", |
|
99 |
#' fixed = FALSE |
|
100 |
#' ) |
|
101 |
#' ), |
|
102 |
#' col_facet = data_extract_spec( |
|
103 |
#' dataname = "CO2", |
|
104 |
#' select = select_spec( |
|
105 |
#' label = "Select variable:", |
|
106 |
#' choices = variable_choices(data[["CO2"]]), |
|
107 |
#' selected = "Treatment", |
|
108 |
#' fixed = FALSE |
|
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 = tm_g_bivariate( |
|
133 |
#' x = data_extract_spec( |
|
134 |
#' dataname = "ADSL", |
|
135 |
#' select = select_spec( |
|
136 |
#' label = "Select variable:", |
|
137 |
#' choices = variable_choices(data[["ADSL"]]), |
|
138 |
#' selected = "AGE", |
|
139 |
#' fixed = FALSE |
|
140 |
#' ) |
|
141 |
#' ), |
|
142 |
#' y = data_extract_spec( |
|
143 |
#' dataname = "ADSL", |
|
144 |
#' select = select_spec( |
|
145 |
#' label = "Select variable:", |
|
146 |
#' choices = variable_choices(data[["ADSL"]]), |
|
147 |
#' selected = "SEX", |
|
148 |
#' multiple = FALSE, |
|
149 |
#' fixed = FALSE |
|
150 |
#' ) |
|
151 |
#' ), |
|
152 |
#' row_facet = data_extract_spec( |
|
153 |
#' dataname = "ADSL", |
|
154 |
#' select = select_spec( |
|
155 |
#' label = "Select variable:", |
|
156 |
#' choices = variable_choices(data[["ADSL"]]), |
|
157 |
#' selected = "ARM", |
|
158 |
#' fixed = FALSE |
|
159 |
#' ) |
|
160 |
#' ), |
|
161 |
#' col_facet = data_extract_spec( |
|
162 |
#' dataname = "ADSL", |
|
163 |
#' select = select_spec( |
|
164 |
#' label = "Select variable:", |
|
165 |
#' choices = variable_choices(data[["ADSL"]]), |
|
166 |
#' selected = "COUNTRY", |
|
167 |
#' fixed = FALSE |
|
168 |
#' ) |
|
169 |
#' ) |
|
170 |
#' ) |
|
171 |
#' ) |
|
172 |
#' if (interactive()) { |
|
173 |
#' shinyApp(app$ui, app$server) |
|
174 |
#' } |
|
175 |
#' |
|
176 |
#' @export |
|
177 |
#' |
|
178 |
tm_g_bivariate <- function(label = "Bivariate Plots", |
|
179 |
x, |
|
180 |
y, |
|
181 |
row_facet = NULL, |
|
182 |
col_facet = NULL, |
|
183 |
facet = !is.null(row_facet) || !is.null(col_facet), |
|
184 |
color = NULL, |
|
185 |
fill = NULL, |
|
186 |
size = NULL, |
|
187 |
use_density = FALSE, |
|
188 |
color_settings = FALSE, |
|
189 |
free_x_scales = FALSE, |
|
190 |
free_y_scales = FALSE, |
|
191 |
plot_height = c(600, 200, 2000), |
|
192 |
plot_width = NULL, |
|
193 |
rotate_xaxis_labels = FALSE, |
|
194 |
swap_axes = FALSE, |
|
195 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
196 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
197 |
pre_output = NULL, |
|
198 |
post_output = NULL, |
|
199 |
decorators = NULL) { |
|
200 | 18x |
message("Initializing tm_g_bivariate") |
201 | ||
202 |
# Normalize the parameters |
|
203 | 14x |
if (inherits(x, "data_extract_spec")) x <- list(x) |
204 | 13x |
if (inherits(y, "data_extract_spec")) y <- list(y) |
205 | 1x |
if (inherits(row_facet, "data_extract_spec")) row_facet <- list(row_facet) |
206 | 1x |
if (inherits(col_facet, "data_extract_spec")) col_facet <- list(col_facet) |
207 | 1x |
if (inherits(color, "data_extract_spec")) color <- list(color) |
208 | 1x |
if (inherits(fill, "data_extract_spec")) fill <- list(fill) |
209 | 1x |
if (inherits(size, "data_extract_spec")) size <- list(size) |
210 | ||
211 |
# Start of assertions |
|
212 | 18x |
checkmate::assert_string(label) |
213 | ||
214 | 18x |
checkmate::assert_list(x, types = "data_extract_spec") |
215 | 18x |
assert_single_selection(x) |
216 | ||
217 | 16x |
checkmate::assert_list(y, types = "data_extract_spec") |
218 | 16x |
assert_single_selection(y) |
219 | ||
220 | 14x |
checkmate::assert_list(row_facet, types = "data_extract_spec", null.ok = TRUE) |
221 | 14x |
assert_single_selection(row_facet) |
222 | ||
223 | 14x |
checkmate::assert_list(col_facet, types = "data_extract_spec", null.ok = TRUE) |
224 | 14x |
assert_single_selection(col_facet) |
225 | ||
226 | 14x |
checkmate::assert_flag(facet) |
227 | ||
228 | 14x |
checkmate::assert_list(color, types = "data_extract_spec", null.ok = TRUE) |
229 | 14x |
assert_single_selection(color) |
230 | ||
231 | 14x |
checkmate::assert_list(fill, types = "data_extract_spec", null.ok = TRUE) |
232 | 14x |
assert_single_selection(fill) |
233 | ||
234 | 14x |
checkmate::assert_list(size, types = "data_extract_spec", null.ok = TRUE) |
235 | 14x |
assert_single_selection(size) |
236 | ||
237 | 14x |
checkmate::assert_flag(use_density) |
238 | ||
239 |
# Determines color, fill & size if they are not explicitly set |
|
240 | 14x |
checkmate::assert_flag(color_settings) |
241 | 14x |
if (color_settings) { |
242 | 2x |
if (is.null(color)) { |
243 | 2x |
color <- x |
244 | 2x |
color[[1]]$select <- teal.transform::select_spec(choices = color[[1]]$select$choices, selected = NULL) |
245 |
} |
|
246 | 2x |
if (is.null(fill)) { |
247 | 2x |
fill <- x |
248 | 2x |
fill[[1]]$select <- teal.transform::select_spec(choices = fill[[1]]$select$choices, selected = NULL) |
249 |
} |
|
250 | 2x |
if (is.null(size)) { |
251 | 2x |
size <- x |
252 | 2x |
size[[1]]$select <- teal.transform::select_spec(choices = size[[1]]$select$choices, selected = NULL) |
253 |
} |
|
254 |
} else { |
|
255 | 12x |
if (!is.null(c(color, fill, size))) { |
256 | 3x |
stop("'color_settings' argument needs to be set to TRUE if 'color', 'fill', and/or 'size' is/are supplied.") |
257 |
} |
|
258 |
} |
|
259 | ||
260 | 11x |
checkmate::assert_flag(free_x_scales) |
261 | 11x |
checkmate::assert_flag(free_y_scales) |
262 | ||
263 | 11x |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
264 | 10x |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
265 | 8x |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
266 | 7x |
checkmate::assert_numeric( |
267 | 7x |
plot_width[1], |
268 | 7x |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
269 |
) |
|
270 | ||
271 | 5x |
checkmate::assert_flag(rotate_xaxis_labels) |
272 | 5x |
checkmate::assert_flag(swap_axes) |
273 | ||
274 | 5x |
ggtheme <- match.arg(ggtheme) |
275 | 5x |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
276 | ||
277 | 5x |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
278 | 5x |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
279 | ||
280 | 5x |
decorators <- normalize_decorators(decorators) |
281 | 5x |
assert_decorators(decorators, null.ok = TRUE, "plot") |
282 |
# End of assertions |
|
283 | ||
284 |
# Make UI args |
|
285 | 5x |
args <- as.list(environment()) |
286 | ||
287 | 5x |
data_extract_list <- list( |
288 | 5x |
x = x, |
289 | 5x |
y = y, |
290 | 5x |
row_facet = row_facet, |
291 | 5x |
col_facet = col_facet, |
292 | 5x |
color_settings = color_settings, |
293 | 5x |
color = color, |
294 | 5x |
fill = fill, |
295 | 5x |
size = size |
296 |
) |
|
297 | ||
298 | 5x |
ans <- module( |
299 | 5x |
label = label, |
300 | 5x |
server = srv_g_bivariate, |
301 | 5x |
ui = ui_g_bivariate, |
302 | 5x |
ui_args = args, |
303 | 5x |
server_args = c( |
304 | 5x |
data_extract_list, |
305 | 5x |
list(plot_height = plot_height, plot_width = plot_width, ggplot2_args = ggplot2_args, decorators = decorators) |
306 |
), |
|
307 | 5x |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
308 |
) |
|
309 | 5x |
attr(ans, "teal_bookmarkable") <- TRUE |
310 | 5x |
ans |
311 |
} |
|
312 | ||
313 |
# UI function for the bivariate module |
|
314 |
ui_g_bivariate <- function(id, ...) { |
|
315 | ! |
args <- list(...) |
316 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset( |
317 | ! |
args$x, args$y, args$row_facet, args$col_facet, args$color, args$fill, args$size |
318 |
) |
|
319 | ||
320 | ! |
ns <- NS(id) |
321 | ! |
teal.widgets::standard_layout( |
322 | ! |
output = teal.widgets::white_small_well( |
323 | ! |
tags$div(teal.widgets::plot_with_settings_ui(id = ns("myplot"))) |
324 |
), |
|
325 | ! |
encoding = tags$div( |
326 |
### Reporter |
|
327 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
328 |
### |
|
329 | ! |
tags$label("Encodings", class = "text-primary"), |
330 | ! |
teal.transform::datanames_input(args[c("x", "y", "row_facet", "col_facet", "color", "fill", "size")]), |
331 | ! |
teal.transform::data_extract_ui( |
332 | ! |
id = ns("x"), |
333 | ! |
label = "X variable", |
334 | ! |
data_extract_spec = args$x, |
335 | ! |
is_single_dataset = is_single_dataset_value |
336 |
), |
|
337 | ! |
teal.transform::data_extract_ui( |
338 | ! |
id = ns("y"), |
339 | ! |
label = "Y variable", |
340 | ! |
data_extract_spec = args$y, |
341 | ! |
is_single_dataset = is_single_dataset_value |
342 |
), |
|
343 | ! |
conditionalPanel( |
344 | ! |
condition = |
345 | ! |
"$(\"button[data-id*='-x-dataset'][data-id$='-select']\").text() == '- Nothing selected - ' || |
346 | ! |
$(\"button[data-id*='-y-dataset'][data-id$='-select']\").text() == '- Nothing selected - ' ", |
347 | ! |
shinyWidgets::radioGroupButtons( |
348 | ! |
inputId = ns("use_density"), |
349 | ! |
label = NULL, |
350 | ! |
choices = c("frequency", "density"), |
351 | ! |
selected = ifelse(args$use_density, "density", "frequency"), |
352 | ! |
justified = TRUE |
353 |
) |
|
354 |
), |
|
355 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")), |
356 | ! |
if (!is.null(args$row_facet) || !is.null(args$col_facet)) { |
357 | ! |
tags$div( |
358 | ! |
class = "data-extract-box", |
359 | ! |
tags$label("Facetting"), |
360 | ! |
shinyWidgets::switchInput(inputId = ns("facetting"), value = args$facet, size = "mini"), |
361 | ! |
conditionalPanel( |
362 | ! |
condition = paste0("input['", ns("facetting"), "']"), |
363 | ! |
tags$div( |
364 | ! |
if (!is.null(args$row_facet)) { |
365 | ! |
teal.transform::data_extract_ui( |
366 | ! |
id = ns("row_facet"), |
367 | ! |
label = "Row facetting variable", |
368 | ! |
data_extract_spec = args$row_facet, |
369 | ! |
is_single_dataset = is_single_dataset_value |
370 |
) |
|
371 |
}, |
|
372 | ! |
if (!is.null(args$col_facet)) { |
373 | ! |
teal.transform::data_extract_ui( |
374 | ! |
id = ns("col_facet"), |
375 | ! |
label = "Column facetting variable", |
376 | ! |
data_extract_spec = args$col_facet, |
377 | ! |
is_single_dataset = is_single_dataset_value |
378 |
) |
|
379 |
}, |
|
380 | ! |
checkboxInput(ns("free_x_scales"), "free x scales", value = args$free_x_scales), |
381 | ! |
checkboxInput(ns("free_y_scales"), "free y scales", value = args$free_y_scales) |
382 |
) |
|
383 |
) |
|
384 |
) |
|
385 |
}, |
|
386 | ! |
if (args$color_settings) { |
387 |
# Put a grey border around the coloring settings |
|
388 | ! |
tags$div( |
389 | ! |
class = "data-extract-box", |
390 | ! |
tags$label("Color settings"), |
391 | ! |
shinyWidgets::switchInput(inputId = ns("coloring"), value = TRUE, size = "mini"), |
392 | ! |
conditionalPanel( |
393 | ! |
condition = paste0("input['", ns("coloring"), "']"), |
394 | ! |
tags$div( |
395 | ! |
teal.transform::data_extract_ui( |
396 | ! |
id = ns("color"), |
397 | ! |
label = "Outline color by variable", |
398 | ! |
data_extract_spec = args$color, |
399 | ! |
is_single_dataset = is_single_dataset_value |
400 |
), |
|
401 | ! |
teal.transform::data_extract_ui( |
402 | ! |
id = ns("fill"), |
403 | ! |
label = "Fill color by variable", |
404 | ! |
data_extract_spec = args$fill, |
405 | ! |
is_single_dataset = is_single_dataset_value |
406 |
), |
|
407 | ! |
tags$div( |
408 | ! |
id = ns("size_settings"), |
409 | ! |
teal.transform::data_extract_ui( |
410 | ! |
id = ns("size"), |
411 | ! |
label = "Size of points by variable (only if x and y are numeric)", |
412 | ! |
data_extract_spec = args$size, |
413 | ! |
is_single_dataset = is_single_dataset_value |
414 |
) |
|
415 |
) |
|
416 |
) |
|
417 |
) |
|
418 |
) |
|
419 |
}, |
|
420 | ! |
teal.widgets::panel_group( |
421 | ! |
teal.widgets::panel_item( |
422 | ! |
title = "Plot settings", |
423 | ! |
checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = args$rotate_xaxis_labels), |
424 | ! |
checkboxInput(ns("swap_axes"), "Swap axes", value = args$swap_axes), |
425 | ! |
selectInput( |
426 | ! |
inputId = ns("ggtheme"), |
427 | ! |
label = "Theme (by ggplot):", |
428 | ! |
choices = ggplot_themes, |
429 | ! |
selected = args$ggtheme, |
430 | ! |
multiple = FALSE |
431 |
), |
|
432 | ! |
sliderInput( |
433 | ! |
ns("alpha"), "Opacity Scatterplot:", |
434 | ! |
min = 0, max = 1, |
435 | ! |
step = .05, value = .5, ticks = FALSE |
436 |
), |
|
437 | ! |
sliderInput( |
438 | ! |
ns("fixed_size"), "Scatterplot point size:", |
439 | ! |
min = 1, max = 8, |
440 | ! |
step = 1, value = 2, ticks = FALSE |
441 |
), |
|
442 | ! |
checkboxInput(ns("add_lines"), "Add lines"), |
443 |
) |
|
444 |
) |
|
445 |
), |
|
446 | ! |
forms = tagList( |
447 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
448 |
), |
|
449 | ! |
pre_output = args$pre_output, |
450 | ! |
post_output = args$post_output |
451 |
) |
|
452 |
} |
|
453 | ||
454 |
# Server function for the bivariate module |
|
455 |
srv_g_bivariate <- function(id, |
|
456 |
data, |
|
457 |
reporter, |
|
458 |
filter_panel_api, |
|
459 |
x, |
|
460 |
y, |
|
461 |
row_facet, |
|
462 |
col_facet, |
|
463 |
color_settings = FALSE, |
|
464 |
color, |
|
465 |
fill, |
|
466 |
size, |
|
467 |
plot_height, |
|
468 |
plot_width, |
|
469 |
ggplot2_args, |
|
470 |
decorators) { |
|
471 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
472 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
473 | ! |
checkmate::assert_class(data, "reactive") |
474 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
475 | ! |
moduleServer(id, function(input, output, session) { |
476 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
477 | ||
478 | ! |
ns <- session$ns |
479 | ||
480 | ! |
data_extract <- list( |
481 | ! |
x = x, y = y, row_facet = row_facet, col_facet = col_facet, |
482 | ! |
color = color, fill = fill, size = size |
483 |
) |
|
484 | ||
485 | ! |
rule_var <- function(other) { |
486 | ! |
function(value) { |
487 | ! |
othervalue <- selector_list()[[other]]()$select |
488 | ! |
if (length(value) == 0L && length(othervalue) == 0L) { |
489 | ! |
"Please select at least one of x-variable or y-variable" |
490 |
} |
|
491 |
} |
|
492 |
} |
|
493 | ! |
rule_diff <- function(other) { |
494 | ! |
function(value) { |
495 | ! |
othervalue <- selector_list()[[other]]()[["select"]] |
496 | ! |
if (!is.null(othervalue)) { |
497 | ! |
if (identical(value, othervalue)) { |
498 | ! |
"Row and column facetting variables must be different." |
499 |
} |
|
500 |
} |
|
501 |
} |
|
502 |
} |
|
503 | ||
504 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
505 | ! |
data_extract = data_extract, |
506 | ! |
datasets = data, |
507 | ! |
select_validation_rule = list( |
508 | ! |
x = rule_var("y"), |
509 | ! |
y = rule_var("x"), |
510 | ! |
row_facet = shinyvalidate::compose_rules( |
511 | ! |
shinyvalidate::sv_optional(), |
512 | ! |
rule_diff("col_facet") |
513 |
), |
|
514 | ! |
col_facet = shinyvalidate::compose_rules( |
515 | ! |
shinyvalidate::sv_optional(), |
516 | ! |
rule_diff("row_facet") |
517 |
) |
|
518 |
) |
|
519 |
) |
|
520 | ||
521 | ! |
iv_r <- reactive({ |
522 | ! |
iv_facet <- shinyvalidate::InputValidator$new() |
523 | ! |
iv_child <- teal.transform::compose_and_enable_validators(iv_facet, selector_list, |
524 | ! |
validator_names = c("row_facet", "col_facet") |
525 |
) |
|
526 | ! |
iv_child$condition(~ isTRUE(input$facetting)) |
527 | ||
528 | ! |
iv <- shinyvalidate::InputValidator$new() |
529 | ! |
iv$add_validator(iv_child) |
530 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list, validator_names = c("x", "y")) |
531 |
}) |
|
532 | ||
533 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
534 | ! |
selector_list = selector_list, |
535 | ! |
datasets = data |
536 |
) |
|
537 | ||
538 | ! |
anl_merged_q <- reactive({ |
539 | ! |
req(anl_merged_input()) |
540 | ! |
data() %>% |
541 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
542 |
}) |
|
543 | ||
544 | ! |
merged <- list( |
545 | ! |
anl_input_r = anl_merged_input, |
546 | ! |
anl_q_r = anl_merged_q |
547 |
) |
|
548 | ||
549 | ! |
output_q <- reactive({ |
550 | ! |
teal::validate_inputs(iv_r()) |
551 | ||
552 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
553 | ! |
teal::validate_has_data(ANL, 3) |
554 | ||
555 | ! |
x_col_vec <- as.vector(merged$anl_input_r()$columns_source$x) |
556 | ! |
x_name <- `if`(is.null(x_col_vec), character(0), x_col_vec) |
557 | ! |
y_col_vec <- as.vector(merged$anl_input_r()$columns_source$y) |
558 | ! |
y_name <- `if`(is.null(y_col_vec), character(0), y_col_vec) |
559 | ||
560 | ! |
row_facet_name <- as.vector(merged$anl_input_r()$columns_source$row_facet) |
561 | ! |
col_facet_name <- as.vector(merged$anl_input_r()$columns_source$col_facet) |
562 | ! |
color_name <- if ("color" %in% names(merged$anl_input_r()$columns_source)) { |
563 | ! |
as.vector(merged$anl_input_r()$columns_source$color) |
564 |
} else { |
|
565 | ! |
character(0) |
566 |
} |
|
567 | ! |
fill_name <- if ("fill" %in% names(merged$anl_input_r()$columns_source)) { |
568 | ! |
as.vector(merged$anl_input_r()$columns_source$fill) |
569 |
} else { |
|
570 | ! |
character(0) |
571 |
} |
|
572 | ! |
size_name <- if ("size" %in% names(merged$anl_input_r()$columns_source)) { |
573 | ! |
as.vector(merged$anl_input_r()$columns_source$size) |
574 |
} else { |
|
575 | ! |
character(0) |
576 |
} |
|
577 | ||
578 | ! |
use_density <- input$use_density == "density" |
579 | ! |
free_x_scales <- input$free_x_scales |
580 | ! |
free_y_scales <- input$free_y_scales |
581 | ! |
ggtheme <- input$ggtheme |
582 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
583 | ! |
swap_axes <- input$swap_axes |
584 | ||
585 | ! |
is_scatterplot <- all(vapply(ANL[c(x_name, y_name)], is.numeric, logical(1))) && |
586 | ! |
length(x_name) > 0 && length(y_name) > 0 |
587 | ||
588 | ! |
if (is_scatterplot) { |
589 | ! |
shinyjs::show("alpha") |
590 | ! |
alpha <- input$alpha |
591 | ! |
shinyjs::show("add_lines") |
592 | ||
593 | ! |
if (color_settings && input$coloring) { |
594 | ! |
shinyjs::hide("fixed_size") |
595 | ! |
shinyjs::show("size_settings") |
596 | ! |
size <- NULL |
597 |
} else { |
|
598 | ! |
shinyjs::show("fixed_size") |
599 | ! |
size <- input$fixed_size |
600 |
} |
|
601 |
} else { |
|
602 | ! |
shinyjs::hide("add_lines") |
603 | ! |
updateCheckboxInput(session, "add_lines", value = restoreInput(ns("add_lines"), FALSE)) |
604 | ! |
shinyjs::hide("alpha") |
605 | ! |
shinyjs::hide("fixed_size") |
606 | ! |
shinyjs::hide("size_settings") |
607 | ! |
alpha <- 1 |
608 | ! |
size <- NULL |
609 |
} |
|
610 | ||
611 | ! |
teal::validate_has_data(ANL[, c(x_name, y_name), drop = FALSE], 3, complete = TRUE, allow_inf = FALSE) |
612 | ||
613 | ! |
cl <- bivariate_plot_call( |
614 | ! |
data_name = "ANL", |
615 | ! |
x = x_name, |
616 | ! |
y = y_name, |
617 | ! |
x_class = ifelse(!identical(x_name, character(0)), class(ANL[[x_name]]), "NULL"), |
618 | ! |
y_class = ifelse(!identical(y_name, character(0)), class(ANL[[y_name]]), "NULL"), |
619 | ! |
x_label = varname_w_label(x_name, ANL), |
620 | ! |
y_label = varname_w_label(y_name, ANL), |
621 | ! |
freq = !use_density, |
622 | ! |
theme = ggtheme, |
623 | ! |
rotate_xaxis_labels = rotate_xaxis_labels, |
624 | ! |
swap_axes = swap_axes, |
625 | ! |
alpha = alpha, |
626 | ! |
size = size, |
627 | ! |
ggplot2_args = ggplot2_args |
628 |
) |
|
629 | ||
630 | ! |
facetting <- (isTRUE(input$facetting) && (!is.null(row_facet_name) || !is.null(col_facet_name))) |
631 | ||
632 | ! |
if (facetting) { |
633 | ! |
facet_cl <- facet_ggplot_call(row_facet_name, col_facet_name, free_x_scales, free_y_scales) |
634 | ||
635 | ! |
if (!is.null(facet_cl)) { |
636 | ! |
cl <- call("+", cl, facet_cl) |
637 |
} |
|
638 |
} |
|
639 | ||
640 | ! |
if (input$add_lines) { |
641 | ! |
cl <- call("+", cl, quote(geom_line(size = 1))) |
642 |
} |
|
643 | ||
644 | ! |
coloring_cl <- NULL |
645 | ! |
if (color_settings) { |
646 | ! |
if (input$coloring) { |
647 | ! |
coloring_cl <- coloring_ggplot_call( |
648 | ! |
colour = color_name, |
649 | ! |
fill = fill_name, |
650 | ! |
size = size_name, |
651 | ! |
is_point = any(grepl("geom_point", cl %>% deparse())) |
652 |
) |
|
653 | ! |
legend_lbls <- substitute( |
654 | ! |
expr = labs(color = color_name, fill = fill_name, size = size_name), |
655 | ! |
env = list( |
656 | ! |
color_name = varname_w_label(color_name, ANL), |
657 | ! |
fill_name = varname_w_label(fill_name, ANL), |
658 | ! |
size_name = varname_w_label(size_name, ANL) |
659 |
) |
|
660 |
) |
|
661 |
} |
|
662 | ! |
if (!is.null(coloring_cl)) { |
663 | ! |
cl <- call("+", call("+", cl, coloring_cl), legend_lbls) |
664 |
} |
|
665 |
} |
|
666 | ||
667 | ! |
teal.code::eval_code(merged$anl_q_r(), substitute(expr = plot <- cl, env = list(cl = cl))) |
668 |
}) |
|
669 | ||
670 | ! |
decorated_output_q_facets <- srv_decorate_teal_data( |
671 | ! |
"decorator", |
672 | ! |
data = output_q, |
673 | ! |
decorators = select_decorators(decorators, "plot"), |
674 | ! |
expr = reactive({ |
675 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
676 | ! |
row_facet_name <- as.vector(merged$anl_input_r()$columns_source$row_facet) |
677 | ! |
col_facet_name <- as.vector(merged$anl_input_r()$columns_source$col_facet) |
678 | ||
679 |
# Add labels to facets |
|
680 | ! |
nulled_row_facet_name <- varname_w_label(row_facet_name, ANL) |
681 | ! |
nulled_col_facet_name <- varname_w_label(col_facet_name, ANL) |
682 | ! |
facetting <- (isTRUE(input$facetting) && (!is.null(row_facet_name) || !is.null(col_facet_name))) |
683 | ! |
without_facet <- (is.null(nulled_row_facet_name) && is.null(nulled_col_facet_name)) || !facetting |
684 | ||
685 | ! |
print_call <- if (without_facet) { |
686 | ! |
quote(print(plot)) |
687 |
} else { |
|
688 | ! |
substitute( |
689 | ! |
expr = { |
690 |
# Add facetting labels |
|
691 |
# optional: grid.newpage() # nolint: commented_code. |
|
692 |
# Prefixed with teal.modules.general as its usage will appear in "Show R code" |
|
693 | ! |
plot <- teal.modules.general::add_facet_labels( |
694 | ! |
plot, |
695 | ! |
xfacet_label = nulled_col_facet_name, |
696 | ! |
yfacet_label = nulled_row_facet_name |
697 |
) |
|
698 | ! |
grid::grid.newpage() |
699 | ! |
grid::grid.draw(plot) |
700 |
}, |
|
701 | ! |
env = list(nulled_col_facet_name = nulled_col_facet_name, nulled_row_facet_name = nulled_row_facet_name) |
702 |
) |
|
703 |
} |
|
704 | ! |
print_call |
705 |
}), |
|
706 | ! |
expr_is_reactive = TRUE |
707 |
) |
|
708 | ||
709 | ! |
plot_r <- reactive(req(decorated_output_q_facets())[["plot"]]) |
710 | ||
711 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
712 | ! |
id = "myplot", |
713 | ! |
plot_r = plot_r, |
714 | ! |
height = plot_height, |
715 | ! |
width = plot_width |
716 |
) |
|
717 | ||
718 | ! |
teal.widgets::verbatim_popup_srv( |
719 | ! |
id = "rcode", |
720 | ! |
verbatim_content = reactive(teal.code::get_code(req(decorated_output_q_facets()))), |
721 | ! |
title = "Bivariate Plot" |
722 |
) |
|
723 | ||
724 |
### REPORTER |
|
725 | ! |
if (with_reporter) { |
726 | ! |
card_fun <- function(comment, label) { |
727 | ! |
card <- teal::report_card_template( |
728 | ! |
title = "Bivariate Plot", |
729 | ! |
label = label, |
730 | ! |
with_filter = with_filter, |
731 | ! |
filter_panel_api = filter_panel_api |
732 |
) |
|
733 | ! |
card$append_text("Plot", "header3") |
734 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
735 | ! |
if (!comment == "") { |
736 | ! |
card$append_text("Comment", "header3") |
737 | ! |
card$append_text(comment) |
738 |
} |
|
739 | ! |
card$append_src(teal.code::get_code(req(decorated_output_q_facets))) |
740 | ! |
card |
741 |
} |
|
742 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
743 |
} |
|
744 |
### |
|
745 |
}) |
|
746 |
} |
|
747 | ||
748 |
# Get Substituted ggplot call |
|
749 |
bivariate_plot_call <- function(data_name, |
|
750 |
x = character(0), |
|
751 |
y = character(0), |
|
752 |
x_class = "NULL", |
|
753 |
y_class = "NULL", |
|
754 |
x_label = NULL, |
|
755 |
y_label = NULL, |
|
756 |
freq = TRUE, |
|
757 |
theme = "gray", |
|
758 |
rotate_xaxis_labels = FALSE, |
|
759 |
swap_axes = FALSE, |
|
760 |
alpha = double(0), |
|
761 |
size = 2, |
|
762 |
ggplot2_args = teal.widgets::ggplot2_args()) { |
|
763 | ! |
supported_types <- c("NULL", "numeric", "integer", "factor", "character", "logical", "ordered") |
764 | ! |
validate(need(x_class %in% supported_types, paste0("Data type '", x_class, "' is not supported."))) |
765 | ! |
validate(need(y_class %in% supported_types, paste0("Data type '", y_class, "' is not supported."))) |
766 | ||
767 | ||
768 | ! |
if (identical(x, character(0))) { |
769 | ! |
x <- x_label <- "-" |
770 |
} else { |
|
771 | ! |
x <- if (is.call(x)) x else as.name(x) |
772 |
} |
|
773 | ! |
if (identical(y, character(0))) { |
774 | ! |
y <- y_label <- "-" |
775 |
} else { |
|
776 | ! |
y <- if (is.call(y)) y else as.name(y) |
777 |
} |
|
778 | ||
779 | ! |
cl <- bivariate_ggplot_call( |
780 | ! |
x_class = x_class, |
781 | ! |
y_class = y_class, |
782 | ! |
freq = freq, |
783 | ! |
theme = theme, |
784 | ! |
rotate_xaxis_labels = rotate_xaxis_labels, |
785 | ! |
swap_axes = swap_axes, |
786 | ! |
alpha = alpha, |
787 | ! |
size = size, |
788 | ! |
ggplot2_args = ggplot2_args, |
789 | ! |
x = x, |
790 | ! |
y = y, |
791 | ! |
xlab = x_label, |
792 | ! |
ylab = y_label, |
793 | ! |
data_name = data_name |
794 |
) |
|
795 |
} |
|
796 | ||
797 |
# Create ggplot part of plot call |
|
798 |
# Due to the type of the x and y variable the plot type is chosen |
|
799 |
bivariate_ggplot_call <- function(x_class, |
|
800 |
y_class, |
|
801 |
freq = TRUE, |
|
802 |
theme = "gray", |
|
803 |
rotate_xaxis_labels = FALSE, |
|
804 |
swap_axes = FALSE, |
|
805 |
size = double(0), |
|
806 |
alpha = double(0), |
|
807 |
x = NULL, |
|
808 |
y = NULL, |
|
809 |
xlab = "-", |
|
810 |
ylab = "-", |
|
811 |
data_name = "ANL", |
|
812 |
ggplot2_args = teal.widgets::ggplot2_args()) { |
|
813 | 42x |
x_class <- switch(x_class, |
814 | 42x |
"character" = , |
815 | 42x |
"ordered" = , |
816 | 42x |
"logical" = , |
817 | 42x |
"factor" = "factor", |
818 | 42x |
"integer" = , |
819 | 42x |
"numeric" = "numeric", |
820 | 42x |
"NULL" = "NULL", |
821 | 42x |
stop("unsupported x_class: ", x_class) |
822 |
) |
|
823 | 42x |
y_class <- switch(y_class, |
824 | 42x |
"character" = , |
825 | 42x |
"ordered" = , |
826 | 42x |
"logical" = , |
827 | 42x |
"factor" = "factor", |
828 | 42x |
"integer" = , |
829 | 42x |
"numeric" = "numeric", |
830 | 42x |
"NULL" = "NULL", |
831 | 42x |
stop("unsupported y_class: ", y_class) |
832 |
) |
|
833 | ||
834 | 42x |
if (all(c(x_class, y_class) == "NULL")) { |
835 | ! |
stop("either x or y is required") |
836 |
} |
|
837 | ||
838 | 42x |
reduce_plot_call <- function(...) { |
839 | 104x |
args <- Filter(Negate(is.null), list(...)) |
840 | 104x |
Reduce(function(x, y) call("+", x, y), args) |
841 |
} |
|
842 | ||
843 | 42x |
plot_call <- substitute(ggplot(data_name), env = list(data_name = as.name(data_name))) |
844 | ||
845 |
# Single data plots |
|
846 | 42x |
if (x_class == "numeric" && y_class == "NULL") { |
847 | 6x |
plot_call <- reduce_plot_call(plot_call, substitute(aes(x = xval), env = list(xval = x))) |
848 | ||
849 | 6x |
if (freq) { |
850 | 4x |
plot_call <- reduce_plot_call( |
851 | 4x |
plot_call, |
852 | 4x |
quote(geom_histogram(bins = 30)), |
853 | 4x |
quote(ylab("Frequency")) |
854 |
) |
|
855 |
} else { |
|
856 | 2x |
plot_call <- reduce_plot_call( |
857 | 2x |
plot_call, |
858 | 2x |
quote(geom_histogram(bins = 30, aes(y = after_stat(density)))), |
859 | 2x |
quote(geom_density(aes(y = after_stat(density)))), |
860 | 2x |
quote(ylab("Density")) |
861 |
) |
|
862 |
} |
|
863 | 36x |
} else if (x_class == "NULL" && y_class == "numeric") { |
864 | 6x |
plot_call <- reduce_plot_call(plot_call, substitute(aes(x = yval), env = list(yval = y))) |
865 | ||
866 | 6x |
if (freq) { |
867 | 4x |
plot_call <- reduce_plot_call( |
868 | 4x |
plot_call, |
869 | 4x |
quote(geom_histogram(bins = 30)), |
870 | 4x |
quote(ylab("Frequency")) |
871 |
) |
|
872 |
} else { |
|
873 | 2x |
plot_call <- reduce_plot_call( |
874 | 2x |
plot_call, |
875 | 2x |
quote(geom_histogram(bins = 30, aes(y = after_stat(density)))), |
876 | 2x |
quote(geom_density(aes(y = after_stat(density)))), |
877 | 2x |
quote(ylab("Density")) |
878 |
) |
|
879 |
} |
|
880 | 30x |
} else if (x_class == "factor" && y_class == "NULL") { |
881 | 4x |
plot_call <- reduce_plot_call(plot_call, substitute(aes(x = xval), env = list(xval = x))) |
882 | ||
883 | 4x |
if (freq) { |
884 | 2x |
plot_call <- reduce_plot_call( |
885 | 2x |
plot_call, |
886 | 2x |
quote(geom_bar()), |
887 | 2x |
quote(ylab("Frequency")) |
888 |
) |
|
889 |
} else { |
|
890 | 2x |
plot_call <- reduce_plot_call( |
891 | 2x |
plot_call, |
892 | 2x |
quote(geom_bar(aes(y = after_stat(prop), group = 1))), |
893 | 2x |
quote(ylab("Fraction")) |
894 |
) |
|
895 |
} |
|
896 | 26x |
} else if (x_class == "NULL" && y_class == "factor") { |
897 | 4x |
plot_call <- reduce_plot_call(plot_call, substitute(aes(x = yval), env = list(yval = y))) |
898 | ||
899 | 4x |
if (freq) { |
900 | 2x |
plot_call <- reduce_plot_call( |
901 | 2x |
plot_call, |
902 | 2x |
quote(geom_bar()), |
903 | 2x |
quote(ylab("Frequency")) |
904 |
) |
|
905 |
} else { |
|
906 | 2x |
plot_call <- reduce_plot_call( |
907 | 2x |
plot_call, |
908 | 2x |
quote(geom_bar(aes(y = after_stat(prop), group = 1))), |
909 | 2x |
quote(ylab("Fraction")) |
910 |
) |
|
911 |
} |
|
912 |
# Numeric Plots |
|
913 | 22x |
} else if (x_class == "numeric" && y_class == "numeric") { |
914 | 2x |
plot_call <- reduce_plot_call( |
915 | 2x |
plot_call, |
916 | 2x |
substitute(aes(x = xval, y = yval), env = list(xval = x, yval = y)), |
917 |
# pch = 21 for consistent coloring behaviour b/w all geoms (outline and fill properties) |
|
918 | 2x |
`if`( |
919 | 2x |
!is.null(size), |
920 | 2x |
substitute( |
921 | 2x |
geom_point(alpha = alphaval, size = sizeval, pch = 21), |
922 | 2x |
env = list(alphaval = alpha, sizeval = size) |
923 |
), |
|
924 | 2x |
substitute( |
925 | 2x |
geom_point(alpha = alphaval, pch = 21), |
926 | 2x |
env = list(alphaval = alpha) |
927 |
) |
|
928 |
) |
|
929 |
) |
|
930 | 20x |
} else if ((x_class == "numeric" && y_class == "factor") || (x_class == "factor" && y_class == "numeric")) { |
931 | 6x |
plot_call <- reduce_plot_call( |
932 | 6x |
plot_call, |
933 | 6x |
substitute(aes(x = xval, y = yval), env = list(xval = x, yval = y)), |
934 | 6x |
quote(geom_boxplot()) |
935 |
) |
|
936 |
# Factor and character plots |
|
937 | 14x |
} else if (x_class == "factor" && y_class == "factor") { |
938 | 14x |
plot_call <- reduce_plot_call( |
939 | 14x |
plot_call, |
940 | 14x |
substitute( |
941 | 14x |
ggmosaic::geom_mosaic(aes(x = ggmosaic::product(xval), fill = yval), na.rm = TRUE), |
942 | 14x |
env = list(xval = x, yval = y) |
943 |
) |
|
944 |
) |
|
945 |
} else { |
|
946 | ! |
stop("x y type combination not allowed") |
947 |
} |
|
948 | ||
949 | 42x |
labs_base <- if (x_class == "NULL") { |
950 | 10x |
list(x = substitute(ylab, list(ylab = ylab))) |
951 | 42x |
} else if (y_class == "NULL") { |
952 | 10x |
list(x = substitute(xlab, list(xlab = xlab))) |
953 |
} else { |
|
954 | 22x |
list( |
955 | 22x |
x = substitute(xlab, list(xlab = xlab)), |
956 | 22x |
y = substitute(ylab, list(ylab = ylab)) |
957 |
) |
|
958 |
} |
|
959 | ||
960 | 42x |
dev_ggplot2_args <- teal.widgets::ggplot2_args(labs = labs_base) |
961 | ||
962 | 42x |
if (rotate_xaxis_labels) { |
963 | ! |
dev_ggplot2_args$theme <- list(axis.text.x = quote(element_text(angle = 45, hjust = 1))) |
964 |
} |
|
965 | ||
966 | 42x |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
967 | 42x |
user_plot = ggplot2_args, |
968 | 42x |
module_plot = dev_ggplot2_args |
969 |
) |
|
970 | ||
971 | 42x |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args(all_ggplot2_args, ggtheme = theme) |
972 | ||
973 | 42x |
plot_call <- reduce_plot_call( |
974 | 42x |
plot_call, |
975 | 42x |
parsed_ggplot2_args$labs, |
976 | 42x |
parsed_ggplot2_args$ggtheme, |
977 | 42x |
parsed_ggplot2_args$theme |
978 |
) |
|
979 | ||
980 | 42x |
if (swap_axes) { |
981 | ! |
plot_call <- reduce_plot_call(plot_call, quote(coord_flip())) |
982 |
} |
|
983 | ||
984 | 42x |
plot_call |
985 |
} |
|
986 | ||
987 |
# Create facet call |
|
988 |
facet_ggplot_call <- function(row_facet = character(0), |
|
989 |
col_facet = character(0), |
|
990 |
free_x_scales = FALSE, |
|
991 |
free_y_scales = FALSE) { |
|
992 | ! |
scales <- if (free_x_scales && free_y_scales) { |
993 | ! |
"free" |
994 | ! |
} else if (free_x_scales) { |
995 | ! |
"free_x" |
996 | ! |
} else if (free_y_scales) { |
997 | ! |
"free_y" |
998 |
} else { |
|
999 | ! |
"fixed" |
1000 |
} |
|
1001 | ||
1002 | ! |
if (identical(row_facet, character(0)) && identical(col_facet, character(0))) { |
1003 | ! |
NULL |
1004 | ! |
} else if (!identical(row_facet, character(0)) && !identical(col_facet, character(0))) { |
1005 | ! |
call( |
1006 | ! |
"facet_grid", |
1007 | ! |
rows = call_fun_dots("vars", row_facet), |
1008 | ! |
cols = call_fun_dots("vars", col_facet), |
1009 | ! |
scales = scales |
1010 |
) |
|
1011 | ! |
} else if (identical(row_facet, character(0)) && !identical(col_facet, character(0))) { |
1012 | ! |
call("facet_grid", cols = call_fun_dots("vars", col_facet), scales = scales) |
1013 | ! |
} else if (!identical(row_facet, character(0)) && identical(col_facet, character(0))) { |
1014 | ! |
call("facet_grid", rows = call_fun_dots("vars", row_facet), scales = scales) |
1015 |
} |
|
1016 |
} |
|
1017 | ||
1018 |
coloring_ggplot_call <- function(colour, |
|
1019 |
fill, |
|
1020 |
size, |
|
1021 |
is_point = FALSE) { |
|
1022 |
if ( |
|
1023 | 15x |
!identical(colour, character(0)) && |
1024 | 15x |
!identical(fill, character(0)) && |
1025 | 15x |
is_point && |
1026 | 15x |
!identical(size, character(0)) |
1027 |
) { |
|
1028 | 1x |
substitute( |
1029 | 1x |
expr = aes(colour = colour_name, fill = fill_name, size = size_name), |
1030 | 1x |
env = list(colour_name = as.name(colour), fill_name = as.name(fill), size_name = as.name(size)) |
1031 |
) |
|
1032 |
} else if ( |
|
1033 | 14x |
identical(colour, character(0)) && |
1034 | 14x |
!identical(fill, character(0)) && |
1035 | 14x |
is_point && |
1036 | 14x |
identical(size, character(0)) |
1037 |
) { |
|
1038 | 1x |
substitute(expr = aes(fill = fill_name), env = list(fill_name = as.name(fill))) |
1039 |
} else if ( |
|
1040 | 13x |
!identical(colour, character(0)) && |
1041 | 13x |
!identical(fill, character(0)) && |
1042 | 13x |
(!is_point || identical(size, character(0))) |
1043 |
) { |
|
1044 | 3x |
substitute( |
1045 | 3x |
expr = aes(colour = colour_name, fill = fill_name), |
1046 | 3x |
env = list(colour_name = as.name(colour), fill_name = as.name(fill)) |
1047 |
) |
|
1048 |
} else if ( |
|
1049 | 10x |
!identical(colour, character(0)) && |
1050 | 10x |
identical(fill, character(0)) && |
1051 | 10x |
(!is_point || identical(size, character(0))) |
1052 |
) { |
|
1053 | 1x |
substitute(expr = aes(colour = colour_name), env = list(colour_name = as.name(colour))) |
1054 |
} else if ( |
|
1055 | 9x |
identical(colour, character(0)) && |
1056 | 9x |
!identical(fill, character(0)) && |
1057 | 9x |
(!is_point || identical(size, character(0))) |
1058 |
) { |
|
1059 | 2x |
substitute(expr = aes(fill = fill_name), env = list(fill_name = as.name(fill))) |
1060 |
} else if ( |
|
1061 | 7x |
identical(colour, character(0)) && |
1062 | 7x |
identical(fill, character(0)) && |
1063 | 7x |
is_point && |
1064 | 7x |
!identical(size, character(0)) |
1065 |
) { |
|
1066 | 1x |
substitute(expr = aes(size = size_name), env = list(size_name = as.name(size))) |
1067 |
} else if ( |
|
1068 | 6x |
!identical(colour, character(0)) && |
1069 | 6x |
identical(fill, character(0)) && |
1070 | 6x |
is_point && |
1071 | 6x |
!identical(size, character(0)) |
1072 |
) { |
|
1073 | 1x |
substitute( |
1074 | 1x |
expr = aes(colour = colour_name, size = size_name), |
1075 | 1x |
env = list(colour_name = as.name(colour), size_name = as.name(size)) |
1076 |
) |
|
1077 |
} else if ( |
|
1078 | 5x |
identical(colour, character(0)) && |
1079 | 5x |
!identical(fill, character(0)) && |
1080 | 5x |
is_point && |
1081 | 5x |
!identical(size, character(0)) |
1082 |
) { |
|
1083 | 1x |
substitute( |
1084 | 1x |
expr = aes(colour = colour_name, fill = fill_name, size = size_name), |
1085 | 1x |
env = list(colour_name = as.name(fill), fill_name = as.name(fill), size_name = as.name(size)) |
1086 |
) |
|
1087 |
} else { |
|
1088 | 4x |
NULL |
1089 |
} |
|
1090 |
} |
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 `datasets_selected`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`) vector of datasets which should be |
|
18 |
#' shown, in order. Names must correspond with datasets names. |
|
19 |
#' If vector of length zero (default) then all datasets are shown. |
|
20 |
#' Note: Only `data.frame` objects are compatible; using other types will cause an error. |
|
21 |
#' |
|
22 |
#' @inherit shared_params return |
|
23 |
#' |
|
24 |
#' @examplesShinylive |
|
25 |
#' library(teal.modules.general) |
|
26 |
#' interactive <- function() TRUE |
|
27 |
#' {{ next_example }} |
|
28 |
# nolint start: line_length_linter. |
|
29 |
#' @examplesIf require("sparkline", quietly = TRUE) && require("htmlwidgets", quietly = TRUE) && require("jsonlite", quietly = TRUE) |
|
30 |
# nolint end: line_length_linter. |
|
31 |
#' # general data example |
|
32 |
#' data <- teal_data() |
|
33 |
#' data <- within(data, { |
|
34 |
#' iris <- iris |
|
35 |
#' mtcars <- mtcars |
|
36 |
#' women <- women |
|
37 |
#' faithful <- faithful |
|
38 |
#' CO2 <- CO2 |
|
39 |
#' }) |
|
40 |
#' |
|
41 |
#' app <- init( |
|
42 |
#' data = data, |
|
43 |
#' modules = modules( |
|
44 |
#' tm_variable_browser( |
|
45 |
#' label = "Variable browser" |
|
46 |
#' ) |
|
47 |
#' ) |
|
48 |
#' ) |
|
49 |
#' if (interactive()) { |
|
50 |
#' shinyApp(app$ui, app$server) |
|
51 |
#' } |
|
52 |
#' |
|
53 |
#' @examplesShinylive |
|
54 |
#' library(teal.modules.general) |
|
55 |
#' interactive <- function() TRUE |
|
56 |
#' {{ next_example }} |
|
57 |
# nolint start: line_length_linter. |
|
58 |
#' @examplesIf require("sparkline", quietly = TRUE) && require("htmlwidgets", quietly = TRUE) && require("jsonlite", quietly = TRUE) |
|
59 |
# nolint end: line_length_linter. |
|
60 |
#' # CDISC example data |
|
61 |
#' library(sparkline) |
|
62 |
#' data <- teal_data() |
|
63 |
#' data <- within(data, { |
|
64 |
#' ADSL <- teal.data::rADSL |
|
65 |
#' ADTTE <- teal.data::rADTTE |
|
66 |
#' }) |
|
67 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
68 |
#' |
|
69 |
#' app <- init( |
|
70 |
#' data = data, |
|
71 |
#' modules = modules( |
|
72 |
#' tm_variable_browser( |
|
73 |
#' label = "Variable browser" |
|
74 |
#' ) |
|
75 |
#' ) |
|
76 |
#' ) |
|
77 |
#' if (interactive()) { |
|
78 |
#' shinyApp(app$ui, app$server) |
|
79 |
#' } |
|
80 |
#' |
|
81 |
#' @export |
|
82 |
#' |
|
83 |
tm_variable_browser <- function(label = "Variable Browser", |
|
84 |
datasets_selected = character(0), |
|
85 |
parent_dataname = "ADSL", |
|
86 |
pre_output = NULL, |
|
87 |
post_output = NULL, |
|
88 |
ggplot2_args = teal.widgets::ggplot2_args()) { |
|
89 | ! |
message("Initializing tm_variable_browser") |
90 | ||
91 |
# Requires Suggested packages |
|
92 | ! |
if (!requireNamespace("sparkline", quietly = TRUE)) { |
93 | ! |
stop("Cannot load sparkline - please install the package or restart your session.") |
94 |
} |
|
95 | ! |
if (!requireNamespace("htmlwidgets", quietly = TRUE)) { |
96 | ! |
stop("Cannot load htmlwidgets - please install the package or restart your session.") |
97 |
} |
|
98 | ! |
if (!requireNamespace("jsonlite", quietly = TRUE)) { |
99 | ! |
stop("Cannot load jsonlite - please install the package or restart your session.") |
100 |
} |
|
101 | ||
102 |
# Start of assertions |
|
103 | ! |
checkmate::assert_string(label) |
104 | ! |
checkmate::assert_character(datasets_selected) |
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 | ! |
datasets_selected <- unique(datasets_selected) |
112 | ||
113 | ! |
ans <- module( |
114 | ! |
label, |
115 | ! |
server = srv_variable_browser, |
116 | ! |
ui = ui_variable_browser, |
117 | ! |
datanames = "all", |
118 | ! |
server_args = list( |
119 | ! |
datasets_selected = datasets_selected, |
120 | ! |
parent_dataname = parent_dataname, |
121 | ! |
ggplot2_args = ggplot2_args |
122 |
), |
|
123 | ! |
ui_args = list( |
124 | ! |
pre_output = pre_output, |
125 | ! |
post_output = post_output |
126 |
) |
|
127 |
) |
|
128 |
# `shiny` inputs are stored properly but the majority of the module is state of `datatable` which is not stored. |
|
129 | ! |
attr(ans, "teal_bookmarkable") <- NULL |
130 | ! |
ans |
131 |
} |
|
132 | ||
133 |
# UI function for the variable browser module |
|
134 |
ui_variable_browser <- function(id, |
|
135 |
pre_output = NULL, |
|
136 |
post_output = NULL) { |
|
137 | ! |
ns <- NS(id) |
138 | ||
139 | ! |
tagList( |
140 | ! |
include_css_files("custom"), |
141 | ! |
shinyjs::useShinyjs(), |
142 | ! |
teal.widgets::standard_layout( |
143 | ! |
output = fluidRow( |
144 | ! |
htmlwidgets::getDependency("sparkline"), # needed for sparklines to work |
145 | ! |
column( |
146 | ! |
6, |
147 |
# variable browser |
|
148 | ! |
teal.widgets::white_small_well( |
149 | ! |
uiOutput(ns("ui_variable_browser")), |
150 | ! |
shinyjs::hidden({ |
151 | ! |
checkboxInput(ns("show_parent_vars"), "Show parent dataset variables", value = FALSE) |
152 |
}) |
|
153 |
) |
|
154 |
), |
|
155 | ! |
column( |
156 | ! |
6, |
157 | ! |
teal.widgets::white_small_well( |
158 |
### Reporter |
|
159 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
160 |
### |
|
161 | ! |
tags$div( |
162 | ! |
class = "block", |
163 | ! |
uiOutput(ns("ui_histogram_display")) |
164 |
), |
|
165 | ! |
tags$div( |
166 | ! |
class = "block", |
167 | ! |
uiOutput(ns("ui_numeric_display")) |
168 |
), |
|
169 | ! |
teal.widgets::plot_with_settings_ui(ns("variable_plot")), |
170 | ! |
tags$br(), |
171 |
# input user-defined text size |
|
172 | ! |
teal.widgets::panel_item( |
173 | ! |
title = "Plot settings", |
174 | ! |
collapsed = TRUE, |
175 | ! |
selectInput( |
176 | ! |
inputId = ns("ggplot_theme"), label = "ggplot2 theme", |
177 | ! |
choices = ggplot_themes, |
178 | ! |
selected = "grey" |
179 |
), |
|
180 | ! |
fluidRow( |
181 | ! |
column(6, sliderInput( |
182 | ! |
inputId = ns("font_size"), label = "font size", |
183 | ! |
min = 5L, max = 30L, value = 15L, step = 1L, ticks = FALSE |
184 |
)), |
|
185 | ! |
column(6, sliderInput( |
186 | ! |
inputId = ns("label_rotation"), label = "rotate x labels", |
187 | ! |
min = 0L, max = 90L, value = 45L, step = 1, ticks = FALSE |
188 |
)) |
|
189 |
) |
|
190 |
), |
|
191 | ! |
tags$br(), |
192 | ! |
teal.widgets::get_dt_rows(ns("variable_summary_table"), ns("variable_summary_table_rows")), |
193 | ! |
DT::dataTableOutput(ns("variable_summary_table")) |
194 |
) |
|
195 |
) |
|
196 |
), |
|
197 | ! |
pre_output = pre_output, |
198 | ! |
post_output = post_output |
199 |
) |
|
200 |
) |
|
201 |
} |
|
202 | ||
203 |
# Server function for the variable browser module |
|
204 |
srv_variable_browser <- function(id, |
|
205 |
data, |
|
206 |
reporter, |
|
207 |
filter_panel_api, |
|
208 |
datasets_selected, parent_dataname, ggplot2_args) { |
|
209 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
210 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
211 | ! |
checkmate::assert_class(data, "reactive") |
212 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
213 | ! |
moduleServer(id, function(input, output, session) { |
214 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
215 | ||
216 |
# if there are < this number of unique records then a numeric |
|
217 |
# variable can be treated as a factor and all factors with < this groups |
|
218 |
# have their values plotted |
|
219 | ! |
.unique_records_for_factor <- 30 |
220 |
# if there are < this number of unique records then a numeric |
|
221 |
# variable is by default treated as a factor |
|
222 | ! |
.unique_records_default_as_factor <- 6 # nolint: object_length. |
223 | ||
224 | ! |
varname_numeric_as_factor <- reactiveValues() |
225 | ||
226 | ! |
datanames <- isolate(names(data())) |
227 | ! |
datanames <- Filter(function(name) { |
228 | ! |
is.data.frame(isolate(data())[[name]]) |
229 | ! |
}, datanames) |
230 | ||
231 | ! |
checkmate::assert_character(datasets_selected) |
232 | ! |
checkmate::assert_subset(datasets_selected, datanames) |
233 | ! |
if (!identical(datasets_selected, character(0))) { |
234 | ! |
checkmate::assert_subset(datasets_selected, datanames) |
235 | ! |
datanames <- datasets_selected |
236 |
} |
|
237 | ||
238 | ! |
output$ui_variable_browser <- renderUI({ |
239 | ! |
ns <- session$ns |
240 | ! |
do.call( |
241 | ! |
tabsetPanel, |
242 | ! |
c( |
243 | ! |
id = ns("tabset_panel"), |
244 | ! |
do.call( |
245 | ! |
tagList, |
246 | ! |
lapply(datanames, function(dataname) { |
247 | ! |
tabPanel( |
248 | ! |
dataname, |
249 | ! |
tags$div( |
250 | ! |
class = "mt-4", |
251 | ! |
textOutput(ns(paste0("dataset_summary_", dataname))) |
252 |
), |
|
253 | ! |
tags$div( |
254 | ! |
class = "mt-4", |
255 | ! |
teal.widgets::get_dt_rows( |
256 | ! |
ns(paste0("variable_browser_", dataname)), |
257 | ! |
ns(paste0("variable_browser_", dataname, "_rows")) |
258 |
), |
|
259 | ! |
DT::dataTableOutput(ns(paste0("variable_browser_", dataname)), width = "100%") |
260 |
) |
|
261 |
) |
|
262 |
}) |
|
263 |
) |
|
264 |
) |
|
265 |
) |
|
266 |
}) |
|
267 | ||
268 |
# conditionally display checkbox |
|
269 | ! |
shinyjs::toggle( |
270 | ! |
id = "show_parent_vars", |
271 | ! |
condition = length(parent_dataname) > 0 && parent_dataname %in% datanames |
272 |
) |
|
273 | ||
274 | ! |
columns_names <- new.env() |
275 | ||
276 |
# plot_var$data holds the name of the currently selected dataset |
|
277 |
# plot_var$variable[[<dataset_name>]] holds the name of the currently selected |
|
278 |
# variable for dataset <dataset_name> |
|
279 | ! |
plot_var <- reactiveValues(data = NULL, variable = list()) |
280 | ||
281 | ! |
establish_updating_selection(datanames, input, plot_var, columns_names) |
282 | ||
283 |
# validations |
|
284 | ! |
validation_checks <- validate_input(input, plot_var, data) |
285 | ||
286 |
# data_for_analysis is a list with two elements: a column from a dataset and the column label |
|
287 | ! |
plotted_data <- reactive({ |
288 | ! |
validation_checks() |
289 | ||
290 | ! |
get_plotted_data(input, plot_var, data) |
291 |
}) |
|
292 | ||
293 | ! |
treat_numeric_as_factor <- reactive({ |
294 | ! |
if (is_num_var_short(.unique_records_for_factor, input, plotted_data)) { |
295 | ! |
input$numeric_as_factor |
296 |
} else { |
|
297 | ! |
FALSE |
298 |
} |
|
299 |
}) |
|
300 | ||
301 | ! |
render_tabset_panel_content( |
302 | ! |
input = input, |
303 | ! |
output = output, |
304 | ! |
data = data, |
305 | ! |
datanames = datanames, |
306 | ! |
parent_dataname = parent_dataname, |
307 | ! |
columns_names = columns_names, |
308 | ! |
plot_var = plot_var |
309 |
) |
|
310 |
# add used-defined text size to ggplot arguments passed from caller frame |
|
311 | ! |
all_ggplot2_args <- reactive({ |
312 | ! |
user_text <- teal.widgets::ggplot2_args( |
313 | ! |
theme = list( |
314 | ! |
"text" = ggplot2::element_text(size = input[["font_size"]]), |
315 | ! |
"axis.text.x" = ggplot2::element_text(angle = input[["label_rotation"]], hjust = 1) |
316 |
) |
|
317 |
) |
|
318 | ! |
user_theme <- utils::getFromNamespace(sprintf("theme_%s", input[["ggplot_theme"]]), ns = "ggplot2") |
319 | ! |
user_theme <- user_theme() |
320 |
# temporary fix to circumvent assertion issue with resolve_ggplot2_args |
|
321 |
# drop problematic elements |
|
322 | ! |
user_theme <- user_theme[grep("strip.text.y.left", names(user_theme), fixed = TRUE, invert = TRUE)] |
323 | ||
324 | ! |
teal.widgets::resolve_ggplot2_args( |
325 | ! |
user_plot = user_text, |
326 | ! |
user_default = teal.widgets::ggplot2_args(theme = user_theme), |
327 | ! |
module_plot = ggplot2_args |
328 |
) |
|
329 |
}) |
|
330 | ||
331 | ! |
output$ui_numeric_display <- renderUI({ |
332 | ! |
validation_checks() |
333 | ! |
dataname <- input$tabset_panel |
334 | ! |
varname <- plot_var$variable[[dataname]] |
335 | ! |
df <- data()[[dataname]] |
336 | ||
337 | ! |
numeric_ui <- tagList( |
338 | ! |
fluidRow( |
339 | ! |
tags$div( |
340 | ! |
class = "col-md-4", |
341 | ! |
tags$br(), |
342 | ! |
shinyWidgets::switchInput( |
343 | ! |
inputId = session$ns("display_density"), |
344 | ! |
label = "Show density", |
345 | ! |
value = `if`(is.null(isolate(input$display_density)), TRUE, isolate(input$display_density)), |
346 | ! |
width = "50%", |
347 | ! |
labelWidth = "100px", |
348 | ! |
handleWidth = "50px" |
349 |
) |
|
350 |
), |
|
351 | ! |
tags$div( |
352 | ! |
class = "col-md-4", |
353 | ! |
tags$br(), |
354 | ! |
shinyWidgets::switchInput( |
355 | ! |
inputId = session$ns("remove_outliers"), |
356 | ! |
label = "Remove outliers", |
357 | ! |
value = `if`(is.null(isolate(input$remove_outliers)), FALSE, isolate(input$remove_outliers)), |
358 | ! |
width = "50%", |
359 | ! |
labelWidth = "100px", |
360 | ! |
handleWidth = "50px" |
361 |
) |
|
362 |
), |
|
363 | ! |
tags$div( |
364 | ! |
class = "col-md-4", |
365 | ! |
uiOutput(session$ns("outlier_definition_slider_ui")) |
366 |
) |
|
367 |
), |
|
368 | ! |
tags$div( |
369 | ! |
class = "ml-4", |
370 | ! |
uiOutput(session$ns("ui_density_help")), |
371 | ! |
uiOutput(session$ns("ui_outlier_help")) |
372 |
) |
|
373 |
) |
|
374 | ||
375 | ! |
observeEvent(input$numeric_as_factor, ignoreInit = TRUE, { |
376 | ! |
varname_numeric_as_factor[[plot_var$variable[[dataname]]]] <- input$numeric_as_factor |
377 |
}) |
|
378 | ||
379 | ! |
if (is.numeric(df[[varname]])) { |
380 | ! |
unique_entries <- length(unique(df[[varname]])) |
381 | ! |
if (unique_entries < .unique_records_for_factor && unique_entries > 0) { |
382 | ! |
list( |
383 | ! |
checkboxInput( |
384 | ! |
session$ns("numeric_as_factor"), |
385 | ! |
"Treat variable as factor", |
386 | ! |
value = `if`( |
387 | ! |
is.null(varname_numeric_as_factor[[varname]]), |
388 | ! |
unique_entries < .unique_records_default_as_factor, |
389 | ! |
varname_numeric_as_factor[[varname]] |
390 |
) |
|
391 |
), |
|
392 | ! |
conditionalPanel("!input.numeric_as_factor", ns = session$ns, numeric_ui) |
393 |
) |
|
394 | ! |
} else if (unique_entries > 0) { |
395 | ! |
numeric_ui |
396 |
} |
|
397 |
} else { |
|
398 | ! |
NULL |
399 |
} |
|
400 |
}) |
|
401 | ||
402 | ! |
output$ui_histogram_display <- renderUI({ |
403 | ! |
validation_checks() |
404 | ! |
dataname <- input$tabset_panel |
405 | ! |
varname <- plot_var$variable[[dataname]] |
406 | ! |
df <- data()[[dataname]] |
407 | ||
408 | ! |
numeric_ui <- tagList(fluidRow( |
409 | ! |
tags$div( |
410 | ! |
class = "col-md-4", |
411 | ! |
shinyWidgets::switchInput( |
412 | ! |
inputId = session$ns("remove_NA_hist"), |
413 | ! |
label = "Remove NA values", |
414 | ! |
value = FALSE, |
415 | ! |
width = "50%", |
416 | ! |
labelWidth = "100px", |
417 | ! |
handleWidth = "50px" |
418 |
) |
|
419 |
) |
|
420 |
)) |
|
421 | ||
422 | ! |
var <- df[[varname]] |
423 | ! |
if (anyNA(var) && (is.factor(var) || is.character(var) || is.logical(var))) { |
424 | ! |
groups <- unique(as.character(var)) |
425 | ! |
len_groups <- length(groups) |
426 | ! |
if (len_groups >= .unique_records_for_factor) { |
427 | ! |
NULL |
428 |
} else { |
|
429 | ! |
numeric_ui |
430 |
} |
|
431 |
} else { |
|
432 | ! |
NULL |
433 |
} |
|
434 |
}) |
|
435 | ||
436 | ! |
output$outlier_definition_slider_ui <- renderUI({ |
437 | ! |
req(input$remove_outliers) |
438 | ! |
sliderInput( |
439 | ! |
inputId = session$ns("outlier_definition_slider"), |
440 | ! |
tags$div( |
441 | ! |
class = "teal-tooltip", |
442 | ! |
tagList( |
443 | ! |
"Outlier definition:", |
444 | ! |
icon("circle-info"), |
445 | ! |
tags$span( |
446 | ! |
class = "tooltiptext", |
447 | ! |
paste( |
448 | ! |
"Use the slider to choose the cut-off value to define outliers; the larger the value the", |
449 | ! |
"further below Q1/above Q3 points have to be in order to be classed as outliers" |
450 |
) |
|
451 |
) |
|
452 |
) |
|
453 |
), |
|
454 | ! |
min = 1, |
455 | ! |
max = 5, |
456 | ! |
value = 3, |
457 | ! |
step = 0.5 |
458 |
) |
|
459 |
}) |
|
460 | ||
461 | ! |
output$ui_density_help <- renderUI({ |
462 | ! |
req(is.logical(input$display_density)) |
463 | ! |
if (input$display_density) { |
464 | ! |
tags$small(helpText(paste( |
465 | ! |
"Kernel density estimation with gaussian kernel", |
466 | ! |
"and bandwidth function bw.nrd0 (R default)" |
467 |
))) |
|
468 |
} else { |
|
469 | ! |
NULL |
470 |
} |
|
471 |
}) |
|
472 | ||
473 | ! |
output$ui_outlier_help <- renderUI({ |
474 | ! |
req(is.logical(input$remove_outliers), input$outlier_definition_slider) |
475 | ! |
if (input$remove_outliers) { |
476 | ! |
tags$small( |
477 | ! |
helpText( |
478 | ! |
withMathJax(paste0( |
479 | ! |
"Outlier data points (\\( X \\lt Q1 - ", input$outlier_definition_slider, "\\times IQR \\) or |
480 | ! |
\\(Q3 + ", input$outlier_definition_slider, "\\times IQR \\lt X\\)) |
481 | ! |
have not been displayed on the graph and will not be used for any kernel density estimations, ", |
482 | ! |
"although their values remain in the statisics table below." |
483 |
)) |
|
484 |
) |
|
485 |
) |
|
486 |
} else { |
|
487 | ! |
NULL |
488 |
} |
|
489 |
}) |
|
490 | ||
491 | ||
492 | ! |
variable_plot_r <- reactive({ |
493 | ! |
display_density <- `if`(is.null(input$display_density), FALSE, input$display_density) |
494 | ! |
remove_outliers <- `if`(is.null(input$remove_outliers), FALSE, input$remove_outliers) |
495 | ||
496 | ! |
if (remove_outliers) { |
497 | ! |
req(input$outlier_definition_slider) |
498 | ! |
outlier_definition <- as.numeric(input$outlier_definition_slider) |
499 |
} else { |
|
500 | ! |
outlier_definition <- 0 |
501 |
} |
|
502 | ||
503 | ! |
plot_var_summary( |
504 | ! |
var = plotted_data()$data, |
505 | ! |
var_lab = plotted_data()$var_description, |
506 | ! |
wrap_character = 15, |
507 | ! |
numeric_as_factor = treat_numeric_as_factor(), |
508 | ! |
remove_NA_hist = input$remove_NA_hist, |
509 | ! |
display_density = display_density, |
510 | ! |
outlier_definition = outlier_definition, |
511 | ! |
records_for_factor = .unique_records_for_factor, |
512 | ! |
ggplot2_args = all_ggplot2_args() |
513 |
) |
|
514 |
}) |
|
515 | ||
516 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
517 | ! |
id = "variable_plot", |
518 | ! |
plot_r = variable_plot_r, |
519 | ! |
height = c(500, 200, 2000) |
520 |
) |
|
521 | ||
522 | ! |
output$variable_summary_table <- DT::renderDataTable({ |
523 | ! |
var_summary_table( |
524 | ! |
plotted_data()$data, |
525 | ! |
treat_numeric_as_factor(), |
526 | ! |
input$variable_summary_table_rows, |
527 | ! |
if (!is.null(input$remove_outliers) && input$remove_outliers) { |
528 | ! |
req(input$outlier_definition_slider) |
529 | ! |
as.numeric(input$outlier_definition_slider) |
530 |
} else { |
|
531 | ! |
0 |
532 |
} |
|
533 |
) |
|
534 |
}) |
|
535 | ||
536 |
### REPORTER |
|
537 | ! |
if (with_reporter) { |
538 | ! |
card_fun <- function(comment) { |
539 | ! |
card <- teal::TealReportCard$new() |
540 | ! |
card$set_name("Variable Browser Plot") |
541 | ! |
card$append_text("Variable Browser Plot", "header2") |
542 | ! |
if (with_filter) card$append_fs(filter_panel_api$get_filter_state()) |
543 | ! |
card$append_text("Plot", "header3") |
544 | ! |
card$append_plot(variable_plot_r(), dim = pws$dim()) |
545 | ! |
if (!comment == "") { |
546 | ! |
card$append_text("Comment", "header3") |
547 | ! |
card$append_text(comment) |
548 |
} |
|
549 | ! |
card |
550 |
} |
|
551 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
552 |
} |
|
553 |
### |
|
554 |
}) |
|
555 |
} |
|
556 | ||
557 |
#' Summarize NAs. |
|
558 |
#' |
|
559 |
#' Summarizes occurrence of missing values in vector. |
|
560 |
#' @param x vector of any type and length |
|
561 |
#' @return Character string describing `NA` occurrence. |
|
562 |
#' @keywords internal |
|
563 |
var_missings_info <- function(x) { |
|
564 | ! |
sprintf("%s [%s%%]", sum(is.na(x)), round(mean(is.na(x) * 100), 2)) |
565 |
} |
|
566 | ||
567 |
#' Summarizes variable |
|
568 |
#' |
|
569 |
#' Creates html summary with statistics relevant to data type. For numeric values it returns central |
|
570 |
#' tendency measures, for factor returns level counts, for Date date range, for other just |
|
571 |
#' number of levels. |
|
572 |
#' |
|
573 |
#' @param x vector of any type |
|
574 |
#' @param numeric_as_factor `logical` should the numeric variable be treated as a factor |
|
575 |
#' @param dt_rows `numeric` current/latest `DT` page length |
|
576 |
#' @param outlier_definition If 0 no outliers are removed, otherwise |
|
577 |
#' outliers (those more than `outlier_definition*IQR below/above Q1/Q3` be removed) |
|
578 |
#' @return text with simple statistics. |
|
579 |
#' @keywords internal |
|
580 |
var_summary_table <- function(x, numeric_as_factor, dt_rows, outlier_definition) { |
|
581 | ! |
if (is.null(dt_rows)) { |
582 | ! |
dt_rows <- 10 |
583 |
} |
|
584 | ! |
if (is.numeric(x) && !numeric_as_factor) { |
585 | ! |
req(!any(is.infinite(x))) |
586 | ||
587 | ! |
x <- remove_outliers_from(x, outlier_definition) |
588 | ||
589 | ! |
qvals <- round(stats::quantile(x, na.rm = TRUE, probs = c(0.25, 0.5, 0.75), type = 2), 2) |
590 |
# classical central tendency measures |
|
591 | ||
592 | ! |
summary <- |
593 | ! |
data.frame( |
594 | ! |
Statistic = c("min", "Q1", "median", "mean", "Q3", "max", "sd", "n"), |
595 | ! |
Value = c( |
596 | ! |
round(min(x, na.rm = TRUE), 2), |
597 | ! |
qvals[1], |
598 | ! |
qvals[2], |
599 | ! |
round(mean(x, na.rm = TRUE), 2), |
600 | ! |
qvals[3], |
601 | ! |
round(max(x, na.rm = TRUE), 2), |
602 | ! |
round(stats::sd(x, na.rm = TRUE), 2), |
603 | ! |
length(x[!is.na(x)]) |
604 |
) |
|
605 |
) |
|
606 | ||
607 | ! |
DT::datatable(summary, rownames = FALSE, options = list(dom = "<t>", pageLength = dt_rows)) |
608 | ! |
} else if (is.factor(x) || is.character(x) || (is.numeric(x) && numeric_as_factor) || is.logical(x)) { |
609 |
# make sure factor is ordered numeric |
|
610 | ! |
if (is.numeric(x)) { |
611 | ! |
x <- factor(x, levels = sort(unique(x))) |
612 |
} |
|
613 | ||
614 | ! |
level_counts <- table(x) |
615 | ! |
max_levels_signif <- nchar(level_counts) |
616 | ||
617 | ! |
if (!all(is.na(x))) { |
618 | ! |
levels <- names(level_counts) |
619 | ! |
counts <- sprintf( |
620 | ! |
"%s [%.2f%%]", |
621 | ! |
format(level_counts, width = max_levels_signif), prop.table(level_counts) * 100 |
622 |
) |
|
623 |
} else { |
|
624 | ! |
levels <- character(0) |
625 | ! |
counts <- numeric(0) |
626 |
} |
|
627 | ||
628 | ! |
summary <- data.frame( |
629 | ! |
Level = levels, |
630 | ! |
Count = counts, |
631 | ! |
stringsAsFactors = FALSE |
632 |
) |
|
633 | ||
634 |
# sort the dataset in decreasing order of counts (needed as character variables default to alphabetical) |
|
635 | ! |
summary <- summary[order(summary$Count, decreasing = TRUE), ] |
636 | ||
637 | ! |
dom_opts <- if (nrow(summary) <= 10) { |
638 | ! |
"<t>" |
639 |
} else { |
|
640 | ! |
"<lf<t>ip>" |
641 |
} |
|
642 | ! |
DT::datatable(summary, rownames = FALSE, options = list(dom = dom_opts, pageLength = dt_rows)) |
643 | ! |
} else if (inherits(x, "Date") || inherits(x, "POSIXct") || inherits(x, "POSIXlt")) { |
644 | ! |
summary <- |
645 | ! |
data.frame( |
646 | ! |
Statistic = c("min", "median", "max"), |
647 | ! |
Value = c( |
648 | ! |
min(x, na.rm = TRUE), |
649 | ! |
stats::median(x, na.rm = TRUE), |
650 | ! |
max(x, na.rm = TRUE) |
651 |
) |
|
652 |
) |
|
653 | ! |
DT::datatable(summary, rownames = FALSE, options = list(dom = "<t>", pageLength = dt_rows)) |
654 |
} else { |
|
655 | ! |
NULL |
656 |
} |
|
657 |
} |
|
658 | ||
659 |
#' Plot variable |
|
660 |
#' |
|
661 |
#' Creates summary plot with statistics relevant to data type. |
|
662 |
#' |
|
663 |
#' @inheritParams shared_params |
|
664 |
#' @param var vector of any type to be plotted. For numeric variables it produces histogram with |
|
665 |
#' density line, for factors it creates frequency plot |
|
666 |
#' @param var_lab text describing selected variable to be displayed on the plot |
|
667 |
#' @param wrap_character (`numeric`) number of characters at which to wrap text values of `var` |
|
668 |
#' @param numeric_as_factor (`logical`) should the numeric variable be treated as a factor |
|
669 |
#' @param display_density (`logical`) should density estimation be displayed for numeric values |
|
670 |
#' @param remove_NA_hist (`logical`) should `NA` values be removed for histogram of factor like variables |
|
671 |
#' @param outlier_definition if 0 no outliers are removed, otherwise |
|
672 |
#' outliers (those more than outlier_definition*IQR below/above Q1/Q3 be removed) |
|
673 |
#' @param records_for_factor (`numeric`) if the number of factor levels is >= than this value then |
|
674 |
#' a graph of the factors isn't shown, only a list of values |
|
675 |
#' |
|
676 |
#' @return plot |
|
677 |
#' @keywords internal |
|
678 |
plot_var_summary <- function(var, |
|
679 |
var_lab, |
|
680 |
wrap_character = NULL, |
|
681 |
numeric_as_factor, |
|
682 |
display_density = is.numeric(var), |
|
683 |
remove_NA_hist = FALSE, # nolint: object_name. |
|
684 |
outlier_definition, |
|
685 |
records_for_factor, |
|
686 |
ggplot2_args) { |
|
687 | ! |
checkmate::assert_character(var_lab) |
688 | ! |
checkmate::assert_numeric(wrap_character, null.ok = TRUE) |
689 | ! |
checkmate::assert_flag(numeric_as_factor) |
690 | ! |
checkmate::assert_flag(display_density) |
691 | ! |
checkmate::assert_logical(remove_NA_hist, null.ok = TRUE) |
692 | ! |
checkmate::assert_number(outlier_definition, lower = 0, finite = TRUE) |
693 | ! |
checkmate::assert_integerish(records_for_factor, lower = 0, len = 1, any.missing = FALSE) |
694 | ! |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
695 | ||
696 | ! |
grid::grid.newpage() |
697 | ||
698 | ! |
plot_main <- if (is.factor(var) || is.character(var) || is.logical(var)) { |
699 | ! |
groups <- unique(as.character(var)) |
700 | ! |
len_groups <- length(groups) |
701 | ! |
if (len_groups >= records_for_factor) { |
702 | ! |
grid::textGrob( |
703 | ! |
sprintf( |
704 | ! |
"%s unique values\n%s:\n %s\n ...\n %s", |
705 | ! |
len_groups, |
706 | ! |
var_lab, |
707 | ! |
paste(utils::head(groups), collapse = ",\n "), |
708 | ! |
paste(utils::tail(groups), collapse = ",\n ") |
709 |
), |
|
710 | ! |
x = grid::unit(1, "line"), |
711 | ! |
y = grid::unit(1, "npc") - grid::unit(1, "line"), |
712 | ! |
just = c("left", "top") |
713 |
) |
|
714 |
} else { |
|
715 | ! |
if (!is.null(wrap_character)) { |
716 | ! |
var <- stringr::str_wrap(var, width = wrap_character) |
717 |
} |
|
718 | ! |
var <- if (isTRUE(remove_NA_hist)) as.vector(stats::na.omit(var)) else var |
719 | ! |
ggplot(data.frame(var), aes(x = forcats::fct_infreq(as.factor(var)))) + |
720 | ! |
geom_bar( |
721 | ! |
stat = "count", aes(fill = ifelse(is.na(var), "withcolor", "")), show.legend = FALSE |
722 |
) + |
|
723 | ! |
scale_fill_manual(values = c("gray50", "tan")) |
724 |
} |
|
725 | ! |
} else if (is.numeric(var)) { |
726 | ! |
validate(need(any(!is.na(var)), "No data left to visualize.")) |
727 | ||
728 |
# Filter out NA |
|
729 | ! |
var <- var[which(!is.na(var))] |
730 | ||
731 | ! |
validate(need(!any(is.infinite(var)), "Cannot display graph when data includes infinite values")) |
732 | ||
733 | ! |
if (numeric_as_factor) { |
734 | ! |
var <- factor(var) |
735 | ! |
ggplot(NULL, aes(x = var)) + |
736 | ! |
geom_histogram(stat = "count") |
737 |
} else { |
|
738 |
# remove outliers |
|
739 | ! |
if (outlier_definition != 0) { |
740 | ! |
number_records <- length(var) |
741 | ! |
var <- remove_outliers_from(var, outlier_definition) |
742 | ! |
number_outliers <- number_records - length(var) |
743 | ! |
outlier_text <- paste0( |
744 | ! |
number_outliers, " outliers (", |
745 | ! |
round(number_outliers / number_records * 100, 2), |
746 | ! |
"% of non-missing records) not shown" |
747 |
) |
|
748 | ! |
validate(need( |
749 | ! |
length(var) > 1, |
750 | ! |
"At least two data points must remain after removing outliers for this graph to be displayed" |
751 |
)) |
|
752 |
} |
|
753 |
## histogram |
|
754 | ! |
binwidth <- get_bin_width(var) |
755 | ! |
p <- ggplot(data = data.frame(var = var), aes(x = var, y = after_stat(count))) + |
756 | ! |
geom_histogram(binwidth = binwidth) + |
757 | ! |
scale_y_continuous( |
758 | ! |
sec.axis = sec_axis( |
759 | ! |
trans = ~ . / nrow(data.frame(var = var)), |
760 | ! |
labels = scales::percent, |
761 | ! |
name = "proportion (in %)" |
762 |
) |
|
763 |
) |
|
764 | ||
765 | ! |
if (display_density) { |
766 | ! |
p <- p + geom_density(aes(y = after_stat(count * binwidth))) |
767 |
} |
|
768 | ||
769 | ! |
if (outlier_definition != 0) { |
770 | ! |
p <- p + annotate( |
771 | ! |
geom = "text", |
772 | ! |
label = outlier_text, |
773 | ! |
x = Inf, y = Inf, |
774 | ! |
hjust = 1.02, vjust = 1.2, |
775 | ! |
color = "black", |
776 |
# explicitly modify geom text size according |
|
777 | ! |
size = ggplot2_args[["theme"]][["text"]][["size"]] / 3.5 |
778 |
) |
|
779 |
} |
|
780 | ! |
p |
781 |
} |
|
782 | ! |
} else if (inherits(var, "Date") || inherits(var, "POSIXct") || inherits(var, "POSIXlt")) { |
783 | ! |
var_num <- as.numeric(var) |
784 | ! |
binwidth <- get_bin_width(var_num, 1) |
785 | ! |
p <- ggplot(data = data.frame(var = var), aes(x = var, y = after_stat(count))) + |
786 | ! |
geom_histogram(binwidth = binwidth) |
787 |
} else { |
|
788 | ! |
grid::textGrob( |
789 | ! |
paste(strwrap( |
790 | ! |
utils::capture.output(utils::str(var)), |
791 | ! |
width = .9 * grid::convertWidth(grid::unit(1, "npc"), "char", TRUE) |
792 | ! |
), collapse = "\n"), |
793 | ! |
x = grid::unit(1, "line"), y = grid::unit(1, "npc") - grid::unit(1, "line"), just = c("left", "top") |
794 |
) |
|
795 |
} |
|
796 | ||
797 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
798 | ! |
labs = list(x = var_lab) |
799 |
) |
|
800 |
### |
|
801 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
802 | ! |
ggplot2_args, |
803 | ! |
module_plot = dev_ggplot2_args |
804 |
) |
|
805 | ||
806 | ! |
if (is.ggplot(plot_main)) { |
807 | ! |
if (is.numeric(var) && !numeric_as_factor) { |
808 |
# numeric not as factor |
|
809 | ! |
plot_main <- plot_main + |
810 | ! |
theme_light() + |
811 | ! |
list( |
812 | ! |
labs = do.call("labs", all_ggplot2_args$labs), |
813 | ! |
theme = do.call("theme", all_ggplot2_args$theme) |
814 |
) |
|
815 |
} else { |
|
816 |
# factor low number of levels OR numeric as factor OR Date |
|
817 | ! |
plot_main <- plot_main + |
818 | ! |
theme_light() + |
819 | ! |
list( |
820 | ! |
labs = do.call("labs", all_ggplot2_args$labs), |
821 | ! |
theme = do.call("theme", all_ggplot2_args$theme) |
822 |
) |
|
823 |
} |
|
824 | ! |
plot_main <- ggplotGrob(plot_main) |
825 |
} |
|
826 | ||
827 | ! |
grid::grid.draw(plot_main) |
828 | ! |
plot_main |
829 |
} |
|
830 | ||
831 |
is_num_var_short <- function(.unique_records_for_factor, input, data_for_analysis) { |
|
832 | ! |
length(unique(data_for_analysis()$data)) < .unique_records_for_factor && !is.null(input$numeric_as_factor) |
833 |
} |
|
834 | ||
835 |
#' Validates the variable browser inputs |
|
836 |
#' |
|
837 |
#' @param input (`session$input`) the `shiny` session input |
|
838 |
#' @param plot_var (`list`) list of a data frame and an array of variable names |
|
839 |
#' @param data (`teal_data`) the datasets passed to the module |
|
840 |
#' |
|
841 |
#' @returns `logical` TRUE if validations pass; a `shiny` validation error otherwise |
|
842 |
#' @keywords internal |
|
843 |
validate_input <- function(input, plot_var, data) { |
|
844 | ! |
reactive({ |
845 | ! |
dataset_name <- req(input$tabset_panel) |
846 | ! |
varname <- plot_var$variable[[dataset_name]] |
847 | ||
848 | ! |
validate(need(dataset_name, "No data selected")) |
849 | ! |
validate(need(varname, "No variable selected")) |
850 | ! |
df <- data()[[dataset_name]] |
851 | ! |
teal::validate_has_data(df, 1) |
852 | ! |
teal::validate_has_variable(varname = varname, data = df, "Variable not available") |
853 | ||
854 | ! |
TRUE |
855 |
}) |
|
856 |
} |
|
857 | ||
858 |
get_plotted_data <- function(input, plot_var, data) { |
|
859 | ! |
dataset_name <- input$tabset_panel |
860 | ! |
varname <- plot_var$variable[[dataset_name]] |
861 | ! |
df <- data()[[dataset_name]] |
862 | ||
863 | ! |
var_description <- teal.data::col_labels(df)[[varname]] |
864 | ! |
list(data = df[[varname]], var_description = var_description) |
865 |
} |
|
866 | ||
867 |
#' Renders the left-hand side `tabset` panel of the module |
|
868 |
#' |
|
869 |
#' @param datanames (`character`) the name of the dataset |
|
870 |
#' @param parent_dataname (`character`) the name of a parent `dataname` to filter out variables from |
|
871 |
#' @param data (`teal_data`) the object containing all datasets |
|
872 |
#' @param input (`session$input`) the `shiny` session input |
|
873 |
#' @param output (`session$output`) the `shiny` session output |
|
874 |
#' @param columns_names (`environment`) the environment containing bindings for each dataset |
|
875 |
#' @param plot_var (`list`) the list containing the currently selected dataset (tab) and its column names |
|
876 |
#' @keywords internal |
|
877 |
render_tabset_panel_content <- function(datanames, parent_dataname, output, data, input, columns_names, plot_var) { |
|
878 | ! |
lapply(datanames, render_single_tab, |
879 | ! |
input = input, |
880 | ! |
output = output, |
881 | ! |
data = data, |
882 | ! |
parent_dataname = parent_dataname, |
883 | ! |
columns_names = columns_names, |
884 | ! |
plot_var = plot_var |
885 |
) |
|
886 |
} |
|
887 | ||
888 |
#' Renders a single tab in the left-hand side tabset panel |
|
889 |
#' |
|
890 |
#' Renders a single tab in the left-hand side tabset panel. The rendered tab contains |
|
891 |
#' information about one dataset out of many presented in the module. |
|
892 |
#' |
|
893 |
#' @param dataset_name (`character`) the name of the dataset contained in the rendered tab |
|
894 |
#' @param parent_dataname (`character`) the name of a parent `dataname` to filter out variables from |
|
895 |
#' @inheritParams render_tabset_panel_content |
|
896 |
#' @keywords internal |
|
897 |
render_single_tab <- function(dataset_name, parent_dataname, output, data, input, columns_names, plot_var) { |
|
898 | ! |
render_tab_header(dataset_name, output, data) |
899 | ||
900 | ! |
render_tab_table( |
901 | ! |
dataset_name = dataset_name, |
902 | ! |
parent_dataname = parent_dataname, |
903 | ! |
output = output, |
904 | ! |
data = data, |
905 | ! |
input = input, |
906 | ! |
columns_names = columns_names, |
907 | ! |
plot_var = plot_var |
908 |
) |
|
909 |
} |
|
910 | ||
911 |
#' Renders the text headlining a single tab in the left-hand side tabset panel |
|
912 |
#' |
|
913 |
#' @param dataset_name (`character`) the name of the dataset of the tab |
|
914 |
#' @inheritParams render_tabset_panel_content |
|
915 |
#' @keywords internal |
|
916 |
render_tab_header <- function(dataset_name, output, data) { |
|
917 | ! |
dataset_ui_id <- paste0("dataset_summary_", dataset_name) |
918 | ! |
output[[dataset_ui_id]] <- renderText({ |
919 | ! |
df <- data()[[dataset_name]] |
920 | ! |
join_keys <- teal.data::join_keys(data()) |
921 | ! |
if (!is.null(join_keys)) { |
922 | ! |
key <- teal.data::join_keys(data())[dataset_name, dataset_name] |
923 |
} else { |
|
924 | ! |
key <- NULL |
925 |
} |
|
926 | ! |
sprintf( |
927 | ! |
"Dataset with %s unique key rows and %s variables", |
928 | ! |
nrow(unique(`if`(length(key) > 0, df[, key, drop = FALSE], df))), |
929 | ! |
ncol(df) |
930 |
) |
|
931 |
}) |
|
932 |
} |
|
933 | ||
934 |
#' Renders the table for a single dataset in the left-hand side tabset panel |
|
935 |
#' |
|
936 |
#' The table contains column names, column labels, |
|
937 |
#' small summary about NA values and `sparkline` (if appropriate). |
|
938 |
#' |
|
939 |
#' @param dataset_name (`character`) the name of the dataset |
|
940 |
#' @param parent_dataname (`character`) the name of a parent `dataname` to filter out variables from |
|
941 |
#' @inheritParams render_tabset_panel_content |
|
942 |
#' @keywords internal |
|
943 |
render_tab_table <- function(dataset_name, parent_dataname, output, data, input, columns_names, plot_var) { |
|
944 | ! |
table_ui_id <- paste0("variable_browser_", dataset_name) |
945 | ||
946 | ! |
output[[table_ui_id]] <- DT::renderDataTable({ |
947 | ! |
df <- data()[[dataset_name]] |
948 | ||
949 | ! |
get_vars_df <- function(input, dataset_name, parent_name, data) { |
950 | ! |
data_cols <- colnames(df) |
951 | ! |
if (isTRUE(input$show_parent_vars)) { |
952 | ! |
data_cols |
953 | ! |
} else if (dataset_name != parent_name && parent_name %in% names(data)) { |
954 | ! |
setdiff(data_cols, colnames(data()[[parent_name]])) |
955 |
} else { |
|
956 | ! |
data_cols |
957 |
} |
|
958 |
} |
|
959 | ||
960 | ! |
if (length(parent_dataname) > 0) { |
961 | ! |
df_vars <- get_vars_df(input, dataset_name, parent_dataname, data) |
962 | ! |
df <- df[df_vars] |
963 |
} |
|
964 | ||
965 | ! |
if (is.null(df) || ncol(df) == 0) { |
966 | ! |
columns_names[[dataset_name]] <- character(0) |
967 | ! |
df_output <- data.frame( |
968 | ! |
Type = character(0), |
969 | ! |
Variable = character(0), |
970 | ! |
Label = character(0), |
971 | ! |
Missings = character(0), |
972 | ! |
Sparklines = character(0), |
973 | ! |
stringsAsFactors = FALSE |
974 |
) |
|
975 |
} else { |
|
976 |
# extract data variable labels |
|
977 | ! |
labels <- teal.data::col_labels(df) |
978 | ||
979 | ! |
columns_names[[dataset_name]] <- names(labels) |
980 | ||
981 |
# calculate number of missing values |
|
982 | ! |
missings <- vapply( |
983 | ! |
df, |
984 | ! |
var_missings_info, |
985 | ! |
FUN.VALUE = character(1), |
986 | ! |
USE.NAMES = FALSE |
987 |
) |
|
988 | ||
989 |
# get icons proper for the data types |
|
990 | ! |
icons <- vapply(df, function(x) class(x)[1L], character(1L)) |
991 | ||
992 | ! |
join_keys <- teal.data::join_keys(data()) |
993 | ! |
if (!is.null(join_keys)) { |
994 | ! |
icons[intersect(join_keys[dataset_name, dataset_name], colnames(df))] <- "primary_key" |
995 |
} |
|
996 | ! |
icons <- variable_type_icons(icons) |
997 | ||
998 |
# generate sparklines |
|
999 | ! |
sparklines_html <- vapply( |
1000 | ! |
df, |
1001 | ! |
create_sparklines, |
1002 | ! |
FUN.VALUE = character(1), |
1003 | ! |
USE.NAMES = FALSE |
1004 |
) |
|
1005 | ||
1006 | ! |
df_output <- data.frame( |
1007 | ! |
Type = icons, |
1008 | ! |
Variable = names(labels), |
1009 | ! |
Label = labels, |
1010 | ! |
Missings = missings, |
1011 | ! |
Sparklines = sparklines_html, |
1012 | ! |
stringsAsFactors = FALSE |
1013 |
) |
|
1014 |
} |
|
1015 | ||
1016 |
# Select row 1 as default / fallback |
|
1017 | ! |
selected_ix <- 1 |
1018 |
# Define starting page index (base-0 index of the first item on page |
|
1019 |
# note: in many cases it's not the item itself |
|
1020 | ! |
selected_page_ix <- 0 |
1021 | ||
1022 |
# Retrieve current selected variable if any |
|
1023 | ! |
isolated_variable <- isolate(plot_var$variable[[dataset_name]]) |
1024 | ||
1025 | ! |
if (!is.null(isolated_variable)) { |
1026 | ! |
index <- which(columns_names[[dataset_name]] == isolated_variable)[1] |
1027 | ! |
if (!is.null(index) && !is.na(index) && length(index) > 0) selected_ix <- index |
1028 |
} |
|
1029 | ||
1030 |
# Retrieve the index of the first item of the current page |
|
1031 |
# it works with varying number of entries on the page (10, 25, ...) |
|
1032 | ! |
table_id_sel <- paste0("variable_browser_", dataset_name, "_state") |
1033 | ! |
dt_state <- isolate(input[[table_id_sel]]) |
1034 | ! |
if (selected_ix != 1 && !is.null(dt_state)) { |
1035 | ! |
selected_page_ix <- floor(selected_ix / dt_state$length) * dt_state$length |
1036 |
} |
|
1037 | ||
1038 | ! |
DT::datatable( |
1039 | ! |
df_output, |
1040 | ! |
escape = FALSE, |
1041 | ! |
rownames = FALSE, |
1042 | ! |
selection = list(mode = "single", target = "row", selected = selected_ix), |
1043 | ! |
options = list( |
1044 | ! |
fnDrawCallback = htmlwidgets::JS("function() { HTMLWidgets.staticRender(); }"), |
1045 | ! |
pageLength = input[[paste0(table_ui_id, "_rows")]], |
1046 | ! |
displayStart = selected_page_ix |
1047 |
) |
|
1048 |
) |
|
1049 |
}) |
|
1050 |
} |
|
1051 | ||
1052 |
#' Creates observers updating the currently selected column |
|
1053 |
#' |
|
1054 |
#' The created observers update the column currently selected in the left-hand side |
|
1055 |
#' tabset panel. |
|
1056 |
#' |
|
1057 |
#' @note |
|
1058 |
#' Creates an observer for each dataset (each tab in the tabset panel). |
|
1059 |
#' |
|
1060 |
#' @inheritParams render_tabset_panel_content |
|
1061 |
#' @keywords internal |
|
1062 |
establish_updating_selection <- function(datanames, input, plot_var, columns_names) { |
|
1063 | ! |
lapply(datanames, function(dataset_name) { |
1064 | ! |
table_ui_id <- paste0("variable_browser_", dataset_name) |
1065 | ! |
table_id_sel <- paste0(table_ui_id, "_rows_selected") |
1066 | ! |
observeEvent(input[[table_id_sel]], { |
1067 | ! |
plot_var$data <- dataset_name |
1068 | ! |
plot_var$variable[[dataset_name]] <- columns_names[[dataset_name]][input[[table_id_sel]]] |
1069 |
}) |
|
1070 |
}) |
|
1071 |
} |
|
1072 | ||
1073 |
get_bin_width <- function(x_vec, scaling_factor = 2) { |
|
1074 | ! |
x_vec <- x_vec[!is.na(x_vec)] |
1075 | ! |
qntls <- stats::quantile(x_vec, probs = c(0.1, 0.25, 0.75, 0.9), type = 2) |
1076 | ! |
iqr <- qntls[3] - qntls[2] |
1077 | ! |
binwidth <- max(scaling_factor * iqr / length(x_vec) ^ (1 / 3), sqrt(qntls[4] - qntls[1])) # styler: off |
1078 | ! |
binwidth <- ifelse(binwidth == 0, 1, binwidth) |
1079 |
# to ensure at least two bins when variable span is very small |
|
1080 | ! |
x_span <- diff(range(x_vec)) |
1081 | ! |
if (isTRUE(x_span / binwidth >= 2)) binwidth else x_span / 2 |
1082 |
} |
|
1083 | ||
1084 |
#' Removes the outlier observation from an array |
|
1085 |
#' |
|
1086 |
#' @param var (`numeric`) a numeric vector |
|
1087 |
#' @param outlier_definition (`numeric`) if `0` then no outliers are removed, otherwise |
|
1088 |
#' outliers (those more than `outlier_definition*IQR below/above Q1/Q3`) are removed |
|
1089 |
#' @returns (`numeric`) vector without the outlier values |
|
1090 |
#' @keywords internal |
|
1091 |
remove_outliers_from <- function(var, outlier_definition) { |
|
1092 | 3x |
if (outlier_definition == 0) { |
1093 | 1x |
return(var) |
1094 |
} |
|
1095 | 2x |
q1_q3 <- stats::quantile(var, probs = c(0.25, 0.75), type = 2, na.rm = TRUE) |
1096 | 2x |
iqr <- q1_q3[2] - q1_q3[1] |
1097 | 2x |
var[var >= q1_q3[1] - outlier_definition * iqr & var <= q1_q3[2] + outlier_definition * iqr] |
1098 |
} |
|
1099 | ||
1100 | ||
1101 |
# sparklines ---- |
|
1102 | ||
1103 |
#' S3 generic for `sparkline` widget HTML |
|
1104 |
#' |
|
1105 |
#' Generates the `sparkline` HTML code corresponding to the input array. |
|
1106 |
#' For numeric variables creates a box plot, for character and factors - bar plot. |
|
1107 |
#' Produces an empty string for variables of other types. |
|
1108 |
#' |
|
1109 |
#' @param arr vector of any type and length |
|
1110 |
#' @param width `numeric` the width of the `sparkline` widget (pixels) |
|
1111 |
#' @param bar_spacing `numeric` the spacing between the bars (in pixels) |
|
1112 |
#' @param bar_width `numeric` the width of the bars (in pixels) |
|
1113 |
#' @param ... `list` additional options passed to bar plots of `jquery.sparkline`; |
|
1114 |
#' see [`jquery.sparkline docs`](https://omnipotent.net/jquery.sparkline/#common) |
|
1115 |
#' |
|
1116 |
#' @return Character string containing HTML code of the `sparkline` HTML widget. |
|
1117 |
#' @keywords internal |
|
1118 |
create_sparklines <- function(arr, width = 150, ...) { |
|
1119 | ! |
if (all(is.null(arr))) { |
1120 | ! |
return("") |
1121 |
} |
|
1122 | ! |
UseMethod("create_sparklines") |
1123 |
} |
|
1124 | ||
1125 |
#' @rdname create_sparklines |
|
1126 |
#' @keywords internal |
|
1127 |
#' @export |
|
1128 |
create_sparklines.logical <- function(arr, ...) { |
|
1129 | ! |
create_sparklines(as.factor(arr)) |
1130 |
} |
|
1131 | ||
1132 |
#' @rdname create_sparklines |
|
1133 |
#' @keywords internal |
|
1134 |
#' @export |
|
1135 |
create_sparklines.numeric <- function(arr, width = 150, ...) { |
|
1136 | ! |
if (any(is.infinite(arr))) { |
1137 | ! |
return(as.character(tags$code("infinite values", class = "text-blue"))) |
1138 |
} |
|
1139 | ! |
if (length(arr) > 100000) { |
1140 | ! |
return(as.character(tags$code("Too many rows (>100000)", class = "text-blue"))) |
1141 |
} |
|
1142 | ||
1143 | ! |
arr <- arr[!is.na(arr)] |
1144 | ! |
sparkline::spk_chr(unname(arr), type = "box", width = width, ...) |
1145 |
} |
|
1146 | ||
1147 |
#' @rdname create_sparklines |
|
1148 |
#' @keywords internal |
|
1149 |
#' @export |
|
1150 |
create_sparklines.character <- function(arr, ...) { |
|
1151 | ! |
return(create_sparklines(as.factor(arr))) |
1152 |
} |
|
1153 | ||
1154 | ||
1155 |
#' @rdname create_sparklines |
|
1156 |
#' @keywords internal |
|
1157 |
#' @export |
|
1158 |
create_sparklines.factor <- function(arr, width = 150, bar_spacing = 5, bar_width = 20, ...) { |
|
1159 | ! |
decreasing_order <- TRUE |
1160 | ||
1161 | ! |
counts <- table(arr) |
1162 | ! |
if (length(counts) >= 100) { |
1163 | ! |
return(as.character(tags$code("> 99 levels", class = "text-blue"))) |
1164 | ! |
} else if (length(counts) == 0) { |
1165 | ! |
return(as.character(tags$code("no levels", class = "text-blue"))) |
1166 | ! |
} else if (length(counts) == 1) { |
1167 | ! |
return(as.character(tags$code("one level", class = "text-blue"))) |
1168 |
} |
|
1169 | ||
1170 |
# Summarize the occurences of different levels |
|
1171 |
# and get the maximum and minimum number of occurences |
|
1172 |
# This is needed for the sparkline to correctly display the bar plots |
|
1173 |
# Otherwise they are cropped |
|
1174 | ! |
counts <- sort(counts, decreasing = decreasing_order, method = "radix") |
1175 | ! |
max_value <- if (decreasing_order) counts[1] else counts[length[counts]] |
1176 | ! |
max_value <- unname(max_value) |
1177 | ||
1178 | ! |
sparkline::spk_chr( |
1179 | ! |
unname(counts), |
1180 | ! |
type = "bar", |
1181 | ! |
chartRangeMin = 0, |
1182 | ! |
chartRangeMax = max_value, |
1183 | ! |
width = width, |
1184 | ! |
barWidth = bar_width, |
1185 | ! |
barSpacing = bar_spacing, |
1186 | ! |
tooltipFormatter = custom_sparkline_formatter(names(counts), as.vector(counts)) |
1187 |
) |
|
1188 |
} |
|
1189 | ||
1190 |
#' @rdname create_sparklines |
|
1191 |
#' @keywords internal |
|
1192 |
#' @export |
|
1193 |
create_sparklines.Date <- function(arr, width = 150, bar_spacing = 5, bar_width = 20, ...) { |
|
1194 | ! |
arr_num <- as.numeric(arr) |
1195 | ! |
arr_num <- sort(arr_num, decreasing = FALSE, method = "radix") |
1196 | ! |
binwidth <- get_bin_width(arr_num, 1) |
1197 | ! |
bins <- floor(diff(range(arr_num)) / binwidth) + 1 |
1198 | ! |
if (all(is.na(bins))) { |
1199 | ! |
return(as.character(tags$code("only NA", class = "text-blue"))) |
1200 | ! |
} else if (bins == 1) { |
1201 | ! |
return(as.character(tags$code("one date", class = "text-blue"))) |
1202 |
} |
|
1203 | ! |
counts <- as.vector(unname(base::table(cut(arr_num, breaks = bins)))) |
1204 | ! |
max_value <- max(counts) |
1205 | ||
1206 | ! |
start_bins <- as.integer(seq(1, length(arr_num), length.out = bins)) |
1207 | ! |
labels_start <- as.character(as.Date(arr_num[start_bins], origin = as.Date("1970-01-01"))) |
1208 | ! |
labels <- paste("Start:", labels_start) |
1209 | ||
1210 | ! |
sparkline::spk_chr( |
1211 | ! |
unname(counts), |
1212 | ! |
type = "bar", |
1213 | ! |
chartRangeMin = 0, |
1214 | ! |
chartRangeMax = max_value, |
1215 | ! |
width = width, |
1216 | ! |
barWidth = bar_width, |
1217 | ! |
barSpacing = bar_spacing, |
1218 | ! |
tooltipFormatter = custom_sparkline_formatter(labels, counts) |
1219 |
) |
|
1220 |
} |
|
1221 | ||
1222 |
#' @rdname create_sparklines |
|
1223 |
#' @keywords internal |
|
1224 |
#' @export |
|
1225 |
create_sparklines.POSIXct <- function(arr, width = 150, bar_spacing = 5, bar_width = 20, ...) { |
|
1226 | ! |
arr_num <- as.numeric(arr) |
1227 | ! |
arr_num <- sort(arr_num, decreasing = FALSE, method = "radix") |
1228 | ! |
binwidth <- get_bin_width(arr_num, 1) |
1229 | ! |
bins <- floor(diff(range(arr_num)) / binwidth) + 1 |
1230 | ! |
if (all(is.na(bins))) { |
1231 | ! |
return(as.character(tags$code("only NA", class = "text-blue"))) |
1232 | ! |
} else if (bins == 1) { |
1233 | ! |
return(as.character(tags$code("one date-time", class = "text-blue"))) |
1234 |
} |
|
1235 | ! |
counts <- as.vector(unname(base::table(cut(arr_num, breaks = bins)))) |
1236 | ! |
max_value <- max(counts) |
1237 | ||
1238 | ! |
start_bins <- as.integer(seq(1, length(arr_num), length.out = bins)) |
1239 | ! |
labels_start <- as.character(format(as.POSIXct(arr_num[start_bins], origin = as.Date("1970-01-01")), "%Y-%m-%d")) |
1240 | ! |
labels <- paste("Start:", labels_start) |
1241 | ||
1242 | ! |
sparkline::spk_chr( |
1243 | ! |
unname(counts), |
1244 | ! |
type = "bar", |
1245 | ! |
chartRangeMin = 0, |
1246 | ! |
chartRangeMax = max_value, |
1247 | ! |
width = width, |
1248 | ! |
barWidth = bar_width, |
1249 | ! |
barSpacing = bar_spacing, |
1250 | ! |
tooltipFormatter = custom_sparkline_formatter(labels, counts) |
1251 |
) |
|
1252 |
} |
|
1253 | ||
1254 |
#' @rdname create_sparklines |
|
1255 |
#' @keywords internal |
|
1256 |
#' @export |
|
1257 |
create_sparklines.POSIXlt <- function(arr, width = 150, bar_spacing = 5, bar_width = 20, ...) { |
|
1258 | ! |
arr_num <- as.numeric(arr) |
1259 | ! |
arr_num <- sort(arr_num, decreasing = FALSE, method = "radix") |
1260 | ! |
binwidth <- get_bin_width(arr_num, 1) |
1261 | ! |
bins <- floor(diff(range(arr_num)) / binwidth) + 1 |
1262 | ! |
if (all(is.na(bins))) { |
1263 | ! |
return(as.character(tags$code("only NA", class = "text-blue"))) |
1264 | ! |
} else if (bins == 1) { |
1265 | ! |
return(as.character(tags$code("one date-time", class = "text-blue"))) |
1266 |
} |
|
1267 | ! |
counts <- as.vector(unname(base::table(cut(arr_num, breaks = bins)))) |
1268 | ! |
max_value <- max(counts) |
1269 | ||
1270 | ! |
start_bins <- as.integer(seq(1, length(arr_num), length.out = bins)) |
1271 | ! |
labels_start <- as.character(format(as.POSIXct(arr_num[start_bins], origin = as.Date("1970-01-01")), "%Y-%m-%d")) |
1272 | ! |
labels <- paste("Start:", labels_start) |
1273 | ||
1274 | ! |
sparkline::spk_chr( |
1275 | ! |
unname(counts), |
1276 | ! |
type = "bar", |
1277 | ! |
chartRangeMin = 0, |
1278 | ! |
chartRangeMax = max_value, |
1279 | ! |
width = width, |
1280 | ! |
barWidth = bar_width, |
1281 | ! |
barSpacing = bar_spacing, |
1282 | ! |
tooltipFormatter = custom_sparkline_formatter(labels, counts) |
1283 |
) |
|
1284 |
} |
|
1285 | ||
1286 |
#' @rdname create_sparklines |
|
1287 |
#' @keywords internal |
|
1288 |
#' @export |
|
1289 |
create_sparklines.default <- function(arr, width = 150, ...) { |
|
1290 | ! |
as.character(tags$code("unsupported variable type", class = "text-blue")) |
1291 |
} |
|
1292 | ||
1293 | ||
1294 |
custom_sparkline_formatter <- function(labels, counts) { |
|
1295 | ! |
htmlwidgets::JS( |
1296 | ! |
sprintf( |
1297 | ! |
"function(sparkline, options, field) { |
1298 | ! |
return 'ID: ' + %s[field[0].offset] + '<br>' + 'Count: ' + %s[field[0].offset]; |
1299 |
}", |
|
1300 | ! |
jsonlite::toJSON(labels), |
1301 | ! |
jsonlite::toJSON(counts) |
1302 |
) |
|
1303 |
) |
|
1304 |
} |
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`) indicating whether the metadata of the datasets be available on the module. |
|
17 |
#' |
|
18 |
#' @inherit shared_params return |
|
19 |
#' |
|
20 |
#' @examplesShinylive |
|
21 |
#' library(teal.modules.general) |
|
22 |
#' interactive <- function() TRUE |
|
23 |
#' {{ next_example }} |
|
24 |
#' @examples |
|
25 |
#' data <- teal_data() |
|
26 |
#' data <- within(data, { |
|
27 |
#' require(nestcolor) |
|
28 |
#' ADSL <- teal.data::rADSL |
|
29 |
#' attr(ADSL, "metadata") <- list("Author" = "NEST team", "data_source" = "synthetic data") |
|
30 |
#' }) |
|
31 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
32 |
#' |
|
33 |
#' table_1 <- data.frame(Info = c("A", "B"), Text = c("A", "B")) |
|
34 |
#' table_2 <- data.frame(`Column 1` = c("C", "D"), `Column 2` = c(5.5, 6.6), `Column 3` = c("A", "B")) |
|
35 |
#' table_3 <- data.frame(Info = c("E", "F"), Text = c("G", "H")) |
|
36 |
#' |
|
37 |
#' table_input <- list( |
|
38 |
#' "Table 1" = table_1, |
|
39 |
#' "Table 2" = table_2, |
|
40 |
#' "Table 3" = table_3 |
|
41 |
#' ) |
|
42 |
#' |
|
43 |
#' app <- init( |
|
44 |
#' data = data, |
|
45 |
#' modules = modules( |
|
46 |
#' tm_front_page( |
|
47 |
#' header_text = c( |
|
48 |
#' "Important information" = "It can go here.", |
|
49 |
#' "Other information" = "Can go here." |
|
50 |
#' ), |
|
51 |
#' tables = table_input, |
|
52 |
#' additional_tags = HTML("Additional HTML or shiny tags go here <br>"), |
|
53 |
#' footnotes = c("X" = "is the first footnote", "Y is the second footnote"), |
|
54 |
#' show_metadata = TRUE |
|
55 |
#' ) |
|
56 |
#' ), |
|
57 |
#' header = tags$h1("Sample Application"), |
|
58 |
#' footer = tags$p("Application footer"), |
|
59 |
#' ) |
|
60 |
#' |
|
61 |
#' if (interactive()) { |
|
62 |
#' shinyApp(app$ui, app$server) |
|
63 |
#' } |
|
64 |
#' |
|
65 |
#' @export |
|
66 |
#' |
|
67 |
tm_front_page <- function(label = "Front page", |
|
68 |
header_text = character(0), |
|
69 |
tables = list(), |
|
70 |
additional_tags = tagList(), |
|
71 |
footnotes = character(0), |
|
72 |
show_metadata = FALSE) { |
|
73 | ! |
message("Initializing tm_front_page") |
74 | ||
75 |
# Start of assertions |
|
76 | ! |
checkmate::assert_string(label) |
77 | ! |
checkmate::assert_character(header_text, min.len = 0, any.missing = FALSE) |
78 | ! |
checkmate::assert_list(tables, types = "data.frame", names = "named", any.missing = FALSE) |
79 | ! |
checkmate::assert_multi_class(additional_tags, classes = c("shiny.tag.list", "html")) |
80 | ! |
checkmate::assert_character(footnotes, min.len = 0, any.missing = FALSE) |
81 | ! |
checkmate::assert_flag(show_metadata) |
82 |
# End of assertions |
|
83 | ||
84 |
# Make UI args |
|
85 | ! |
args <- as.list(environment()) |
86 | ||
87 | ! |
ans <- module( |
88 | ! |
label = label, |
89 | ! |
server = srv_front_page, |
90 | ! |
ui = ui_front_page, |
91 | ! |
ui_args = args, |
92 | ! |
server_args = list(tables = tables, show_metadata = show_metadata), |
93 | ! |
datanames = if (show_metadata) "all" else NULL |
94 |
) |
|
95 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
96 | ! |
ans |
97 |
} |
|
98 | ||
99 |
# UI function for the front page module |
|
100 |
ui_front_page <- function(id, ...) { |
|
101 | ! |
args <- list(...) |
102 | ! |
ns <- NS(id) |
103 | ||
104 | ! |
tagList( |
105 | ! |
include_css_files("custom"), |
106 | ! |
tags$div( |
107 | ! |
id = "front_page_content", |
108 | ! |
class = "ml-8", |
109 | ! |
tags$div( |
110 | ! |
id = "front_page_headers", |
111 | ! |
get_header_tags(args$header_text) |
112 |
), |
|
113 | ! |
tags$div( |
114 | ! |
id = "front_page_tables", |
115 | ! |
class = "ml-4", |
116 | ! |
get_table_tags(args$tables, ns) |
117 |
), |
|
118 | ! |
tags$div( |
119 | ! |
id = "front_page_custom_html", |
120 | ! |
class = "my-4", |
121 | ! |
args$additional_tags |
122 |
), |
|
123 | ! |
if (args$show_metadata) { |
124 | ! |
tags$div( |
125 | ! |
id = "front_page_metabutton", |
126 | ! |
class = "m-4", |
127 | ! |
actionButton(ns("metadata_button"), "Show metadata") |
128 |
) |
|
129 |
}, |
|
130 | ! |
tags$footer( |
131 | ! |
class = ".small", |
132 | ! |
get_footer_tags(args$footnotes) |
133 |
) |
|
134 |
) |
|
135 |
) |
|
136 |
} |
|
137 | ||
138 |
# Server function for the front page module |
|
139 |
srv_front_page <- function(id, data, tables, show_metadata) { |
|
140 | ! |
checkmate::assert_class(data, "reactive") |
141 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
142 | ! |
moduleServer(id, function(input, output, session) { |
143 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
144 | ||
145 | ! |
ns <- session$ns |
146 | ||
147 | ! |
setBookmarkExclude("metadata_button") |
148 | ||
149 | ! |
lapply(seq_along(tables), function(idx) { |
150 | ! |
output[[paste0("table_", idx)]] <- renderTable( |
151 | ! |
tables[[idx]], |
152 | ! |
bordered = TRUE, |
153 | ! |
caption = names(tables)[idx], |
154 | ! |
caption.placement = "top" |
155 |
) |
|
156 |
}) |
|
157 | ||
158 | ! |
if (show_metadata) { |
159 | ! |
observeEvent( |
160 | ! |
input$metadata_button, showModal( |
161 | ! |
modalDialog( |
162 | ! |
title = "Metadata", |
163 | ! |
dataTableOutput(ns("metadata_table")), |
164 | ! |
size = "l", |
165 | ! |
easyClose = TRUE |
166 |
) |
|
167 |
) |
|
168 |
) |
|
169 | ||
170 | ! |
metadata_data_frame <- reactive({ |
171 | ! |
datanames <- names(data()) |
172 | ! |
convert_metadata_to_dataframe( |
173 | ! |
lapply(datanames, function(dataname) attr(data()[[dataname]], "metadata")), |
174 | ! |
datanames |
175 |
) |
|
176 |
}) |
|
177 | ||
178 | ! |
output$metadata_table <- renderDataTable({ |
179 | ! |
validate(need(nrow(metadata_data_frame()) > 0, "The data has no associated metadata")) |
180 | ! |
metadata_data_frame() |
181 |
}) |
|
182 |
} |
|
183 |
}) |
|
184 |
} |
|
185 | ||
186 |
## utils functions |
|
187 | ||
188 |
get_header_tags <- function(header_text) { |
|
189 | ! |
if (length(header_text) == 0) { |
190 | ! |
return(list()) |
191 |
} |
|
192 | ||
193 | ! |
get_single_header_tags <- function(header_text, p_text, header_tag = tags$h4) { |
194 | ! |
tagList( |
195 | ! |
tags$div( |
196 | ! |
if (!is.null(header_text) && nchar(header_text) > 0) header_tag(header_text), |
197 | ! |
tags$p(p_text) |
198 |
) |
|
199 |
) |
|
200 |
} |
|
201 | ||
202 | ! |
header_tags <- get_single_header_tags(names(header_text[1]), header_text[1], header_tag = tags$h3) |
203 | ! |
c(header_tags, mapply(get_single_header_tags, utils::tail(names(header_text), -1), utils::tail(header_text, -1))) |
204 |
} |
|
205 | ||
206 |
get_table_tags <- function(tables, ns) { |
|
207 | ! |
if (length(tables) == 0) { |
208 | ! |
return(list()) |
209 |
} |
|
210 | ! |
table_tags <- c(lapply(seq_along(tables), function(idx) { |
211 | ! |
list( |
212 | ! |
tableOutput(ns(paste0("table_", idx))) |
213 |
) |
|
214 |
})) |
|
215 | ! |
return(table_tags) |
216 |
} |
|
217 | ||
218 |
get_footer_tags <- function(footnotes) { |
|
219 | ! |
if (length(footnotes) == 0) { |
220 | ! |
return(list()) |
221 |
} |
|
222 | ! |
bold_texts <- if (is.null(names(footnotes))) rep("", length(footnotes)) else names(footnotes) |
223 | ! |
footnote_tags <- mapply(function(bold_text, value) { |
224 | ! |
list( |
225 | ! |
tags$div( |
226 | ! |
tags$b(bold_text), |
227 | ! |
value, |
228 | ! |
tags$br() |
229 |
) |
|
230 |
) |
|
231 | ! |
}, bold_text = bold_texts, value = footnotes) |
232 |
} |
|
233 | ||
234 |
# take a list of metadata, one item per dataset (raw_metadata each element from datasets$get_metadata()) |
|
235 |
# and the corresponding datanames and output a data.frame with columns {Dataset, Name, Value}. |
|
236 |
# which are, the Dataset the metadata came from, the metadata's name and value |
|
237 |
convert_metadata_to_dataframe <- function(raw_metadata, datanames) { |
|
238 | 4x |
output <- mapply(function(metadata, dataname) { |
239 | 6x |
if (is.null(metadata)) { |
240 | 2x |
return(data.frame(Dataset = character(0), Name = character(0), Value = character(0))) |
241 |
} |
|
242 | 4x |
return(data.frame( |
243 | 4x |
Dataset = dataname, |
244 | 4x |
Name = names(metadata), |
245 | 4x |
Value = unname(unlist(lapply(metadata, as.character))) |
246 |
)) |
|
247 | 4x |
}, raw_metadata, datanames, SIMPLIFY = FALSE) |
248 | 4x |
do.call(rbind, output) |
249 |
} |
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 |
#' @param decorators `r roxygen_decorators_param("tm_a_pca")` |
|
18 |
#' |
|
19 |
#' @inherit shared_params return |
|
20 |
#' |
|
21 |
#' @section Decorating `tm_a_pca`: |
|
22 |
#' |
|
23 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
24 |
#' - `elbow_plot` (`ggplot2`) |
|
25 |
#' - `circle_plot` (`ggplot2`) |
|
26 |
#' - `biplot` (`ggplot2`) |
|
27 |
#' - `eigenvector_plot` (`ggplot2`) |
|
28 |
#' |
|
29 |
#' Decorators can be applied to all outputs or only to specific objects using a |
|
30 |
#' named list of `teal_transform_module` objects. |
|
31 |
#' The `"default"` name is reserved for decorators that are applied to all outputs. |
|
32 |
#' See code snippet below: |
|
33 |
#' |
|
34 |
#' ``` |
|
35 |
#' tm_a_pca( |
|
36 |
#' ..., # arguments for module |
|
37 |
#' decorators = list( |
|
38 |
#' default = list(teal_transform_module(...)), # applied to all outputs |
|
39 |
#' elbow_plot = list(teal_transform_module(...)), # applied only to `elbow_plot` output |
|
40 |
#' circle_plot = list(teal_transform_module(...)) # applied only to `circle_plot` output |
|
41 |
#' biplot = list(teal_transform_module(...)) # applied only to `biplot` output |
|
42 |
#' eigenvector_plot = list(teal_transform_module(...)) # applied only to `eigenvector_plot` output |
|
43 |
#' ) |
|
44 |
#' ) |
|
45 |
#' ``` |
|
46 |
#' |
|
47 |
#' For additional details and examples of decorators, refer to the vignette |
|
48 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
49 |
#' |
|
50 |
#' @examplesShinylive |
|
51 |
#' library(teal.modules.general) |
|
52 |
#' interactive <- function() TRUE |
|
53 |
#' {{ next_example }} |
|
54 |
#' @examples |
|
55 |
#' |
|
56 |
#' # general data example |
|
57 |
#' data <- teal_data() |
|
58 |
#' data <- within(data, { |
|
59 |
#' require(nestcolor) |
|
60 |
#' USArrests <- USArrests |
|
61 |
#' }) |
|
62 |
#' |
|
63 |
#' app <- init( |
|
64 |
#' data = data, |
|
65 |
#' modules = modules( |
|
66 |
#' tm_a_pca( |
|
67 |
#' "PCA", |
|
68 |
#' dat = data_extract_spec( |
|
69 |
#' dataname = "USArrests", |
|
70 |
#' select = select_spec( |
|
71 |
#' choices = variable_choices( |
|
72 |
#' data = data[["USArrests"]], c("Murder", "Assault", "UrbanPop", "Rape") |
|
73 |
#' ), |
|
74 |
#' selected = c("Murder", "Assault"), |
|
75 |
#' multiple = TRUE |
|
76 |
#' ), |
|
77 |
#' filter = NULL |
|
78 |
#' ) |
|
79 |
#' ) |
|
80 |
#' ) |
|
81 |
#' ) |
|
82 |
#' if (interactive()) { |
|
83 |
#' shinyApp(app$ui, app$server) |
|
84 |
#' } |
|
85 |
#' |
|
86 |
#' @examplesShinylive |
|
87 |
#' library(teal.modules.general) |
|
88 |
#' interactive <- function() TRUE |
|
89 |
#' {{ next_example }} |
|
90 |
#' @examples |
|
91 |
#' |
|
92 |
#' # CDISC data example |
|
93 |
#' data <- teal_data() |
|
94 |
#' data <- within(data, { |
|
95 |
#' require(nestcolor) |
|
96 |
#' ADSL <- teal.data::rADSL |
|
97 |
#' }) |
|
98 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
99 |
#' |
|
100 |
#' app <- init( |
|
101 |
#' data = data, |
|
102 |
#' modules = modules( |
|
103 |
#' tm_a_pca( |
|
104 |
#' "PCA", |
|
105 |
#' dat = data_extract_spec( |
|
106 |
#' dataname = "ADSL", |
|
107 |
#' select = select_spec( |
|
108 |
#' choices = variable_choices( |
|
109 |
#' data = data[["ADSL"]], c("BMRKR1", "AGE", "EOSDY") |
|
110 |
#' ), |
|
111 |
#' selected = c("BMRKR1", "AGE"), |
|
112 |
#' multiple = TRUE |
|
113 |
#' ), |
|
114 |
#' filter = NULL |
|
115 |
#' ) |
|
116 |
#' ) |
|
117 |
#' ) |
|
118 |
#' ) |
|
119 |
#' if (interactive()) { |
|
120 |
#' shinyApp(app$ui, app$server) |
|
121 |
#' } |
|
122 |
#' |
|
123 |
#' @export |
|
124 |
#' |
|
125 |
tm_a_pca <- function(label = "Principal Component Analysis", |
|
126 |
dat, |
|
127 |
plot_height = c(600, 200, 2000), |
|
128 |
plot_width = NULL, |
|
129 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
130 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
131 |
rotate_xaxis_labels = FALSE, |
|
132 |
font_size = c(12, 8, 20), |
|
133 |
alpha = c(1, 0, 1), |
|
134 |
size = c(2, 1, 8), |
|
135 |
pre_output = NULL, |
|
136 |
post_output = NULL, |
|
137 |
decorators = NULL) { |
|
138 | ! |
message("Initializing tm_a_pca") |
139 | ||
140 |
# Normalize the parameters |
|
141 | ! |
if (inherits(dat, "data_extract_spec")) dat <- list(dat) |
142 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
143 | ||
144 |
# Start of assertions |
|
145 | ! |
checkmate::assert_string(label) |
146 | ! |
checkmate::assert_list(dat, types = "data_extract_spec") |
147 | ||
148 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
149 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
150 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
151 | ! |
checkmate::assert_numeric( |
152 | ! |
plot_width[1], |
153 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
154 |
) |
|
155 | ||
156 | ! |
ggtheme <- match.arg(ggtheme) |
157 | ||
158 | ! |
plot_choices <- c("Elbow plot", "Circle plot", "Biplot", "Eigenvector plot") |
159 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
160 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
161 | ||
162 | ! |
checkmate::assert_flag(rotate_xaxis_labels) |
163 | ||
164 | ! |
if (length(font_size) == 1) { |
165 | ! |
checkmate::assert_numeric(font_size, any.missing = FALSE, finite = TRUE, lower = 8, upper = 20) |
166 |
} else { |
|
167 | ! |
checkmate::assert_numeric(font_size, len = 3, any.missing = FALSE, finite = TRUE, lower = 8, upper = 20) |
168 | ! |
checkmate::assert_numeric(font_size[1], lower = font_size[2], upper = font_size[3], .var.name = "font_size") |
169 |
} |
|
170 | ||
171 | ! |
if (length(alpha) == 1) { |
172 | ! |
checkmate::assert_numeric(alpha, any.missing = FALSE, finite = TRUE, lower = 0, upper = 1) |
173 |
} else { |
|
174 | ! |
checkmate::assert_numeric(alpha, len = 3, any.missing = FALSE, finite = TRUE, lower = 0, upper = 1) |
175 | ! |
checkmate::assert_numeric(alpha[1], lower = alpha[2], upper = alpha[3], .var.name = "alpha") |
176 |
} |
|
177 | ||
178 | ! |
if (length(size) == 1) { |
179 | ! |
checkmate::assert_numeric(size, any.missing = FALSE, finite = TRUE, lower = 1, upper = 8) |
180 |
} else { |
|
181 | ! |
checkmate::assert_numeric(size, len = 3, any.missing = FALSE, finite = TRUE, lower = 1, upper = 8) |
182 | ! |
checkmate::assert_numeric(size[1], lower = size[2], upper = size[3], .var.name = "size") |
183 |
} |
|
184 | ||
185 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
186 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
187 | ||
188 | ! |
available_decorators <- c("elbow_plot", "circle_plot", "biplot", "eigenvector_plot") |
189 | ! |
decorators <- normalize_decorators(decorators) |
190 | ! |
assert_decorators(decorators, null.ok = TRUE, available_decorators) |
191 |
# End of assertions |
|
192 | ||
193 |
# Make UI args |
|
194 | ! |
args <- as.list(environment()) |
195 | ||
196 | ! |
data_extract_list <- list(dat = dat) |
197 | ||
198 | ! |
ans <- module( |
199 | ! |
label = label, |
200 | ! |
server = srv_a_pca, |
201 | ! |
ui = ui_a_pca, |
202 | ! |
ui_args = args, |
203 | ! |
server_args = c( |
204 | ! |
data_extract_list, |
205 | ! |
list( |
206 | ! |
plot_height = plot_height, |
207 | ! |
plot_width = plot_width, |
208 | ! |
ggplot2_args = ggplot2_args, |
209 | ! |
decorators = decorators |
210 |
) |
|
211 |
), |
|
212 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
213 |
) |
|
214 | ! |
attr(ans, "teal_bookmarkable") <- FALSE |
215 | ! |
ans |
216 |
} |
|
217 | ||
218 |
# UI function for the PCA module |
|
219 |
ui_a_pca <- function(id, ...) { |
|
220 | ! |
ns <- NS(id) |
221 | ! |
args <- list(...) |
222 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$dat) |
223 | ||
224 | ! |
color_selector <- args$dat |
225 | ! |
for (i in seq_along(color_selector)) { |
226 | ! |
color_selector[[i]]$select$multiple <- FALSE |
227 | ! |
color_selector[[i]]$select$always_selected <- NULL |
228 | ! |
color_selector[[i]]$select$selected <- NULL |
229 |
} |
|
230 | ||
231 | ! |
tagList( |
232 | ! |
include_css_files("custom"), |
233 | ! |
teal.widgets::standard_layout( |
234 | ! |
output = teal.widgets::white_small_well( |
235 | ! |
uiOutput(ns("all_plots")) |
236 |
), |
|
237 | ! |
encoding = tags$div( |
238 |
### Reporter |
|
239 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
240 |
### |
|
241 | ! |
tags$label("Encodings", class = "text-primary"), |
242 | ! |
teal.transform::datanames_input(args["dat"]), |
243 | ! |
teal.transform::data_extract_ui( |
244 | ! |
id = ns("dat"), |
245 | ! |
label = "Data selection", |
246 | ! |
data_extract_spec = args$dat, |
247 | ! |
is_single_dataset = is_single_dataset_value |
248 |
), |
|
249 | ! |
teal.widgets::panel_group( |
250 | ! |
teal.widgets::panel_item( |
251 | ! |
title = "Display", |
252 | ! |
collapsed = FALSE, |
253 | ! |
checkboxGroupInput( |
254 | ! |
ns("tables_display"), |
255 | ! |
"Tables display", |
256 | ! |
choices = c("PC importance" = "importance", "Eigenvectors" = "eigenvector"), |
257 | ! |
selected = c("importance", "eigenvector") |
258 |
), |
|
259 | ! |
radioButtons( |
260 | ! |
ns("plot_type"), |
261 | ! |
label = "Plot type", |
262 | ! |
choices = args$plot_choices, |
263 | ! |
selected = args$plot_choices[1] |
264 |
), |
|
265 | ! |
conditionalPanel( |
266 | ! |
condition = sprintf("input['%s'] == 'Elbow plot'", ns("plot_type")), |
267 | ! |
ui_decorate_teal_data( |
268 | ! |
ns("d_elbow_plot"), |
269 | ! |
decorators = select_decorators(args$decorators, "elbow_plot") |
270 |
) |
|
271 |
), |
|
272 | ! |
conditionalPanel( |
273 | ! |
condition = sprintf("input['%s'] == 'Circle plot'", ns("plot_type")), |
274 | ! |
ui_decorate_teal_data( |
275 | ! |
ns("d_circle_plot"), |
276 | ! |
decorators = select_decorators(args$decorators, "circle_plot") |
277 |
) |
|
278 |
), |
|
279 | ! |
conditionalPanel( |
280 | ! |
condition = sprintf("input['%s'] == 'Biplot'", ns("plot_type")), |
281 | ! |
ui_decorate_teal_data( |
282 | ! |
ns("d_biplot"), |
283 | ! |
decorators = select_decorators(args$decorators, "biplot") |
284 |
) |
|
285 |
), |
|
286 | ! |
conditionalPanel( |
287 | ! |
condition = sprintf("input['%s'] == 'Eigenvector plot'", ns("plot_type")), |
288 | ! |
ui_decorate_teal_data( |
289 | ! |
ns("d_eigenvector_plot"), |
290 | ! |
decorators = select_decorators(args$decorators, "eigenvector_plot") |
291 |
) |
|
292 |
) |
|
293 |
), |
|
294 | ! |
teal.widgets::panel_item( |
295 | ! |
title = "Pre-processing", |
296 | ! |
radioButtons( |
297 | ! |
ns("standardization"), "Standardization", |
298 | ! |
choices = c("None" = "none", "Center" = "center", "Center & Scale" = "center_scale"), |
299 | ! |
selected = "center_scale" |
300 |
), |
|
301 | ! |
radioButtons( |
302 | ! |
ns("na_action"), "NA action", |
303 | ! |
choices = c("None" = "none", "Drop" = "drop"), |
304 | ! |
selected = "none" |
305 |
) |
|
306 |
), |
|
307 | ! |
teal.widgets::panel_item( |
308 | ! |
title = "Selected plot specific settings", |
309 | ! |
collapsed = FALSE, |
310 | ! |
uiOutput(ns("plot_settings")), |
311 | ! |
conditionalPanel( |
312 | ! |
condition = sprintf("input['%s'] == 'Biplot'", ns("plot_type")), |
313 | ! |
list( |
314 | ! |
teal.transform::data_extract_ui( |
315 | ! |
id = ns("response"), |
316 | ! |
label = "Color by", |
317 | ! |
data_extract_spec = color_selector, |
318 | ! |
is_single_dataset = is_single_dataset_value |
319 |
), |
|
320 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("alpha"), "Opacity:", args$alpha, ticks = FALSE), |
321 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("size"), "Points size:", args$size, ticks = FALSE) |
322 |
) |
|
323 |
) |
|
324 |
), |
|
325 | ! |
teal.widgets::panel_item( |
326 | ! |
title = "Plot settings", |
327 | ! |
collapsed = TRUE, |
328 | ! |
conditionalPanel( |
329 | ! |
condition = sprintf( |
330 | ! |
"input['%s'] == 'Elbow plot' || input['%s'] == 'Eigenvector plot'", |
331 | ! |
ns("plot_type"), |
332 | ! |
ns("plot_type") |
333 |
), |
|
334 | ! |
list(checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = args$rotate_xaxis_labels)) |
335 |
), |
|
336 | ! |
selectInput( |
337 | ! |
inputId = ns("ggtheme"), |
338 | ! |
label = "Theme (by ggplot):", |
339 | ! |
choices = ggplot_themes, |
340 | ! |
selected = args$ggtheme, |
341 | ! |
multiple = FALSE |
342 |
), |
|
343 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("font_size"), "Font Size", args$font_size, ticks = FALSE) |
344 |
) |
|
345 |
) |
|
346 |
), |
|
347 | ! |
forms = tagList( |
348 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
349 |
), |
|
350 | ! |
pre_output = args$pre_output, |
351 | ! |
post_output = args$post_output |
352 |
) |
|
353 |
) |
|
354 |
} |
|
355 | ||
356 |
# Server function for the PCA module |
|
357 |
srv_a_pca <- function(id, data, reporter, filter_panel_api, dat, plot_height, plot_width, ggplot2_args, decorators) { |
|
358 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
359 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
360 | ! |
checkmate::assert_class(data, "reactive") |
361 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
362 | ! |
moduleServer(id, function(input, output, session) { |
363 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
364 | ||
365 | ! |
response <- dat |
366 | ||
367 | ! |
for (i in seq_along(response)) { |
368 | ! |
response[[i]]$select$multiple <- FALSE |
369 | ! |
response[[i]]$select$always_selected <- NULL |
370 | ! |
response[[i]]$select$selected <- NULL |
371 | ! |
all_cols <- teal.data::col_labels(isolate(data())[[response[[i]]$dataname]]) |
372 | ! |
ignore_cols <- unlist(teal.data::join_keys(isolate(data()))[[response[[i]]$dataname]]) |
373 | ! |
color_cols <- all_cols[!names(all_cols) %in% ignore_cols] |
374 | ! |
response[[i]]$select$choices <- teal.transform::choices_labeled(names(color_cols), color_cols) |
375 |
} |
|
376 | ||
377 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
378 | ! |
data_extract = list(dat = dat, response = response), |
379 | ! |
datasets = data, |
380 | ! |
select_validation_rule = list( |
381 | ! |
dat = ~ if (length(.) < 2L) "Please select more than 1 variable to perform PCA.", |
382 | ! |
response = shinyvalidate::compose_rules( |
383 | ! |
shinyvalidate::sv_optional(), |
384 | ! |
~ if (isTRUE(is.element(., selector_list()$dat()$select))) { |
385 | ! |
"Response must not have been used for PCA." |
386 |
} |
|
387 |
) |
|
388 |
) |
|
389 |
) |
|
390 | ||
391 | ! |
iv_r <- reactive({ |
392 | ! |
iv <- shinyvalidate::InputValidator$new() |
393 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
394 |
}) |
|
395 | ||
396 | ! |
iv_extra <- shinyvalidate::InputValidator$new() |
397 | ! |
iv_extra$add_rule("x_axis", function(value) { |
398 | ! |
if (isTRUE(input$plot_type %in% c("Circle plot", "Biplot"))) { |
399 | ! |
if (!shinyvalidate::input_provided(value)) { |
400 | ! |
"Need X axis" |
401 |
} |
|
402 |
} |
|
403 |
}) |
|
404 | ! |
iv_extra$add_rule("y_axis", function(value) { |
405 | ! |
if (isTRUE(input$plot_type %in% c("Circle plot", "Biplot"))) { |
406 | ! |
if (!shinyvalidate::input_provided(value)) { |
407 | ! |
"Need Y axis" |
408 |
} |
|
409 |
} |
|
410 |
}) |
|
411 | ! |
rule_dupl <- function(...) { |
412 | ! |
if (isTRUE(input$plot_type %in% c("Circle plot", "Biplot"))) { |
413 | ! |
if (isTRUE(input$x_axis == input$y_axis)) { |
414 | ! |
"Please choose different X and Y axes." |
415 |
} |
|
416 |
} |
|
417 |
} |
|
418 | ! |
iv_extra$add_rule("x_axis", rule_dupl) |
419 | ! |
iv_extra$add_rule("y_axis", rule_dupl) |
420 | ! |
iv_extra$add_rule("variables", function(value) { |
421 | ! |
if (identical(input$plot_type, "Circle plot")) { |
422 | ! |
if (!shinyvalidate::input_provided(value)) { |
423 | ! |
"Need Original Coordinates" |
424 |
} |
|
425 |
} |
|
426 |
}) |
|
427 | ! |
iv_extra$add_rule("pc", function(value) { |
428 | ! |
if (identical(input$plot_type, "Eigenvector plot")) { |
429 | ! |
if (!shinyvalidate::input_provided(value)) { |
430 | ! |
"Need PC" |
431 |
} |
|
432 |
} |
|
433 |
}) |
|
434 | ! |
iv_extra$enable() |
435 | ||
436 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
437 | ! |
selector_list = selector_list, |
438 | ! |
datasets = data |
439 |
) |
|
440 | ||
441 | ! |
anl_merged_q <- reactive({ |
442 | ! |
req(anl_merged_input()) |
443 | ! |
data() %>% |
444 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
445 |
}) |
|
446 | ||
447 | ! |
merged <- list( |
448 | ! |
anl_input_r = anl_merged_input, |
449 | ! |
anl_q_r = anl_merged_q |
450 |
) |
|
451 | ||
452 | ! |
validation <- reactive({ |
453 | ! |
req(merged$anl_q_r()) |
454 |
# inputs |
|
455 | ! |
keep_cols <- as.character(merged$anl_input_r()$columns_source$dat) |
456 | ! |
na_action <- input$na_action |
457 | ! |
standardization <- input$standardization |
458 | ! |
center <- standardization %in% c("center", "center_scale") |
459 | ! |
scale <- standardization == "center_scale" |
460 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
461 | ||
462 | ! |
teal::validate_has_data(ANL, 10) |
463 | ! |
validate(need( |
464 | ! |
na_action != "none" | !anyNA(ANL[keep_cols]), |
465 | ! |
paste( |
466 | ! |
"There are NAs in the dataset. Please deal with them in preprocessing", |
467 | ! |
"or select \"Drop\" in the NA actions inside the encodings panel (left)." |
468 |
) |
|
469 |
)) |
|
470 | ! |
if (scale) { |
471 | ! |
not_single <- vapply(ANL[keep_cols], function(column) length(unique(column)) != 1, FUN.VALUE = logical(1)) |
472 | ||
473 | ! |
msg <- paste0( |
474 | ! |
"You have selected `Center & Scale` under `Standardization` in the `Pre-processing` panel, ", |
475 | ! |
"but one or more of your columns has/have a variance value of zero, indicating all values are identical" |
476 |
) |
|
477 | ! |
validate(need(all(not_single), msg)) |
478 |
} |
|
479 |
}) |
|
480 | ||
481 |
# computation ---- |
|
482 | ! |
computation <- reactive({ |
483 | ! |
validation() |
484 | ||
485 |
# inputs |
|
486 | ! |
keep_cols <- as.character(merged$anl_input_r()$columns_source$dat) |
487 | ! |
na_action <- input$na_action |
488 | ! |
standardization <- input$standardization |
489 | ! |
center <- standardization %in% c("center", "center_scale") |
490 | ! |
scale <- standardization == "center_scale" |
491 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
492 | ||
493 | ! |
qenv <- teal.code::eval_code( |
494 | ! |
merged$anl_q_r(), |
495 | ! |
substitute( |
496 | ! |
expr = keep_columns <- keep_cols, |
497 | ! |
env = list(keep_cols = keep_cols) |
498 |
) |
|
499 |
) |
|
500 | ||
501 | ! |
if (na_action == "drop") { |
502 | ! |
qenv <- teal.code::eval_code( |
503 | ! |
qenv, |
504 | ! |
quote(ANL <- tidyr::drop_na(ANL, keep_columns)) |
505 |
) |
|
506 |
} |
|
507 | ||
508 | ! |
qenv <- teal.code::eval_code( |
509 | ! |
qenv, |
510 | ! |
substitute( |
511 | ! |
expr = pca <- summary(stats::prcomp(ANL[keep_columns], center = center, scale. = scale, retx = TRUE)), |
512 | ! |
env = list(center = center, scale = scale) |
513 |
) |
|
514 |
) |
|
515 | ||
516 | ! |
qenv <- teal.code::eval_code( |
517 | ! |
qenv, |
518 | ! |
quote({ |
519 | ! |
tbl_importance <- dplyr::as_tibble(pca$importance, rownames = "Metric") |
520 | ! |
tbl_importance |
521 |
}) |
|
522 |
) |
|
523 | ||
524 | ! |
teal.code::eval_code( |
525 | ! |
qenv, |
526 | ! |
quote({ |
527 | ! |
tbl_eigenvector <- dplyr::as_tibble(pca$rotation, rownames = "Variable") |
528 | ! |
tbl_eigenvector |
529 |
}) |
|
530 |
) |
|
531 |
}) |
|
532 | ||
533 |
# plot args ---- |
|
534 | ! |
output$plot_settings <- renderUI({ |
535 |
# reactivity triggers |
|
536 | ! |
req(iv_r()$is_valid()) |
537 | ! |
req(computation()) |
538 | ! |
qenv <- computation() |
539 | ||
540 | ! |
ns <- session$ns |
541 | ||
542 | ! |
pca <- qenv[["pca"]] |
543 | ! |
chcs_pcs <- colnames(pca$rotation) |
544 | ! |
chcs_vars <- qenv[["keep_columns"]] |
545 | ||
546 | ! |
tagList( |
547 | ! |
conditionalPanel( |
548 | ! |
condition = sprintf( |
549 | ! |
"input['%s'] == 'Biplot' || input['%s'] == 'Circle plot'", |
550 | ! |
ns("plot_type"), ns("plot_type") |
551 |
), |
|
552 | ! |
list( |
553 | ! |
teal.widgets::optionalSelectInput(ns("x_axis"), "X axis", choices = chcs_pcs, selected = chcs_pcs[1]), |
554 | ! |
teal.widgets::optionalSelectInput(ns("y_axis"), "Y axis", choices = chcs_pcs, selected = chcs_pcs[2]), |
555 | ! |
teal.widgets::optionalSelectInput( |
556 | ! |
ns("variables"), "Original coordinates", |
557 | ! |
choices = chcs_vars, selected = chcs_vars, |
558 | ! |
multiple = TRUE |
559 |
) |
|
560 |
) |
|
561 |
), |
|
562 | ! |
conditionalPanel( |
563 | ! |
condition = sprintf("input['%s'] == 'Elbow plot'", ns("plot_type")), |
564 | ! |
helpText("No plot specific settings available.") |
565 |
), |
|
566 | ! |
conditionalPanel( |
567 | ! |
condition = paste0("input['", ns("plot_type"), "'] == 'Eigenvector plot'"), |
568 | ! |
teal.widgets::optionalSelectInput(ns("pc"), "PC", choices = chcs_pcs, selected = chcs_pcs[1]) |
569 |
) |
|
570 |
) |
|
571 |
}) |
|
572 | ||
573 |
# plot elbow ---- |
|
574 | ! |
plot_elbow <- function(base_q) { |
575 | ! |
ggtheme <- input$ggtheme |
576 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
577 | ! |
font_size <- input$font_size |
578 | ||
579 | ! |
angle_value <- ifelse(isTRUE(rotate_xaxis_labels), 45, 0) |
580 | ! |
hjust_value <- ifelse(isTRUE(rotate_xaxis_labels), 1, 0.5) |
581 | ||
582 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
583 | ! |
labs = list(x = "Principal component", y = "Proportion of variance explained", color = "", fill = "Legend"), |
584 | ! |
theme = list( |
585 | ! |
legend.position = "right", |
586 | ! |
legend.spacing.y = quote(grid::unit(-5, "pt")), |
587 | ! |
legend.title = quote(element_text(vjust = 25)), |
588 | ! |
axis.text.x = substitute( |
589 | ! |
element_text(angle = angle_value, hjust = hjust_value), |
590 | ! |
list(angle_value = angle_value, hjust_value = hjust_value) |
591 |
), |
|
592 | ! |
text = substitute(element_text(size = font_size), list(font_size = font_size)) |
593 |
) |
|
594 |
) |
|
595 | ||
596 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
597 | ! |
teal.widgets::resolve_ggplot2_args( |
598 | ! |
user_plot = ggplot2_args[["Elbow plot"]], |
599 | ! |
user_default = ggplot2_args$default, |
600 | ! |
module_plot = dev_ggplot2_args |
601 |
), |
|
602 | ! |
ggtheme = ggtheme |
603 |
) |
|
604 | ||
605 | ! |
teal.code::eval_code( |
606 | ! |
base_q, |
607 | ! |
substitute( |
608 | ! |
expr = { |
609 | ! |
elb_dat <- pca$importance[c("Proportion of Variance", "Cumulative Proportion"), ] %>% |
610 | ! |
dplyr::as_tibble(rownames = "metric") %>% |
611 | ! |
tidyr::gather("component", "value", -metric) %>% |
612 | ! |
dplyr::mutate( |
613 | ! |
component = factor(component, levels = unique(stringr::str_sort(component, numeric = TRUE))) |
614 |
) |
|
615 | ||
616 | ! |
cols <- c(getOption("ggplot2.discrete.colour"), c("lightblue", "darkred", "black"))[1:3] |
617 | ! |
elbow_plot <- ggplot(mapping = aes_string(x = "component", y = "value")) + |
618 | ! |
geom_bar( |
619 | ! |
aes(fill = "Single variance"), |
620 | ! |
data = dplyr::filter(elb_dat, metric == "Proportion of Variance"), |
621 | ! |
color = "black", |
622 | ! |
stat = "identity" |
623 |
) + |
|
624 | ! |
geom_point( |
625 | ! |
aes(color = "Cumulative variance"), |
626 | ! |
data = dplyr::filter(elb_dat, metric == "Cumulative Proportion") |
627 |
) + |
|
628 | ! |
geom_line( |
629 | ! |
aes(group = 1, color = "Cumulative variance"), |
630 | ! |
data = dplyr::filter(elb_dat, metric == "Cumulative Proportion") |
631 |
) + |
|
632 | ! |
labs + |
633 | ! |
scale_color_manual(values = c("Cumulative variance" = cols[2], "Single variance" = cols[3])) + |
634 | ! |
scale_fill_manual(values = c("Cumulative variance" = cols[2], "Single variance" = cols[1])) + |
635 | ! |
ggthemes + |
636 | ! |
themes |
637 |
}, |
|
638 | ! |
env = list( |
639 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
640 | ! |
labs = parsed_ggplot2_args$labs, |
641 | ! |
themes = parsed_ggplot2_args$theme |
642 |
) |
|
643 |
) |
|
644 |
) |
|
645 |
} |
|
646 | ||
647 |
# plot circle ---- |
|
648 | ! |
plot_circle <- function(base_q) { |
649 | ! |
x_axis <- input$x_axis |
650 | ! |
y_axis <- input$y_axis |
651 | ! |
variables <- input$variables |
652 | ! |
ggtheme <- input$ggtheme |
653 | ||
654 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
655 | ! |
font_size <- input$font_size |
656 | ||
657 | ! |
angle <- ifelse(isTRUE(rotate_xaxis_labels), 45, 0) |
658 | ! |
hjust <- ifelse(isTRUE(rotate_xaxis_labels), 1, 0.5) |
659 | ||
660 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
661 | ! |
theme = list( |
662 | ! |
text = substitute(element_text(size = font_size), list(font_size = font_size)), |
663 | ! |
axis.text.x = substitute( |
664 | ! |
element_text(angle = angle_val, hjust = hjust_val), |
665 | ! |
list(angle_val = angle, hjust_val = hjust) |
666 |
) |
|
667 |
) |
|
668 |
) |
|
669 | ||
670 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
671 | ! |
user_plot = ggplot2_args[["Circle plot"]], |
672 | ! |
user_default = ggplot2_args$default, |
673 | ! |
module_plot = dev_ggplot2_args |
674 |
) |
|
675 | ||
676 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
677 | ! |
all_ggplot2_args, |
678 | ! |
ggtheme = ggtheme |
679 |
) |
|
680 | ||
681 | ! |
teal.code::eval_code( |
682 | ! |
base_q, |
683 | ! |
substitute( |
684 | ! |
expr = { |
685 | ! |
pca_rot <- pca$rotation[, c(x_axis, y_axis)] %>% |
686 | ! |
dplyr::as_tibble(rownames = "label") %>% |
687 | ! |
dplyr::filter(label %in% variables) |
688 | ||
689 | ! |
circle_data <- data.frame( |
690 | ! |
x = cos(seq(0, 2 * pi, length.out = 100)), |
691 | ! |
y = sin(seq(0, 2 * pi, length.out = 100)) |
692 |
) |
|
693 | ||
694 | ! |
circle_plot <- ggplot(pca_rot) + |
695 | ! |
geom_point(aes_string(x = x_axis, y = y_axis)) + |
696 | ! |
geom_label( |
697 | ! |
aes_string(x = x_axis, y = y_axis, label = "label"), |
698 | ! |
nudge_x = 0.1, nudge_y = 0.05, |
699 | ! |
fontface = "bold" |
700 |
) + |
|
701 | ! |
geom_path(aes(x, y, group = 1), data = circle_data) + |
702 | ! |
geom_point(aes(x = x, y = y), data = data.frame(x = 0, y = 0), shape = "x", size = 5) + |
703 | ! |
labs + |
704 | ! |
ggthemes + |
705 | ! |
themes |
706 |
}, |
|
707 | ! |
env = list( |
708 | ! |
x_axis = x_axis, |
709 | ! |
y_axis = y_axis, |
710 | ! |
variables = variables, |
711 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
712 | ! |
labs = `if`(is.null(parsed_ggplot2_args$labs), quote(labs()), parsed_ggplot2_args$labs), |
713 | ! |
themes = parsed_ggplot2_args$theme |
714 |
) |
|
715 |
) |
|
716 |
) |
|
717 |
} |
|
718 | ||
719 |
# plot biplot ---- |
|
720 | ! |
plot_biplot <- function(base_q) { |
721 | ! |
qenv <- base_q |
722 | ||
723 | ! |
ANL <- qenv[["ANL"]] |
724 | ||
725 | ! |
resp_col <- as.character(merged$anl_input_r()$columns_source$response) |
726 | ! |
dat_cols <- as.character(merged$anl_input_r()$columns_source$dat) |
727 | ! |
x_axis <- input$x_axis |
728 | ! |
y_axis <- input$y_axis |
729 | ! |
variables <- input$variables |
730 | ! |
pca <- qenv[["pca"]] |
731 | ||
732 | ! |
ggtheme <- input$ggtheme |
733 | ||
734 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
735 | ! |
alpha <- input$alpha |
736 | ! |
size <- input$size |
737 | ! |
font_size <- input$font_size |
738 | ||
739 | ! |
qenv <- teal.code::eval_code( |
740 | ! |
qenv, |
741 | ! |
substitute( |
742 | ! |
expr = pca_rot <- dplyr::as_tibble(pca$x[, c(x_axis, y_axis)]), |
743 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
744 |
) |
|
745 |
) |
|
746 | ||
747 |
# rot_vars = data frame that displays arrows in the plot, need to be scaled to data |
|
748 | ! |
if (!is.null(input$variables)) { |
749 | ! |
qenv <- teal.code::eval_code( |
750 | ! |
qenv, |
751 | ! |
substitute( |
752 | ! |
expr = { |
753 | ! |
r <- sqrt(qchisq(0.69, df = 2)) * prod(colMeans(pca_rot ^ 2)) ^ (1 / 4) # styler: off |
754 | ! |
v_scale <- rowSums(pca$rotation ^ 2) # styler: off |
755 | ||
756 | ! |
rot_vars <- pca$rotation[, c(x_axis, y_axis)] %>% |
757 | ! |
dplyr::as_tibble(rownames = "label") %>% |
758 | ! |
dplyr::mutate_at(vars(c(x_axis, y_axis)), function(x) r * x / sqrt(max(v_scale))) |
759 |
}, |
|
760 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
761 |
) |
|
762 |
) %>% |
|
763 | ! |
teal.code::eval_code( |
764 | ! |
if (is.logical(pca$center) && !pca$center) { |
765 | ! |
substitute( |
766 | ! |
expr = { |
767 | ! |
rot_vars <- rot_vars %>% |
768 | ! |
tibble::column_to_rownames("label") %>% |
769 | ! |
sweep(1, apply(ANL[keep_columns], 2, mean, na.rm = TRUE)) %>% |
770 | ! |
tibble::rownames_to_column("label") %>% |
771 | ! |
dplyr::mutate( |
772 | ! |
xstart = mean(pca$x[, x_axis], na.rm = TRUE), |
773 | ! |
ystart = mean(pca$x[, y_axis], na.rm = TRUE) |
774 |
) |
|
775 |
}, |
|
776 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
777 |
) |
|
778 |
} else { |
|
779 | ! |
quote(rot_vars <- rot_vars %>% dplyr::mutate(xstart = 0, ystart = 0)) |
780 |
} |
|
781 |
) %>% |
|
782 | ! |
teal.code::eval_code( |
783 | ! |
substitute( |
784 | ! |
expr = rot_vars <- rot_vars %>% dplyr::filter(label %in% variables), |
785 | ! |
env = list(variables = variables) |
786 |
) |
|
787 |
) |
|
788 |
} |
|
789 | ||
790 | ! |
pca_plot_biplot_expr <- list(quote(ggplot())) |
791 | ||
792 | ! |
if (length(resp_col) == 0) { |
793 | ! |
pca_plot_biplot_expr <- c( |
794 | ! |
pca_plot_biplot_expr, |
795 | ! |
substitute( |
796 | ! |
geom_point(aes_string(x = x_axis, y = y_axis), data = pca_rot, alpha = alpha, size = size), |
797 | ! |
list(x_axis = input$x_axis, y_axis = input$y_axis, alpha = input$alpha, size = input$size) |
798 |
) |
|
799 |
) |
|
800 | ! |
dev_labs <- list() |
801 |
} else { |
|
802 | ! |
rp_keys <- setdiff(colnames(ANL), as.character(unlist(merged$anl_input_r()$columns_source))) |
803 | ||
804 | ! |
response <- ANL[[resp_col]] |
805 | ||
806 | ! |
aes_biplot <- substitute( |
807 | ! |
aes_string(x = x_axis, y = y_axis, color = "response"), |
808 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
809 |
) |
|
810 | ||
811 | ! |
qenv <- teal.code::eval_code( |
812 | ! |
qenv, |
813 | ! |
substitute(response <- ANL[[resp_col]], env = list(resp_col = resp_col)) |
814 |
) |
|
815 | ||
816 | ! |
dev_labs <- list(color = varname_w_label(resp_col, ANL)) |
817 | ||
818 | ! |
scales_biplot <- |
819 | ! |
if ( |
820 | ! |
is.character(response) || |
821 | ! |
is.factor(response) || |
822 | ! |
(is.numeric(response) && length(unique(response)) <= 6) |
823 |
) { |
|
824 | ! |
qenv <- teal.code::eval_code( |
825 | ! |
qenv, |
826 | ! |
quote(pca_rot$response <- as.factor(response)) |
827 |
) |
|
828 | ! |
quote(scale_color_brewer(palette = "Dark2")) |
829 | ! |
} else if (inherits(response, "Date")) { |
830 | ! |
qenv <- teal.code::eval_code( |
831 | ! |
qenv, |
832 | ! |
quote(pca_rot$response <- numeric(response)) |
833 |
) |
|
834 | ||
835 | ! |
quote( |
836 | ! |
scale_color_gradient( |
837 | ! |
low = c(getOption("ggplot2.discrete.colour")[2], "darkred")[1], |
838 | ! |
high = c(getOption("ggplot2.discrete.colour"), "lightblue")[1], |
839 | ! |
labels = function(x) as.Date(x, origin = "1970-01-01") |
840 |
) |
|
841 |
) |
|
842 |
} else { |
|
843 | ! |
qenv <- teal.code::eval_code( |
844 | ! |
qenv, |
845 | ! |
quote(pca_rot$response <- response) |
846 |
) |
|
847 | ! |
quote(scale_color_gradient( |
848 | ! |
low = c(getOption("ggplot2.discrete.colour")[2], "darkred")[1], |
849 | ! |
high = c(getOption("ggplot2.discrete.colour"), "lightblue")[1] |
850 |
)) |
|
851 |
} |
|
852 | ||
853 | ! |
pca_plot_biplot_expr <- c( |
854 | ! |
pca_plot_biplot_expr, |
855 | ! |
substitute( |
856 | ! |
geom_point(aes_biplot, data = pca_rot, alpha = alpha, size = size), |
857 | ! |
env = list(aes_biplot = aes_biplot, alpha = alpha, size = size) |
858 |
), |
|
859 | ! |
scales_biplot |
860 |
) |
|
861 |
} |
|
862 | ||
863 | ! |
if (!is.null(input$variables)) { |
864 | ! |
pca_plot_biplot_expr <- c( |
865 | ! |
pca_plot_biplot_expr, |
866 | ! |
substitute( |
867 | ! |
geom_segment( |
868 | ! |
aes_string(x = "xstart", y = "ystart", xend = x_axis, yend = y_axis), |
869 | ! |
data = rot_vars, |
870 | ! |
lineend = "round", linejoin = "round", |
871 | ! |
arrow = grid::arrow(length = grid::unit(0.5, "cm")) |
872 |
), |
|
873 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
874 |
), |
|
875 | ! |
substitute( |
876 | ! |
geom_label( |
877 | ! |
aes_string( |
878 | ! |
x = x_axis, |
879 | ! |
y = y_axis, |
880 | ! |
label = "label" |
881 |
), |
|
882 | ! |
data = rot_vars, |
883 | ! |
nudge_y = 0.1, |
884 | ! |
fontface = "bold" |
885 |
), |
|
886 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
887 |
), |
|
888 | ! |
quote(geom_point(aes(x = xstart, y = ystart), data = rot_vars, shape = "x", size = 5)) |
889 |
) |
|
890 |
} |
|
891 | ||
892 | ! |
angle <- ifelse(isTRUE(rotate_xaxis_labels), 45, 0) |
893 | ! |
hjust <- ifelse(isTRUE(rotate_xaxis_labels), 1, 0.5) |
894 | ||
895 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
896 | ! |
labs = dev_labs, |
897 | ! |
theme = list( |
898 | ! |
text = substitute(element_text(size = font_size), list(font_size = font_size)), |
899 | ! |
axis.text.x = substitute( |
900 | ! |
element_text(angle = angle_val, hjust = hjust_val), |
901 | ! |
list(angle_val = angle, hjust_val = hjust) |
902 |
) |
|
903 |
) |
|
904 |
) |
|
905 | ||
906 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
907 | ! |
user_plot = ggplot2_args[["Biplot"]], |
908 | ! |
user_default = ggplot2_args$default, |
909 | ! |
module_plot = dev_ggplot2_args |
910 |
) |
|
911 | ||
912 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
913 | ! |
all_ggplot2_args, |
914 | ! |
ggtheme = ggtheme |
915 |
) |
|
916 | ||
917 | ! |
pca_plot_biplot_expr <- c( |
918 | ! |
pca_plot_biplot_expr, |
919 | ! |
parsed_ggplot2_args |
920 |
) |
|
921 | ||
922 | ! |
teal.code::eval_code( |
923 | ! |
qenv, |
924 | ! |
substitute( |
925 | ! |
expr = { |
926 | ! |
biplot <- plot_call |
927 |
}, |
|
928 | ! |
env = list( |
929 | ! |
plot_call = Reduce(function(x, y) call("+", x, y), pca_plot_biplot_expr) |
930 |
) |
|
931 |
) |
|
932 |
) |
|
933 |
} |
|
934 | ||
935 |
# plot eigenvector_plot ---- |
|
936 | ! |
plot_eigenvector <- function(base_q) { |
937 | ! |
pc <- input$pc |
938 | ! |
ggtheme <- input$ggtheme |
939 | ||
940 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
941 | ! |
font_size <- input$font_size |
942 | ||
943 | ! |
angle <- ifelse(rotate_xaxis_labels, 45, 0) |
944 | ! |
hjust <- ifelse(rotate_xaxis_labels, 1, 0.5) |
945 | ||
946 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
947 | ! |
theme = list( |
948 | ! |
text = substitute(element_text(size = font_size), list(font_size = font_size)), |
949 | ! |
axis.text.x = substitute( |
950 | ! |
element_text(angle = angle_val, hjust = hjust_val), |
951 | ! |
list(angle_val = angle, hjust_val = hjust) |
952 |
) |
|
953 |
) |
|
954 |
) |
|
955 | ||
956 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
957 | ! |
user_plot = ggplot2_args[["Eigenvector plot"]], |
958 | ! |
user_default = ggplot2_args$default, |
959 | ! |
module_plot = dev_ggplot2_args |
960 |
) |
|
961 | ||
962 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
963 | ! |
all_ggplot2_args, |
964 | ! |
ggtheme = ggtheme |
965 |
) |
|
966 | ||
967 | ! |
ggplot_exprs <- c( |
968 | ! |
list( |
969 | ! |
quote(ggplot(pca_rot)), |
970 | ! |
substitute( |
971 | ! |
geom_bar( |
972 | ! |
aes_string(x = "Variable", y = pc), |
973 | ! |
stat = "identity", |
974 | ! |
color = "black", |
975 | ! |
fill = c(getOption("ggplot2.discrete.colour"), "lightblue")[1] |
976 |
), |
|
977 | ! |
env = list(pc = pc) |
978 |
), |
|
979 | ! |
substitute( |
980 | ! |
geom_text( |
981 | ! |
aes( |
982 | ! |
x = Variable, |
983 | ! |
y = pc_name, |
984 | ! |
label = round(pc_name, 3), |
985 | ! |
vjust = ifelse(pc_name > 0, -0.5, 1.3) |
986 |
) |
|
987 |
), |
|
988 | ! |
env = list(pc_name = as.name(pc)) |
989 |
) |
|
990 |
), |
|
991 | ! |
parsed_ggplot2_args$labs, |
992 | ! |
parsed_ggplot2_args$ggtheme, |
993 | ! |
parsed_ggplot2_args$theme |
994 |
) |
|
995 | ||
996 | ! |
teal.code::eval_code( |
997 | ! |
base_q, |
998 | ! |
substitute( |
999 | ! |
expr = { |
1000 | ! |
pca_rot <- pca$rotation[, pc, drop = FALSE] %>% |
1001 | ! |
dplyr::as_tibble(rownames = "Variable") |
1002 | ! |
eigenvector_plot <- plot_call |
1003 |
}, |
|
1004 | ! |
env = list( |
1005 | ! |
pc = pc, |
1006 | ! |
plot_call = Reduce(function(x, y) call("+", x, y), ggplot_exprs) |
1007 |
) |
|
1008 |
) |
|
1009 |
) |
|
1010 |
} |
|
1011 | ||
1012 |
# qenvs --- |
|
1013 | ! |
output_q <- lapply( |
1014 | ! |
list( |
1015 | ! |
elbow_plot = plot_elbow, |
1016 | ! |
circle_plot = plot_circle, |
1017 | ! |
biplot = plot_biplot, |
1018 | ! |
eigenvector_plot = plot_eigenvector |
1019 |
), |
|
1020 | ! |
function(fun) { |
1021 | ! |
reactive({ |
1022 | ! |
req(computation()) |
1023 | ! |
teal::validate_inputs(iv_r()) |
1024 | ! |
teal::validate_inputs(iv_extra, header = "Plot settings are required") |
1025 | ! |
fun(computation()) |
1026 |
}) |
|
1027 |
} |
|
1028 |
) |
|
1029 | ||
1030 | ! |
decorated_q <- mapply( |
1031 | ! |
function(obj_name, q) { |
1032 | ! |
srv_decorate_teal_data( |
1033 | ! |
id = sprintf("d_%s", obj_name), |
1034 | ! |
data = q, |
1035 | ! |
decorators = select_decorators(decorators, obj_name), |
1036 | ! |
expr = reactive({ |
1037 | ! |
substitute(print(.plot), env = list(.plot = as.name(obj_name))) |
1038 |
}), |
|
1039 | ! |
expr_is_reactive = TRUE |
1040 |
) |
|
1041 |
}, |
|
1042 | ! |
names(output_q), |
1043 | ! |
output_q |
1044 |
) |
|
1045 | ||
1046 |
# plot final ---- |
|
1047 | ! |
decorated_output_q <- reactive({ |
1048 | ! |
switch(req(input$plot_type), |
1049 | ! |
"Elbow plot" = decorated_q$elbow_plot(), |
1050 | ! |
"Circle plot" = decorated_q$circle_plot(), |
1051 | ! |
"Biplot" = decorated_q$biplot(), |
1052 | ! |
"Eigenvector plot" = decorated_q$eigenvector_plot(), |
1053 | ! |
stop("Unknown plot") |
1054 |
) |
|
1055 |
}) |
|
1056 | ||
1057 | ! |
plot_r <- reactive({ |
1058 | ! |
plot_name <- gsub(" ", "_", tolower(req(input$plot_type))) |
1059 | ! |
req(decorated_output_q())[[plot_name]] |
1060 |
}) |
|
1061 | ||
1062 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
1063 | ! |
id = "pca_plot", |
1064 | ! |
plot_r = plot_r, |
1065 | ! |
height = plot_height, |
1066 | ! |
width = plot_width, |
1067 | ! |
graph_align = "center" |
1068 |
) |
|
1069 | ||
1070 |
# tables ---- |
|
1071 | ! |
output$tbl_importance <- renderTable( |
1072 | ! |
expr = { |
1073 | ! |
req("importance" %in% input$tables_display, computation()) |
1074 | ! |
computation()[["tbl_importance"]] |
1075 |
}, |
|
1076 | ! |
bordered = TRUE, |
1077 | ! |
align = "c", |
1078 | ! |
digits = 3 |
1079 |
) |
|
1080 | ||
1081 | ! |
output$tbl_importance_ui <- renderUI({ |
1082 | ! |
req("importance" %in% input$tables_display) |
1083 | ! |
tags$div( |
1084 | ! |
align = "center", |
1085 | ! |
tags$h4("Principal components importance"), |
1086 | ! |
tableOutput(session$ns("tbl_importance")), |
1087 | ! |
tags$hr() |
1088 |
) |
|
1089 |
}) |
|
1090 | ||
1091 | ! |
output$tbl_eigenvector <- renderTable( |
1092 | ! |
expr = { |
1093 | ! |
req("eigenvector" %in% input$tables_display, req(computation())) |
1094 | ! |
computation()[["tbl_eigenvector"]] |
1095 |
}, |
|
1096 | ! |
bordered = TRUE, |
1097 | ! |
align = "c", |
1098 | ! |
digits = 3 |
1099 |
) |
|
1100 | ||
1101 | ! |
output$tbl_eigenvector_ui <- renderUI({ |
1102 | ! |
req("eigenvector" %in% input$tables_display) |
1103 | ! |
tags$div( |
1104 | ! |
align = "center", |
1105 | ! |
tags$h4("Eigenvectors"), |
1106 | ! |
tableOutput(session$ns("tbl_eigenvector")), |
1107 | ! |
tags$hr() |
1108 |
) |
|
1109 |
}) |
|
1110 | ||
1111 | ! |
output$all_plots <- renderUI({ |
1112 | ! |
teal::validate_inputs(iv_r()) |
1113 | ! |
teal::validate_inputs(iv_extra, header = "Plot settings are required") |
1114 | ||
1115 | ! |
validation() |
1116 | ! |
tags$div( |
1117 | ! |
class = "overflow-scroll", |
1118 | ! |
uiOutput(session$ns("tbl_importance_ui")), |
1119 | ! |
uiOutput(session$ns("tbl_eigenvector_ui")), |
1120 | ! |
teal.widgets::plot_with_settings_ui(id = session$ns("pca_plot")) |
1121 |
) |
|
1122 |
}) |
|
1123 | ||
1124 | ! |
teal.widgets::verbatim_popup_srv( |
1125 | ! |
id = "rcode", |
1126 | ! |
verbatim_content = reactive(teal.code::get_code(req(decorated_output_q()))), |
1127 | ! |
title = "R Code for PCA" |
1128 |
) |
|
1129 | ||
1130 |
### REPORTER |
|
1131 | ! |
if (with_reporter) { |
1132 | ! |
card_fun <- function(comment, label) { |
1133 | ! |
card <- teal::report_card_template( |
1134 | ! |
title = "Principal Component Analysis Plot", |
1135 | ! |
label = label, |
1136 | ! |
with_filter = with_filter, |
1137 | ! |
filter_panel_api = filter_panel_api |
1138 |
) |
|
1139 | ! |
card$append_text("Principal Components Table", "header3") |
1140 | ! |
card$append_table(computation()[["tbl_importance"]]) |
1141 | ! |
card$append_text("Eigenvectors Table", "header3") |
1142 | ! |
card$append_table(computation()[["tbl_eigenvector"]]) |
1143 | ! |
card$append_text("Plot", "header3") |
1144 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
1145 | ! |
if (!comment == "") { |
1146 | ! |
card$append_text("Comment", "header3") |
1147 | ! |
card$append_text(comment) |
1148 |
} |
|
1149 | ! |
card$append_src(teal.code::get_code(req(decorated_output_q()))) |
1150 | ! |
card |
1151 |
} |
|
1152 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
1153 |
} |
|
1154 |
### |
|
1155 |
}) |
|
1156 |
} |
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 |
#' @param decorators `r roxygen_decorators_param("tm_outliers")` |
|
16 |
#' |
|
17 |
#' @inherit shared_params return |
|
18 |
#' |
|
19 |
#' @section Decorating `tm_outliers`: |
|
20 |
#' |
|
21 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
22 |
#' - `box_plot` (`ggplot2`) |
|
23 |
#' - `density_plot` (`ggplot2`) |
|
24 |
#' - `cumulative_plot` (`ggplot2`) |
|
25 |
#' - `table` ([DT::datatable()]) |
|
26 |
#' |
|
27 |
#' Decorators can be applied to all outputs or only to specific objects using a |
|
28 |
#' named list of `teal_transform_module` objects. |
|
29 |
#' The `"default"` name is reserved for decorators that are applied to all outputs. |
|
30 |
#' See code snippet below: |
|
31 |
#' |
|
32 |
#' ``` |
|
33 |
#' tm_outliers( |
|
34 |
#' ..., # arguments for module |
|
35 |
#' decorators = list( |
|
36 |
#' default = list(teal_transform_module(...)), # applied to all outputs |
|
37 |
#' box_plot = list(teal_transform_module(...)), # applied only to `box_plot` output |
|
38 |
#' density_plot = list(teal_transform_module(...)) # applied only to `density_plot` output |
|
39 |
#' cumulative_plot = list(teal_transform_module(...)) # applied only to `cumulative_plot` output |
|
40 |
#' table = list(teal_transform_module(...)) # applied only to `table` output |
|
41 |
#' ) |
|
42 |
#' ) |
|
43 |
#' ``` |
|
44 |
#' |
|
45 |
#' For additional details and examples of decorators, refer to the vignette |
|
46 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
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 |
decorators = NULL) { |
|
162 | ! |
message("Initializing tm_outliers") |
163 | ||
164 |
# Normalize the parameters |
|
165 | ! |
if (inherits(outlier_var, "data_extract_spec")) outlier_var <- list(outlier_var) |
166 | ! |
if (inherits(categorical_var, "data_extract_spec")) categorical_var <- list(categorical_var) |
167 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
168 | ||
169 |
# Start of assertions |
|
170 | ! |
checkmate::assert_string(label) |
171 | ! |
checkmate::assert_list(outlier_var, types = "data_extract_spec") |
172 | ||
173 | ! |
checkmate::assert_list(categorical_var, types = "data_extract_spec", null.ok = TRUE) |
174 | ! |
if (is.list(categorical_var)) { |
175 | ! |
lapply(categorical_var, function(x) { |
176 | ! |
if (length(x$filter) > 1L) { |
177 | ! |
stop("tm_outliers: categorical_var data_extract_specs may only specify one filter_spec", call. = FALSE) |
178 |
} |
|
179 |
}) |
|
180 |
} |
|
181 | ||
182 | ! |
ggtheme <- match.arg(ggtheme) |
183 | ||
184 | ! |
plot_choices <- c("Boxplot", "Density Plot", "Cumulative Distribution Plot") |
185 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
186 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
187 | ||
188 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
189 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
190 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
191 | ! |
checkmate::assert_numeric( |
192 | ! |
plot_width[1], |
193 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
194 |
) |
|
195 | ||
196 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
197 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
198 | ||
199 | ! |
available_decorators <- c("box_plot", "density_plot", "cumulative_plot", "table") |
200 | ! |
decorators <- normalize_decorators(decorators) |
201 | ! |
assert_decorators(decorators, null.ok = TRUE, names = available_decorators) |
202 |
# End of assertions |
|
203 | ||
204 |
# Make UI args |
|
205 | ! |
args <- as.list(environment()) |
206 | ||
207 | ! |
data_extract_list <- list( |
208 | ! |
outlier_var = outlier_var, |
209 | ! |
categorical_var = categorical_var |
210 |
) |
|
211 | ||
212 | ||
213 | ! |
ans <- module( |
214 | ! |
label = label, |
215 | ! |
server = srv_outliers, |
216 | ! |
server_args = c( |
217 | ! |
data_extract_list, |
218 | ! |
list( |
219 | ! |
plot_height = plot_height, plot_width = plot_width, ggplot2_args = ggplot2_args, |
220 | ! |
decorators = decorators |
221 |
) |
|
222 |
), |
|
223 | ! |
ui = ui_outliers, |
224 | ! |
ui_args = args, |
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 | ! |
DT::dataTableOutput(ns("summary_table")), |
241 | ! |
uiOutput(ns("total_missing")), |
242 | ! |
tags$br(), tags$hr(), |
243 | ! |
tabsetPanel( |
244 | ! |
id = ns("tabs"), |
245 | ! |
tabPanel( |
246 | ! |
"Boxplot", |
247 | ! |
teal.widgets::plot_with_settings_ui(id = ns("box_plot")) |
248 |
), |
|
249 | ! |
tabPanel( |
250 | ! |
"Density Plot", |
251 | ! |
teal.widgets::plot_with_settings_ui(id = ns("density_plot")) |
252 |
), |
|
253 | ! |
tabPanel( |
254 | ! |
"Cumulative Distribution Plot", |
255 | ! |
teal.widgets::plot_with_settings_ui(id = ns("cum_density_plot")) |
256 |
) |
|
257 |
), |
|
258 | ! |
tags$br(), tags$hr(), |
259 | ! |
uiOutput(ns("table_ui_wrap")), |
260 | ! |
DT::dataTableOutput(ns("table_ui")) |
261 |
), |
|
262 | ! |
encoding = tags$div( |
263 |
### Reporter |
|
264 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
265 |
### |
|
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 | ! |
teal.widgets::panel_group( |
295 | ! |
teal.widgets::panel_item( |
296 | ! |
title = "Method parameters", |
297 | ! |
collapsed = FALSE, |
298 | ! |
teal.widgets::optionalSelectInput( |
299 | ! |
inputId = ns("method"), |
300 | ! |
label = "Method", |
301 | ! |
choices = c("IQR", "Z-score", "Percentile"), |
302 | ! |
selected = "IQR", |
303 | ! |
multiple = FALSE |
304 |
), |
|
305 | ! |
conditionalPanel( |
306 | ! |
condition = |
307 | ! |
paste0("input['", ns("method"), "'] == 'IQR'"), |
308 | ! |
sliderInput( |
309 | ! |
ns("iqr_slider"), |
310 | ! |
"Outlier range:", |
311 | ! |
min = 1, |
312 | ! |
max = 5, |
313 | ! |
value = 3, |
314 | ! |
step = 0.5 |
315 |
) |
|
316 |
), |
|
317 | ! |
conditionalPanel( |
318 | ! |
condition = |
319 | ! |
paste0("input['", ns("method"), "'] == 'Z-score'"), |
320 | ! |
sliderInput( |
321 | ! |
ns("zscore_slider"), |
322 | ! |
"Outlier range:", |
323 | ! |
min = 1, |
324 | ! |
max = 5, |
325 | ! |
value = 3, |
326 | ! |
step = 0.5 |
327 |
) |
|
328 |
), |
|
329 | ! |
conditionalPanel( |
330 | ! |
condition = |
331 | ! |
paste0("input['", ns("method"), "'] == 'Percentile'"), |
332 | ! |
sliderInput( |
333 | ! |
ns("percentile_slider"), |
334 | ! |
"Outlier range:", |
335 | ! |
min = 0.001, |
336 | ! |
max = 0.5, |
337 | ! |
value = 0.01, |
338 | ! |
step = 0.001 |
339 |
) |
|
340 |
), |
|
341 | ! |
uiOutput(ns("ui_outlier_help")) |
342 |
) |
|
343 |
), |
|
344 | ! |
conditionalPanel( |
345 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'Boxplot'"), |
346 | ! |
ui_decorate_teal_data( |
347 | ! |
ns("d_box_plot"), |
348 | ! |
decorators = select_decorators(args$decorators, "box_plot") |
349 |
) |
|
350 |
), |
|
351 | ! |
conditionalPanel( |
352 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'Density Plot'"), |
353 | ! |
ui_decorate_teal_data( |
354 | ! |
ns("d_density_plot"), |
355 | ! |
decorators = select_decorators(args$decorators, "density_plot") |
356 |
) |
|
357 |
), |
|
358 | ! |
conditionalPanel( |
359 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'Cumulative Distribution Plot'"), |
360 | ! |
ui_decorate_teal_data( |
361 | ! |
ns("d_cumulative_plot"), |
362 | ! |
decorators = select_decorators(args$decorators, "cumulative_plot") |
363 |
) |
|
364 |
), |
|
365 | ! |
ui_decorate_teal_data(ns("d_table"), decorators = select_decorators(args$decorators, "table")), |
366 | ! |
teal.widgets::panel_item( |
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, reporter, filter_panel_api, outlier_var, |
|
388 |
categorical_var, plot_height, plot_width, ggplot2_args, decorators) { |
|
389 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
390 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
391 | ! |
checkmate::assert_class(data, "reactive") |
392 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
393 | ! |
moduleServer(id, function(input, output, session) { |
394 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
395 | ||
396 | ! |
ns <- session$ns |
397 | ||
398 | ! |
vars <- list(outlier_var = outlier_var, categorical_var = categorical_var) |
399 | ||
400 | ! |
rule_diff <- function(other) { |
401 | ! |
function(value) { |
402 | ! |
othervalue <- tryCatch(selector_list()[[other]]()[["select"]], error = function(e) NULL) |
403 | ! |
if (!is.null(othervalue) && identical(othervalue, value)) { |
404 | ! |
"`Variable` and `Categorical factor` cannot be the same" |
405 |
} |
|
406 |
} |
|
407 |
} |
|
408 | ||
409 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
410 | ! |
data_extract = vars, |
411 | ! |
datasets = data, |
412 | ! |
select_validation_rule = list( |
413 | ! |
outlier_var = shinyvalidate::compose_rules( |
414 | ! |
shinyvalidate::sv_required("Please select a variable"), |
415 | ! |
rule_diff("categorical_var") |
416 |
), |
|
417 | ! |
categorical_var = rule_diff("outlier_var") |
418 |
) |
|
419 |
) |
|
420 | ||
421 | ! |
iv_r <- reactive({ |
422 | ! |
iv <- shinyvalidate::InputValidator$new() |
423 | ! |
iv$add_rule("method", shinyvalidate::sv_required("Please select a method")) |
424 | ! |
iv$add_rule("boxplot_alts", shinyvalidate::sv_required("Please select Plot Type")) |
425 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
426 |
}) |
|
427 | ||
428 | ! |
reactive_select_input <- reactive({ |
429 | ! |
if (is.null(selector_list()$categorical_var) || length(selector_list()$categorical_var()$select) == 0) { |
430 | ! |
selector_list()[names(selector_list()) != "categorical_var"] |
431 |
} else { |
|
432 | ! |
selector_list() |
433 |
} |
|
434 |
}) |
|
435 | ||
436 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
437 | ! |
selector_list = reactive_select_input, |
438 | ! |
datasets = data, |
439 | ! |
merge_function = "dplyr::inner_join" |
440 |
) |
|
441 | ||
442 | ! |
anl_merged_q <- reactive({ |
443 | ! |
req(anl_merged_input()) |
444 | ! |
data() %>% |
445 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
446 |
}) |
|
447 | ||
448 | ! |
merged <- list( |
449 | ! |
anl_input_r = anl_merged_input, |
450 | ! |
anl_q_r = anl_merged_q |
451 |
) |
|
452 | ||
453 | ! |
n_outlier_missing <- reactive({ |
454 | ! |
req(iv_r()$is_valid()) |
455 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
456 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
457 | ! |
sum(is.na(ANL[[outlier_var]])) |
458 |
}) |
|
459 | ||
460 |
# Used to create outlier table and the dropdown with additional columns |
|
461 | ! |
dataname_first <- isolate(names(data())[[1]]) |
462 | ||
463 | ! |
common_code_q <- reactive({ |
464 | ! |
req(iv_r()$is_valid()) |
465 | ||
466 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
467 | ! |
qenv <- merged$anl_q_r() |
468 | ||
469 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
470 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
471 | ! |
order_by_outlier <- input$order_by_outlier |
472 | ! |
method <- input$method |
473 | ! |
split_outliers <- input$split_outliers |
474 | ! |
teal::validate_has_data( |
475 |
# missing values in the categorical variable may be used to form a category of its own |
|
476 | ! |
`if`( |
477 | ! |
length(categorical_var) == 0, |
478 | ! |
ANL, |
479 | ! |
ANL[, names(ANL) != categorical_var, drop = FALSE] |
480 |
), |
|
481 | ! |
min_nrow = 10, |
482 | ! |
complete = TRUE, |
483 | ! |
allow_inf = FALSE |
484 |
) |
|
485 | ! |
validate(need(is.numeric(ANL[[outlier_var]]), "`Variable` is not numeric")) |
486 | ! |
validate(need(length(unique(ANL[[outlier_var]])) > 1, "Variable has no variation, i.e. only one unique value")) |
487 | ||
488 |
# show/hide split_outliers |
|
489 | ! |
if (length(categorical_var) == 0) { |
490 | ! |
shinyjs::hide("split_outliers") |
491 | ! |
if (n_outlier_missing() > 0) { |
492 | ! |
qenv <- teal.code::eval_code( |
493 | ! |
qenv, |
494 | ! |
substitute( |
495 | ! |
expr = ANL <- ANL %>% dplyr::filter(!is.na(outlier_var_name)), |
496 | ! |
env = list(outlier_var_name = as.name(outlier_var)) |
497 |
) |
|
498 |
) |
|
499 |
} |
|
500 |
} else { |
|
501 | ! |
validate(need( |
502 | ! |
is.factor(ANL[[categorical_var]]) || |
503 | ! |
is.character(ANL[[categorical_var]]) || |
504 | ! |
is.integer(ANL[[categorical_var]]), |
505 | ! |
"`Categorical factor` must be `factor`, `character`, or `integer`" |
506 |
)) |
|
507 | ||
508 | ! |
if (n_outlier_missing() > 0) { |
509 | ! |
qenv <- teal.code::eval_code( |
510 | ! |
qenv, |
511 | ! |
substitute( |
512 | ! |
expr = ANL <- ANL %>% dplyr::filter(!is.na(outlier_var_name)), |
513 | ! |
env = list(outlier_var_name = as.name(outlier_var)) |
514 |
) |
|
515 |
) |
|
516 |
} |
|
517 | ! |
shinyjs::show("split_outliers") |
518 |
} |
|
519 | ||
520 |
# slider |
|
521 | ! |
outlier_definition_param <- if (method == "IQR") { |
522 | ! |
input$iqr_slider |
523 | ! |
} else if (method == "Z-score") { |
524 | ! |
input$zscore_slider |
525 | ! |
} else if (method == "Percentile") { |
526 | ! |
input$percentile_slider |
527 |
} |
|
528 | ||
529 |
# this is utils function that converts a %>% NULL %>% b into a %>% b |
|
530 | ! |
remove_pipe_null <- function(x) { |
531 | ! |
if (length(x) == 1) { |
532 | ! |
return(x) |
533 |
} |
|
534 | ! |
if (identical(x[[1]], as.name("%>%")) && is.null(x[[3]])) { |
535 | ! |
return(remove_pipe_null(x[[2]])) |
536 |
} |
|
537 | ! |
return(as.call(c(x[[1]], lapply(x[-1], remove_pipe_null)))) |
538 |
} |
|
539 | ||
540 | ! |
qenv <- teal.code::eval_code( |
541 | ! |
qenv, |
542 | ! |
substitute( |
543 | ! |
expr = { |
544 | ! |
ANL_OUTLIER <- ANL %>% |
545 | ! |
group_expr %>% # styler: off |
546 | ! |
dplyr::mutate(is_outlier = { |
547 | ! |
q1_q3 <- stats::quantile(outlier_var_name, probs = c(0.25, 0.75)) |
548 | ! |
iqr <- q1_q3[2] - q1_q3[1] |
549 | ! |
!(outlier_var_name >= q1_q3[1] - 1.5 * iqr & outlier_var_name <= q1_q3[2] + 1.5 * iqr) |
550 |
}) %>% |
|
551 | ! |
calculate_outliers %>% # styler: off |
552 | ! |
ungroup_expr %>% # styler: off |
553 | ! |
dplyr::filter(is_outlier | is_outlier_selected) %>% |
554 | ! |
dplyr::select(-is_outlier) |
555 |
}, |
|
556 | ! |
env = list( |
557 | ! |
calculate_outliers = if (method == "IQR") { |
558 | ! |
substitute( |
559 | ! |
expr = dplyr::mutate(is_outlier_selected = { |
560 | ! |
q1_q3 <- stats::quantile(outlier_var_name, probs = c(0.25, 0.75)) |
561 | ! |
iqr <- q1_q3[2] - q1_q3[1] |
562 |
!( |
|
563 | ! |
outlier_var_name >= q1_q3[1] - outlier_definition_param * iqr & |
564 | ! |
outlier_var_name <= q1_q3[2] + outlier_definition_param * iqr |
565 |
) |
|
566 |
}), |
|
567 | ! |
env = list( |
568 | ! |
outlier_var_name = as.name(outlier_var), |
569 | ! |
outlier_definition_param = outlier_definition_param |
570 |
) |
|
571 |
) |
|
572 | ! |
} else if (method == "Z-score") { |
573 | ! |
substitute( |
574 | ! |
expr = dplyr::mutate( |
575 | ! |
is_outlier_selected = abs(outlier_var_name - mean(outlier_var_name)) / |
576 | ! |
stats::sd(outlier_var_name) > outlier_definition_param |
577 |
), |
|
578 | ! |
env = list( |
579 | ! |
outlier_var_name = as.name(outlier_var), |
580 | ! |
outlier_definition_param = outlier_definition_param |
581 |
) |
|
582 |
) |
|
583 | ! |
} else if (method == "Percentile") { |
584 | ! |
substitute( |
585 | ! |
expr = dplyr::mutate( |
586 | ! |
is_outlier_selected = outlier_var_name < stats::quantile(outlier_var_name, outlier_definition_param) | |
587 | ! |
outlier_var_name > stats::quantile(outlier_var_name, 1 - outlier_definition_param) |
588 |
), |
|
589 | ! |
env = list( |
590 | ! |
outlier_var_name = as.name(outlier_var), |
591 | ! |
outlier_definition_param = outlier_definition_param |
592 |
) |
|
593 |
) |
|
594 |
}, |
|
595 | ! |
outlier_var_name = as.name(outlier_var), |
596 | ! |
group_expr = if (isTRUE(split_outliers) && length(categorical_var) != 0) { |
597 | ! |
substitute(dplyr::group_by(x), list(x = as.name(categorical_var))) |
598 |
}, |
|
599 | ! |
ungroup_expr = if (isTRUE(split_outliers) && length(categorical_var) != 0) { |
600 | ! |
substitute(dplyr::ungroup()) |
601 |
} |
|
602 |
) |
|
603 |
) %>% |
|
604 | ! |
remove_pipe_null() |
605 |
) |
|
606 | ||
607 |
# ANL_OUTLIER_EXTENDED is the base table |
|
608 | ! |
qenv <- teal.code::eval_code( |
609 | ! |
qenv, |
610 | ! |
substitute( |
611 | ! |
expr = { |
612 | ! |
ANL_OUTLIER_EXTENDED <- dplyr::left_join( |
613 | ! |
ANL_OUTLIER, |
614 | ! |
dplyr::select( |
615 | ! |
dataname, |
616 | ! |
dplyr::setdiff(names(dataname), dplyr::setdiff(names(ANL_OUTLIER), join_keys)) |
617 |
), |
|
618 | ! |
by = join_keys |
619 |
) |
|
620 |
}, |
|
621 | ! |
env = list( |
622 | ! |
dataname = as.name(dataname_first), |
623 | ! |
join_keys = as.character(teal.data::join_keys(data())[dataname_first, dataname_first]) |
624 |
) |
|
625 |
) |
|
626 |
) |
|
627 | ||
628 | ! |
qenv <- if (length(categorical_var) > 0) { |
629 | ! |
qenv <- teal.code::eval_code( |
630 | ! |
qenv, |
631 | ! |
substitute( |
632 | ! |
expr = summary_table_pre <- ANL_OUTLIER %>% |
633 | ! |
dplyr::filter(is_outlier_selected) %>% |
634 | ! |
dplyr::select(outlier_var_name, categorical_var_name) %>% |
635 | ! |
dplyr::group_by(categorical_var_name) %>% |
636 | ! |
dplyr::summarise(n_outliers = dplyr::n()) %>% |
637 | ! |
dplyr::right_join( |
638 | ! |
ANL %>% |
639 | ! |
dplyr::select(outlier_var_name, categorical_var_name) %>% |
640 | ! |
dplyr::group_by(categorical_var_name) %>% |
641 | ! |
dplyr::summarise( |
642 | ! |
total_in_cat = dplyr::n(), |
643 | ! |
n_na = sum(is.na(outlier_var_name) | is.na(categorical_var_name)) |
644 |
), |
|
645 | ! |
by = categorical_var |
646 |
) %>% |
|
647 |
# This is important as there may be categorical variables with natural orderings, e.g. AGE. |
|
648 |
# The plots should be displayed by default in increasing order in these situations. |
|
649 |
# dplyr::arrange will sort integer, factor, and character data types in the expected way. |
|
650 | ! |
dplyr::arrange(categorical_var_name) %>% |
651 | ! |
dplyr::mutate( |
652 | ! |
n_outliers = dplyr::if_else(is.na(n_outliers), 0, as.numeric(n_outliers)), |
653 | ! |
display_str = dplyr::if_else( |
654 | ! |
n_outliers > 0, |
655 | ! |
sprintf("%d [%.02f%%]", n_outliers, 100 * n_outliers / total_in_cat), |
656 | ! |
"0" |
657 |
), |
|
658 | ! |
display_str_na = dplyr::if_else( |
659 | ! |
n_na > 0, |
660 | ! |
sprintf("%d [%.02f%%]", n_na, 100 * n_na / total_in_cat), |
661 | ! |
"0" |
662 |
), |
|
663 | ! |
order = seq_along(n_outliers) |
664 |
), |
|
665 | ! |
env = list( |
666 | ! |
categorical_var = categorical_var, |
667 | ! |
categorical_var_name = as.name(categorical_var), |
668 | ! |
outlier_var_name = as.name(outlier_var) |
669 |
) |
|
670 |
) |
|
671 |
) |
|
672 |
# now to handle when user chooses to order based on amount of outliers |
|
673 | ! |
if (order_by_outlier) { |
674 | ! |
qenv <- teal.code::eval_code( |
675 | ! |
qenv, |
676 | ! |
quote( |
677 | ! |
summary_table_pre <- summary_table_pre %>% |
678 | ! |
dplyr::arrange(desc(n_outliers / total_in_cat)) %>% |
679 | ! |
dplyr::mutate(order = seq_len(nrow(summary_table_pre))) |
680 |
) |
|
681 |
) |
|
682 |
} |
|
683 | ||
684 | ! |
teal.code::eval_code( |
685 | ! |
qenv, |
686 | ! |
substitute( |
687 | ! |
expr = { |
688 |
# In order for geom_rug to work properly when reordering takes place inside facet_grid, |
|
689 |
# all tables must have the column used for reording. |
|
690 |
# In this case, the column used for reordering is `order`. |
|
691 | ! |
ANL_OUTLIER <- dplyr::left_join( |
692 | ! |
ANL_OUTLIER, |
693 | ! |
summary_table_pre[, c("order", categorical_var)], |
694 | ! |
by = categorical_var |
695 |
) |
|
696 |
# so that x axis of plot aligns with columns of summary table, from most outliers to least by percentage |
|
697 | ! |
ANL <- ANL %>% |
698 | ! |
dplyr::left_join( |
699 | ! |
dplyr::select(summary_table_pre, categorical_var_name, order), |
700 | ! |
by = categorical_var |
701 |
) %>% |
|
702 | ! |
dplyr::arrange(order) |
703 | ! |
summary_table <- summary_table_pre %>% |
704 | ! |
dplyr::select( |
705 | ! |
categorical_var_name, |
706 | ! |
Outliers = display_str, Missings = display_str_na, Total = total_in_cat |
707 |
) %>% |
|
708 | ! |
dplyr::mutate_all(as.character) %>% |
709 | ! |
tidyr::pivot_longer(-categorical_var_name) %>% |
710 | ! |
tidyr::pivot_wider(names_from = categorical_var, values_from = value) %>% |
711 | ! |
tibble::column_to_rownames("name") |
712 |
}, |
|
713 | ! |
env = list( |
714 | ! |
categorical_var = categorical_var, |
715 | ! |
categorical_var_name = as.name(categorical_var) |
716 |
) |
|
717 |
) |
|
718 |
) |
|
719 |
} else { |
|
720 | ! |
within(qenv, summary_table <- data.frame()) |
721 |
} |
|
722 | ||
723 |
# Datatable is generated in qenv to allow for output decoration |
|
724 | ! |
qenv <- within(qenv, { |
725 | ! |
table <- DT::datatable( |
726 | ! |
summary_table, |
727 | ! |
options = list( |
728 | ! |
dom = "t", |
729 | ! |
autoWidth = TRUE, |
730 | ! |
columnDefs = list(list(width = "200px", targets = "_all")) |
731 |
) |
|
732 |
) |
|
733 |
}) |
|
734 | ||
735 | ! |
if (length(categorical_var) > 0 && nrow(qenv[["ANL_OUTLIER"]]) > 0) { |
736 | ! |
shinyjs::show("order_by_outlier") |
737 |
} else { |
|
738 | ! |
shinyjs::hide("order_by_outlier") |
739 |
} |
|
740 | ||
741 | ! |
qenv |
742 |
}) |
|
743 | ||
744 |
# boxplot/violinplot # nolint commented_code |
|
745 | ! |
box_plot_q <- reactive({ |
746 | ! |
req(common_code_q()) |
747 | ! |
ANL <- common_code_q()[["ANL"]] |
748 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
749 | ||
750 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
751 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
752 | ||
753 |
# validation |
|
754 | ! |
teal::validate_has_data(ANL, 1) |
755 | ||
756 |
# boxplot |
|
757 | ! |
plot_call <- quote(ANL %>% ggplot()) |
758 | ||
759 | ! |
plot_call <- if (input$boxplot_alts == "Box plot") { |
760 | ! |
substitute(expr = plot_call + geom_boxplot(outlier.shape = NA), env = list(plot_call = plot_call)) |
761 | ! |
} else if (input$boxplot_alts == "Violin plot") { |
762 | ! |
substitute(expr = plot_call + geom_violin(), env = list(plot_call = plot_call)) |
763 |
} else { |
|
764 | ! |
NULL |
765 |
} |
|
766 | ||
767 | ! |
plot_call <- if (identical(categorical_var, character(0)) || is.null(categorical_var)) { |
768 | ! |
inner_call <- substitute( |
769 | ! |
expr = plot_call + |
770 | ! |
aes(x = "Entire dataset", y = outlier_var_name) + |
771 | ! |
scale_x_discrete(), |
772 | ! |
env = list(plot_call = plot_call, outlier_var_name = as.name(outlier_var)) |
773 |
) |
|
774 | ! |
if (nrow(ANL_OUTLIER) > 0) { |
775 | ! |
substitute( |
776 | ! |
expr = inner_call + geom_point( |
777 | ! |
data = ANL_OUTLIER, |
778 | ! |
aes(x = "Entire dataset", y = outlier_var_name, color = is_outlier_selected) |
779 |
), |
|
780 | ! |
env = list(inner_call = inner_call, outlier_var_name = as.name(outlier_var)) |
781 |
) |
|
782 |
} else { |
|
783 | ! |
inner_call |
784 |
} |
|
785 |
} else { |
|
786 | ! |
substitute( |
787 | ! |
expr = plot_call + |
788 | ! |
aes(y = outlier_var_name, x = reorder(categorical_var_name, order)) + |
789 | ! |
xlab(categorical_var) + |
790 | ! |
scale_x_discrete() + |
791 | ! |
geom_point( |
792 | ! |
data = ANL_OUTLIER, |
793 | ! |
aes(x = as.factor(categorical_var_name), y = outlier_var_name, color = is_outlier_selected) |
794 |
), |
|
795 | ! |
env = list( |
796 | ! |
plot_call = plot_call, |
797 | ! |
outlier_var_name = as.name(outlier_var), |
798 | ! |
categorical_var_name = as.name(categorical_var), |
799 | ! |
categorical_var = categorical_var |
800 |
) |
|
801 |
) |
|
802 |
} |
|
803 | ||
804 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
805 | ! |
labs = list(color = "Is outlier?"), |
806 | ! |
theme = list(legend.position = "top") |
807 |
) |
|
808 | ||
809 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
810 | ! |
user_plot = ggplot2_args[["Boxplot"]], |
811 | ! |
user_default = ggplot2_args$default, |
812 | ! |
module_plot = dev_ggplot2_args |
813 |
) |
|
814 | ||
815 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
816 | ! |
all_ggplot2_args, |
817 | ! |
ggtheme = input$ggtheme |
818 |
) |
|
819 | ||
820 | ! |
teal.code::eval_code( |
821 | ! |
common_code_q(), |
822 | ! |
substitute( |
823 | ! |
expr = box_plot <- plot_call + |
824 | ! |
scale_color_manual(values = c("TRUE" = "red", "FALSE" = "black")) + |
825 | ! |
labs + ggthemes + themes, |
826 | ! |
env = list( |
827 | ! |
plot_call = plot_call, |
828 | ! |
labs = parsed_ggplot2_args$labs, |
829 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
830 | ! |
themes = parsed_ggplot2_args$theme |
831 |
) |
|
832 |
) |
|
833 |
) |
|
834 |
}) |
|
835 | ||
836 |
# density plot |
|
837 | ! |
density_plot_q <- reactive({ |
838 | ! |
ANL <- common_code_q()[["ANL"]] |
839 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
840 | ||
841 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
842 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
843 | ||
844 |
# validation |
|
845 | ! |
teal::validate_has_data(ANL, 1) |
846 |
# plot |
|
847 | ! |
plot_call <- substitute( |
848 | ! |
expr = ANL %>% |
849 | ! |
ggplot(aes(x = outlier_var_name)) + |
850 | ! |
geom_density() + |
851 | ! |
geom_rug(data = ANL_OUTLIER, aes(x = outlier_var_name, color = is_outlier_selected)) + |
852 | ! |
scale_color_manual(values = c("TRUE" = "red", "FALSE" = "black")), |
853 | ! |
env = list(outlier_var_name = as.name(outlier_var)) |
854 |
) |
|
855 | ||
856 | ! |
plot_call <- if (identical(categorical_var, character(0)) || is.null(categorical_var)) { |
857 | ! |
substitute(expr = plot_call, env = list(plot_call = plot_call)) |
858 |
} else { |
|
859 | ! |
substitute( |
860 | ! |
expr = plot_call + facet_grid(~ reorder(categorical_var_name, order)), |
861 | ! |
env = list(plot_call = plot_call, categorical_var_name = as.name(categorical_var)) |
862 |
) |
|
863 |
} |
|
864 | ||
865 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
866 | ! |
labs = list(color = "Is outlier?"), |
867 | ! |
theme = list(legend.position = "top") |
868 |
) |
|
869 | ||
870 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
871 | ! |
user_plot = ggplot2_args[["Density Plot"]], |
872 | ! |
user_default = ggplot2_args$default, |
873 | ! |
module_plot = dev_ggplot2_args |
874 |
) |
|
875 | ||
876 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
877 | ! |
all_ggplot2_args, |
878 | ! |
ggtheme = input$ggtheme |
879 |
) |
|
880 | ||
881 | ! |
teal.code::eval_code( |
882 | ! |
common_code_q(), |
883 | ! |
substitute( |
884 | ! |
expr = density_plot <- plot_call + labs + ggthemes + themes, |
885 | ! |
env = list( |
886 | ! |
plot_call = plot_call, |
887 | ! |
labs = parsed_ggplot2_args$labs, |
888 | ! |
themes = parsed_ggplot2_args$theme, |
889 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
890 |
) |
|
891 |
) |
|
892 |
) |
|
893 |
}) |
|
894 | ||
895 |
# Cumulative distribution plot |
|
896 | ! |
cumulative_plot_q <- reactive({ |
897 | ! |
ANL <- common_code_q()[["ANL"]] |
898 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
899 | ||
900 | ! |
qenv <- common_code_q() |
901 | ||
902 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
903 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
904 | ||
905 |
# validation |
|
906 | ! |
teal::validate_has_data(ANL, 1) |
907 | ||
908 |
# plot |
|
909 | ! |
plot_call <- substitute( |
910 | ! |
expr = ANL %>% ggplot(aes(x = outlier_var_name)) + |
911 | ! |
stat_ecdf(), |
912 | ! |
env = list(outlier_var_name = as.name(outlier_var)) |
913 |
) |
|
914 | ! |
if (length(categorical_var) == 0) { |
915 | ! |
qenv <- teal.code::eval_code( |
916 | ! |
qenv, |
917 | ! |
substitute( |
918 | ! |
expr = { |
919 | ! |
ecdf_df <- ANL %>% |
920 | ! |
dplyr::mutate( |
921 | ! |
y = stats::ecdf(ANL[[outlier_var]])(ANL[[outlier_var]]) |
922 |
) |
|
923 | ||
924 | ! |
outlier_points <- dplyr::left_join( |
925 | ! |
ecdf_df, |
926 | ! |
ANL_OUTLIER, |
927 | ! |
by = dplyr::setdiff(names(ecdf_df), "y") |
928 |
) %>% |
|
929 | ! |
dplyr::filter(!is.na(is_outlier_selected)) |
930 |
}, |
|
931 | ! |
env = list(outlier_var = outlier_var) |
932 |
) |
|
933 |
) |
|
934 |
} else { |
|
935 | ! |
qenv <- teal.code::eval_code( |
936 | ! |
qenv, |
937 | ! |
substitute( |
938 | ! |
expr = { |
939 | ! |
all_categories <- lapply( |
940 | ! |
unique(ANL[[categorical_var]]), |
941 | ! |
function(x) { |
942 | ! |
ANL <- ANL %>% dplyr::filter(get(categorical_var) == x) |
943 | ! |
anl_outlier2 <- ANL_OUTLIER %>% dplyr::filter(get(categorical_var) == x) |
944 | ! |
ecdf_df <- ANL %>% |
945 | ! |
dplyr::mutate(y = stats::ecdf(ANL[[outlier_var]])(ANL[[outlier_var]])) |
946 | ||
947 | ! |
dplyr::left_join( |
948 | ! |
ecdf_df, |
949 | ! |
anl_outlier2, |
950 | ! |
by = dplyr::setdiff(names(ecdf_df), "y") |
951 |
) %>% |
|
952 | ! |
dplyr::filter(!is.na(is_outlier_selected)) |
953 |
} |
|
954 |
) |
|
955 | ! |
outlier_points <- do.call(rbind, all_categories) |
956 |
}, |
|
957 | ! |
env = list(categorical_var = categorical_var, outlier_var = outlier_var) |
958 |
) |
|
959 |
) |
|
960 | ! |
plot_call <- substitute( |
961 | ! |
expr = plot_call + facet_grid(~ reorder(categorical_var_name, order)), |
962 | ! |
env = list(plot_call = plot_call, categorical_var_name = as.name(categorical_var)) |
963 |
) |
|
964 |
} |
|
965 | ||
966 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
967 | ! |
labs = list(color = "Is outlier?"), |
968 | ! |
theme = list(legend.position = "top") |
969 |
) |
|
970 | ||
971 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
972 | ! |
user_plot = ggplot2_args[["Cumulative Distribution Plot"]], |
973 | ! |
user_default = ggplot2_args$default, |
974 | ! |
module_plot = dev_ggplot2_args |
975 |
) |
|
976 | ||
977 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
978 | ! |
all_ggplot2_args, |
979 | ! |
ggtheme = input$ggtheme |
980 |
) |
|
981 | ||
982 | ! |
teal.code::eval_code( |
983 | ! |
qenv, |
984 | ! |
substitute( |
985 | ! |
expr = cumulative_plot <- plot_call + |
986 | ! |
geom_point(data = outlier_points, aes(x = outlier_var_name, y = y, color = is_outlier_selected)) + |
987 | ! |
scale_color_manual(values = c("TRUE" = "red", "FALSE" = "black")) + |
988 | ! |
labs + ggthemes + themes, |
989 | ! |
env = list( |
990 | ! |
plot_call = plot_call, |
991 | ! |
outlier_var_name = as.name(outlier_var), |
992 | ! |
labs = parsed_ggplot2_args$labs, |
993 | ! |
themes = parsed_ggplot2_args$theme, |
994 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
995 |
) |
|
996 |
) |
|
997 |
) |
|
998 |
}) |
|
999 | ||
1000 | ! |
current_tab_r <- reactive({ |
1001 | ! |
switch(req(input$tabs), |
1002 | ! |
"Boxplot" = "box_plot", |
1003 | ! |
"Density Plot" = "density_plot", |
1004 | ! |
"Cumulative Distribution Plot" = "cumulative_plot" |
1005 |
) |
|
1006 |
}) |
|
1007 | ||
1008 | ! |
decorated_q <- mapply( |
1009 | ! |
function(obj_name, q) { |
1010 | ! |
srv_decorate_teal_data( |
1011 | ! |
id = sprintf("d_%s", obj_name), |
1012 | ! |
data = q, |
1013 | ! |
decorators = select_decorators(decorators, obj_name), |
1014 | ! |
expr = reactive({ |
1015 | ! |
substitute( |
1016 | ! |
expr = { |
1017 | ! |
columns_index <- union( |
1018 | ! |
setdiff(names(ANL_OUTLIER), c("is_outlier_selected", "order")), |
1019 | ! |
table_columns |
1020 |
) |
|
1021 | ! |
ANL_OUTLIER_EXTENDED[ANL_OUTLIER_EXTENDED$is_outlier_selected, columns_index] |
1022 | ! |
print(.plot) |
1023 |
}, |
|
1024 | ! |
env = list(table_columns = input$table_ui_columns, .plot = as.name(obj_name)) |
1025 |
) |
|
1026 |
}), |
|
1027 | ! |
expr_is_reactive = TRUE |
1028 |
) |
|
1029 |
}, |
|
1030 | ! |
rlang::set_names(c("box_plot", "density_plot", "cumulative_plot")), |
1031 | ! |
c(box_plot_q, density_plot_q, cumulative_plot_q) |
1032 |
) |
|
1033 | ||
1034 | ! |
decorated_final_q_no_table <- reactive(decorated_q[[req(current_tab_r())]]()) |
1035 | ||
1036 | ! |
decorated_final_q <- srv_decorate_teal_data( |
1037 | ! |
"d_table", |
1038 | ! |
data = decorated_final_q_no_table, |
1039 | ! |
decorators = select_decorators(decorators, "table"), |
1040 | ! |
expr = table |
1041 |
) |
|
1042 | ||
1043 | ! |
output$summary_table <- DT::renderDataTable( |
1044 | ! |
expr = { |
1045 | ! |
if (iv_r()$is_valid()) { |
1046 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
1047 | ! |
if (!is.null(categorical_var)) { |
1048 | ! |
decorated_final_q()[["table"]] |
1049 |
} |
|
1050 |
} |
|
1051 |
} |
|
1052 |
) |
|
1053 | ||
1054 |
# slider text |
|
1055 | ! |
output$ui_outlier_help <- renderUI({ |
1056 | ! |
req(input$method) |
1057 | ! |
if (input$method == "IQR") { |
1058 | ! |
req(input$iqr_slider) |
1059 | ! |
tags$small( |
1060 | ! |
withMathJax( |
1061 | ! |
helpText( |
1062 | ! |
"Outlier data points (\\(x \\lt Q1 - ", input$iqr_slider, "\\times IQR\\) or \\( |
1063 | ! |
Q3 + ", input$iqr_slider, "\\times IQR \\lt x\\)) |
1064 | ! |
are displayed in red on the plot and can be visualized in the table below." |
1065 |
), |
|
1066 | ! |
if (input$split_outliers) { |
1067 | ! |
withMathJax(helpText("Note: Quantiles are calculated per group.")) |
1068 |
} |
|
1069 |
) |
|
1070 |
) |
|
1071 | ! |
} else if (input$method == "Z-score") { |
1072 | ! |
req(input$zscore_slider) |
1073 | ! |
tags$small( |
1074 | ! |
withMathJax( |
1075 | ! |
helpText( |
1076 | ! |
"Outlier data points (\\(Zscore(x) < -", input$zscore_slider, |
1077 | ! |
"\\) or \\(", input$zscore_slider, "< Zscore(x) \\)) |
1078 | ! |
are displayed in red on the plot and can be visualized in the table below." |
1079 |
), |
|
1080 | ! |
if (input$split_outliers) { |
1081 | ! |
withMathJax(helpText(" Note: Z-scores are calculated per group.")) |
1082 |
} |
|
1083 |
) |
|
1084 |
) |
|
1085 | ! |
} else if (input$method == "Percentile") { |
1086 | ! |
req(input$percentile_slider) |
1087 | ! |
tags$small( |
1088 | ! |
withMathJax( |
1089 | ! |
helpText( |
1090 | ! |
"Outlier/extreme data points (\\( Percentile(x) <", input$percentile_slider, |
1091 | ! |
"\\) or \\(", 1 - input$percentile_slider, " < Percentile(x) \\)) |
1092 | ! |
are displayed in red on the plot and can be visualized in the table below." |
1093 |
), |
|
1094 | ! |
if (input$split_outliers) { |
1095 | ! |
withMathJax(helpText("Note: Percentiles are calculated per group.")) |
1096 |
} |
|
1097 |
) |
|
1098 |
) |
|
1099 |
} |
|
1100 |
}) |
|
1101 | ||
1102 | ! |
box_plot_r <- reactive({ |
1103 | ! |
teal::validate_inputs(iv_r()) |
1104 | ! |
req(decorated_q$box_plot())[["box_plot"]] |
1105 |
}) |
|
1106 | ! |
density_plot_r <- reactive({ |
1107 | ! |
teal::validate_inputs(iv_r()) |
1108 | ! |
req(decorated_q$density_plot())[["density_plot"]] |
1109 |
}) |
|
1110 | ! |
cumulative_plot_r <- reactive({ |
1111 | ! |
teal::validate_inputs(iv_r()) |
1112 | ! |
req(decorated_q$cumulative_plot())[["cumulative_plot"]] |
1113 |
}) |
|
1114 | ||
1115 | ! |
box_pws <- teal.widgets::plot_with_settings_srv( |
1116 | ! |
id = "box_plot", |
1117 | ! |
plot_r = box_plot_r, |
1118 | ! |
height = plot_height, |
1119 | ! |
width = plot_width, |
1120 | ! |
brushing = TRUE |
1121 |
) |
|
1122 | ||
1123 | ! |
density_pws <- teal.widgets::plot_with_settings_srv( |
1124 | ! |
id = "density_plot", |
1125 | ! |
plot_r = density_plot_r, |
1126 | ! |
height = plot_height, |
1127 | ! |
width = plot_width, |
1128 | ! |
brushing = TRUE |
1129 |
) |
|
1130 | ||
1131 | ! |
cum_density_pws <- teal.widgets::plot_with_settings_srv( |
1132 | ! |
id = "cum_density_plot", |
1133 | ! |
plot_r = cumulative_plot_r, |
1134 | ! |
height = plot_height, |
1135 | ! |
width = plot_width, |
1136 | ! |
brushing = TRUE |
1137 |
) |
|
1138 | ||
1139 | ! |
choices <- reactive(teal.transform::variable_choices(data()[[dataname_first]])) |
1140 | ||
1141 | ! |
observeEvent(common_code_q(), { |
1142 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
1143 | ! |
teal.widgets::updateOptionalSelectInput( |
1144 | ! |
session, |
1145 | ! |
inputId = "table_ui_columns", |
1146 | ! |
choices = dplyr::setdiff(choices(), names(ANL_OUTLIER)), |
1147 | ! |
selected = restoreInput(ns("table_ui_columns"), isolate(input$table_ui_columns)) |
1148 |
) |
|
1149 |
}) |
|
1150 | ||
1151 | ! |
output$table_ui <- DT::renderDataTable( |
1152 | ! |
expr = { |
1153 | ! |
tab <- input$tabs |
1154 | ! |
req(tab) # tab is NULL upon app launch, hence will crash without this statement |
1155 | ! |
req(iv_r()$is_valid()) # Same validation as output$table_ui_wrap |
1156 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
1157 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
1158 | ||
1159 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
1160 | ! |
ANL_OUTLIER_EXTENDED <- common_code_q()[["ANL_OUTLIER_EXTENDED"]] |
1161 | ! |
ANL <- common_code_q()[["ANL"]] |
1162 | ||
1163 | ! |
plot_brush <- switch(current_tab_r(), |
1164 | ! |
box_plot = { |
1165 | ! |
box_plot_r() |
1166 | ! |
box_pws$brush() |
1167 |
}, |
|
1168 | ! |
density_plot = { |
1169 | ! |
density_plot_r() |
1170 | ! |
density_pws$brush() |
1171 |
}, |
|
1172 | ! |
cumulative_plot = { |
1173 | ! |
cumulative_plot_r() |
1174 | ! |
cum_density_pws$brush() |
1175 |
} |
|
1176 |
) |
|
1177 | ||
1178 |
# removing unused column ASAP |
|
1179 | ! |
ANL_OUTLIER$order <- ANL$order <- NULL |
1180 | ||
1181 | ! |
display_table <- if (!is.null(plot_brush)) { |
1182 | ! |
if (length(categorical_var) > 0) { |
1183 |
# due to reordering, the x-axis label may be changed to something like "reorder(categorical_var, order)" |
|
1184 | ! |
if (tab == "Boxplot") { |
1185 | ! |
plot_brush$mapping$x <- categorical_var |
1186 |
} else { |
|
1187 |
# the other plots use facetting |
|
1188 |
# so it is panelvar1 that gets relabelled to "reorder(categorical_var, order)" |
|
1189 | ! |
plot_brush$mapping$panelvar1 <- categorical_var |
1190 |
} |
|
1191 |
} else { |
|
1192 | ! |
if (tab == "Boxplot") { |
1193 |
# in boxplot with no categorical variable, there is no column in ANL that would correspond to x-axis |
|
1194 |
# so a column needs to be inserted with the value "Entire dataset" because that's the label used in plot |
|
1195 | ! |
ANL[[plot_brush$mapping$x]] <- "Entire dataset" |
1196 |
} |
|
1197 |
} |
|
1198 | ||
1199 |
# in density and cumulative plots, ANL does not have a column corresponding to y-axis. |
|
1200 |
# so they need to be computed and attached to ANL |
|
1201 | ! |
if (tab == "Density Plot") { |
1202 | ! |
plot_brush$mapping$y <- "density" |
1203 | ! |
ANL$density <- plot_brush$ymin |
1204 |
# either ymin or ymax will work |
|
1205 | ! |
} else if (tab == "Cumulative Distribution Plot") { |
1206 | ! |
plot_brush$mapping$y <- "cdf" |
1207 | ! |
if (length(categorical_var) > 0) { |
1208 | ! |
ANL <- ANL %>% |
1209 | ! |
dplyr::group_by(!!as.name(plot_brush$mapping$panelvar1)) %>% |
1210 | ! |
dplyr::mutate(cdf = stats::ecdf(!!as.name(outlier_var))(!!as.name(outlier_var))) |
1211 |
} else { |
|
1212 | ! |
ANL$cdf <- stats::ecdf(ANL[[outlier_var]])(ANL[[outlier_var]]) |
1213 |
} |
|
1214 |
} |
|
1215 | ||
1216 | ! |
brushed_rows <- brushedPoints(ANL, plot_brush) |
1217 | ! |
if (nrow(brushed_rows) > 0) { |
1218 |
# now we need to remove extra column from ANL so that it will have the same columns as ANL_OUTLIER |
|
1219 |
# so that dplyr::intersect will work |
|
1220 | ! |
if (tab == "Density Plot") { |
1221 | ! |
brushed_rows$density <- NULL |
1222 | ! |
} else if (tab == "Cumulative Distribution Plot") { |
1223 | ! |
brushed_rows$cdf <- NULL |
1224 | ! |
} else if (tab == "Boxplot" && length(categorical_var) == 0) { |
1225 | ! |
brushed_rows[[plot_brush$mapping$x]] <- NULL |
1226 |
} |
|
1227 |
# is_outlier_selected is part of ANL_OUTLIER so needed here |
|
1228 | ! |
brushed_rows$is_outlier_selected <- TRUE |
1229 | ! |
dplyr::intersect(ANL_OUTLIER, brushed_rows) |
1230 |
} else { |
|
1231 | ! |
ANL_OUTLIER[0, ] |
1232 |
} |
|
1233 |
} else { |
|
1234 | ! |
ANL_OUTLIER[ANL_OUTLIER$is_outlier_selected, ] |
1235 |
} |
|
1236 | ||
1237 | ! |
display_table$is_outlier_selected <- NULL |
1238 | ||
1239 |
# Extend the brushed ANL_OUTLIER with additional columns |
|
1240 | ! |
dplyr::left_join( |
1241 | ! |
display_table, |
1242 | ! |
dplyr::select(ANL_OUTLIER_EXTENDED, -"is_outlier_selected"), |
1243 | ! |
by = names(display_table) |
1244 |
) %>% |
|
1245 | ! |
dplyr::select(union(names(display_table), input$table_ui_columns)) |
1246 |
}, |
|
1247 | ! |
options = list( |
1248 | ! |
searching = FALSE, language = list( |
1249 | ! |
zeroRecords = "The brushed area does not contain outlier observations for the currently defined threshold" |
1250 |
), |
|
1251 | ! |
pageLength = input$table_ui_rows |
1252 |
) |
|
1253 |
) |
|
1254 | ||
1255 | ! |
output$total_outliers <- renderUI({ |
1256 | ! |
req(iv_r()$is_valid()) |
1257 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
1258 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
1259 | ! |
teal::validate_has_data(ANL, 1) |
1260 | ! |
ANL_OUTLIER_SELECTED <- ANL_OUTLIER[ANL_OUTLIER$is_outlier_selected, ] |
1261 | ! |
tags$h5( |
1262 | ! |
sprintf( |
1263 | ! |
"%s %d / %d [%.02f%%]", |
1264 | ! |
"Total number of outlier(s):", |
1265 | ! |
nrow(ANL_OUTLIER_SELECTED), |
1266 | ! |
nrow(ANL), |
1267 | ! |
100 * nrow(ANL_OUTLIER_SELECTED) / nrow(ANL) |
1268 |
) |
|
1269 |
) |
|
1270 |
}) |
|
1271 | ||
1272 | ! |
output$total_missing <- renderUI({ |
1273 | ! |
if (n_outlier_missing() > 0) { |
1274 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
1275 | ! |
helpText( |
1276 | ! |
sprintf( |
1277 | ! |
"%s %d / %d [%.02f%%]", |
1278 | ! |
"Total number of row(s) with missing values:", |
1279 | ! |
n_outlier_missing(), |
1280 | ! |
nrow(ANL), |
1281 | ! |
100 * (n_outlier_missing()) / nrow(ANL) |
1282 |
) |
|
1283 |
) |
|
1284 |
} |
|
1285 |
}) |
|
1286 | ||
1287 | ! |
output$table_ui_wrap <- renderUI({ |
1288 | ! |
req(iv_r()$is_valid()) |
1289 | ! |
tagList( |
1290 | ! |
teal.widgets::optionalSelectInput( |
1291 | ! |
inputId = ns("table_ui_columns"), |
1292 | ! |
label = "Choose additional columns", |
1293 | ! |
choices = NULL, |
1294 | ! |
selected = NULL, |
1295 | ! |
multiple = TRUE |
1296 |
), |
|
1297 | ! |
tags$h4("Outlier Table"), |
1298 | ! |
teal.widgets::get_dt_rows(ns("table_ui"), ns("table_ui_rows")) |
1299 |
) |
|
1300 |
}) |
|
1301 | ||
1302 | ! |
teal.widgets::verbatim_popup_srv( |
1303 | ! |
id = "rcode", |
1304 | ! |
verbatim_content = reactive(teal.code::get_code(req(decorated_final_q()))), |
1305 | ! |
title = "Show R Code for Outlier" |
1306 |
) |
|
1307 | ||
1308 |
### REPORTER |
|
1309 | ! |
if (with_reporter) { |
1310 | ! |
card_fun <- function(comment, label) { |
1311 | ! |
tab_type <- input$tabs |
1312 | ! |
card <- teal::report_card_template( |
1313 | ! |
title = paste0("Outliers - ", tab_type), |
1314 | ! |
label = label, |
1315 | ! |
with_filter = with_filter, |
1316 | ! |
filter_panel_api = filter_panel_api |
1317 |
) |
|
1318 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
1319 | ! |
if (length(categorical_var) > 0) { |
1320 | ! |
summary_table <- common_code_q()[["summary_table"]] |
1321 | ! |
card$append_text("Summary Table", "header3") |
1322 | ! |
card$append_table(summary_table) |
1323 |
} |
|
1324 | ! |
card$append_text("Plot", "header3") |
1325 | ! |
if (tab_type == "Boxplot") { |
1326 | ! |
card$append_plot(box_plot_r(), dim = box_pws$dim()) |
1327 | ! |
} else if (tab_type == "Density Plot") { |
1328 | ! |
card$append_plot(density_plot_r(), dim = density_pws$dim()) |
1329 | ! |
} else if (tab_type == "Cumulative Distribution Plot") { |
1330 | ! |
card$append_plot(cumulative_plot_r(), dim = cum_density_pws$dim()) |
1331 |
} |
|
1332 | ! |
if (!comment == "") { |
1333 | ! |
card$append_text("Comment", "header3") |
1334 | ! |
card$append_text(comment) |
1335 |
} |
|
1336 | ! |
card$append_src(teal.code::get_code(req(decorated_final_q()))) |
1337 | ! |
card |
1338 |
} |
|
1339 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
1340 |
} |
|
1341 |
### |
|
1342 |
}) |
|
1343 |
} |
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 |
#' @param decorators `r roxygen_decorators_param("tm_g_association")` |
|
25 |
#' |
|
26 |
#' @inherit shared_params return |
|
27 |
#' |
|
28 |
#' @section Decorating `tm_g_association`: |
|
29 |
#' |
|
30 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
31 |
#' - `plot` (`grob` created with [ggplot2::ggplotGrob()]) |
|
32 |
#' |
|
33 |
#' For additional details and examples of decorators, refer to the vignette |
|
34 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
35 |
#' |
|
36 |
#' @examplesShinylive |
|
37 |
#' library(teal.modules.general) |
|
38 |
#' interactive <- function() TRUE |
|
39 |
#' {{ next_example }} |
|
40 |
#' @examples |
|
41 |
#' # general data example |
|
42 |
#' data <- teal_data() |
|
43 |
#' data <- within(data, { |
|
44 |
#' require(nestcolor) |
|
45 |
#' CO2 <- CO2 |
|
46 |
#' factors <- names(Filter(isTRUE, vapply(CO2, is.factor, logical(1L)))) |
|
47 |
#' CO2[factors] <- lapply(CO2[factors], as.character) |
|
48 |
#' }) |
|
49 |
#' |
|
50 |
#' app <- init( |
|
51 |
#' data = data, |
|
52 |
#' modules = modules( |
|
53 |
#' tm_g_association( |
|
54 |
#' ref = data_extract_spec( |
|
55 |
#' dataname = "CO2", |
|
56 |
#' select = select_spec( |
|
57 |
#' label = "Select variable:", |
|
58 |
#' choices = variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment")), |
|
59 |
#' selected = "Plant", |
|
60 |
#' fixed = FALSE |
|
61 |
#' ) |
|
62 |
#' ), |
|
63 |
#' vars = data_extract_spec( |
|
64 |
#' dataname = "CO2", |
|
65 |
#' select = select_spec( |
|
66 |
#' label = "Select variables:", |
|
67 |
#' choices = variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment")), |
|
68 |
#' selected = "Treatment", |
|
69 |
#' multiple = TRUE, |
|
70 |
#' fixed = FALSE |
|
71 |
#' ) |
|
72 |
#' ) |
|
73 |
#' ) |
|
74 |
#' ) |
|
75 |
#' ) |
|
76 |
#' if (interactive()) { |
|
77 |
#' shinyApp(app$ui, app$server) |
|
78 |
#' } |
|
79 |
#' |
|
80 |
#' @examplesShinylive |
|
81 |
#' library(teal.modules.general) |
|
82 |
#' interactive <- function() TRUE |
|
83 |
#' {{ next_example }} |
|
84 |
#' @examples |
|
85 |
#' # CDISC data example |
|
86 |
#' data <- teal_data() |
|
87 |
#' data <- within(data, { |
|
88 |
#' require(nestcolor) |
|
89 |
#' ADSL <- teal.data::rADSL |
|
90 |
#' }) |
|
91 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
92 |
#' |
|
93 |
#' app <- init( |
|
94 |
#' data = data, |
|
95 |
#' modules = modules( |
|
96 |
#' tm_g_association( |
|
97 |
#' ref = data_extract_spec( |
|
98 |
#' dataname = "ADSL", |
|
99 |
#' select = select_spec( |
|
100 |
#' label = "Select variable:", |
|
101 |
#' choices = variable_choices( |
|
102 |
#' data[["ADSL"]], |
|
103 |
#' c("SEX", "RACE", "COUNTRY", "ARM", "STRATA1", "STRATA2", "ITTFL", "BMRKR2") |
|
104 |
#' ), |
|
105 |
#' selected = "RACE", |
|
106 |
#' fixed = FALSE |
|
107 |
#' ) |
|
108 |
#' ), |
|
109 |
#' vars = data_extract_spec( |
|
110 |
#' dataname = "ADSL", |
|
111 |
#' select = select_spec( |
|
112 |
#' label = "Select variables:", |
|
113 |
#' choices = variable_choices( |
|
114 |
#' data[["ADSL"]], |
|
115 |
#' c("SEX", "RACE", "COUNTRY", "ARM", "STRATA1", "STRATA2", "ITTFL", "BMRKR2") |
|
116 |
#' ), |
|
117 |
#' selected = "BMRKR2", |
|
118 |
#' multiple = TRUE, |
|
119 |
#' fixed = FALSE |
|
120 |
#' ) |
|
121 |
#' ) |
|
122 |
#' ) |
|
123 |
#' ) |
|
124 |
#' ) |
|
125 |
#' if (interactive()) { |
|
126 |
#' shinyApp(app$ui, app$server) |
|
127 |
#' } |
|
128 |
#' |
|
129 |
#' @export |
|
130 |
#' |
|
131 |
tm_g_association <- function(label = "Association", |
|
132 |
ref, |
|
133 |
vars, |
|
134 |
show_association = TRUE, |
|
135 |
plot_height = c(600, 400, 5000), |
|
136 |
plot_width = NULL, |
|
137 |
distribution_theme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), # nolint: line_length. |
|
138 |
association_theme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), # nolint: line_length. |
|
139 |
pre_output = NULL, |
|
140 |
post_output = NULL, |
|
141 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
142 |
decorators = NULL) { |
|
143 | ! |
message("Initializing tm_g_association") |
144 | ||
145 |
# Normalize the parameters |
|
146 | ! |
if (inherits(ref, "data_extract_spec")) ref <- list(ref) |
147 | ! |
if (inherits(vars, "data_extract_spec")) vars <- list(vars) |
148 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
149 | ||
150 |
# Start of assertions |
|
151 | ! |
checkmate::assert_string(label) |
152 | ||
153 | ! |
checkmate::assert_list(ref, types = "data_extract_spec") |
154 | ! |
if (!all(vapply(ref, function(x) !x$select$multiple, logical(1)))) { |
155 | ! |
stop("'ref' should not allow multiple selection") |
156 |
} |
|
157 | ||
158 | ! |
checkmate::assert_list(vars, types = "data_extract_spec") |
159 | ! |
checkmate::assert_flag(show_association) |
160 | ||
161 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
162 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
163 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
164 | ! |
checkmate::assert_numeric( |
165 | ! |
plot_width[1], |
166 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
167 |
) |
|
168 | ||
169 | ! |
distribution_theme <- match.arg(distribution_theme) |
170 | ! |
association_theme <- match.arg(association_theme) |
171 | ||
172 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
173 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
174 | ||
175 | ! |
plot_choices <- c("Bivariate1", "Bivariate2") |
176 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
177 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
178 | ||
179 | ! |
decorators <- normalize_decorators(decorators) |
180 | ! |
assert_decorators(decorators, null.ok = TRUE, "plot") |
181 |
# End of assertions |
|
182 | ||
183 |
# Make UI args |
|
184 | ! |
args <- as.list(environment()) |
185 | ||
186 | ! |
data_extract_list <- list( |
187 | ! |
ref = ref, |
188 | ! |
vars = vars |
189 |
) |
|
190 | ||
191 | ! |
ans <- module( |
192 | ! |
label = label, |
193 | ! |
server = srv_tm_g_association, |
194 | ! |
ui = ui_tm_g_association, |
195 | ! |
ui_args = args, |
196 | ! |
server_args = c( |
197 | ! |
data_extract_list, |
198 | ! |
list(plot_height = plot_height, plot_width = plot_width, ggplot2_args = ggplot2_args, decorators = decorators) |
199 |
), |
|
200 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
201 |
) |
|
202 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
203 | ! |
ans |
204 |
} |
|
205 | ||
206 |
# UI function for the association module |
|
207 |
ui_tm_g_association <- function(id, ...) { |
|
208 | ! |
ns <- NS(id) |
209 | ! |
args <- list(...) |
210 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$ref, args$vars) |
211 | ||
212 | ! |
teal.widgets::standard_layout( |
213 | ! |
output = teal.widgets::white_small_well( |
214 | ! |
textOutput(ns("title")), |
215 | ! |
tags$br(), |
216 | ! |
teal.widgets::plot_with_settings_ui(id = ns("myplot")) |
217 |
), |
|
218 | ! |
encoding = tags$div( |
219 |
### Reporter |
|
220 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
221 |
### |
|
222 | ! |
tags$label("Encodings", class = "text-primary"), |
223 | ! |
teal.transform::datanames_input(args[c("ref", "vars")]), |
224 | ! |
teal.transform::data_extract_ui( |
225 | ! |
id = ns("ref"), |
226 | ! |
label = "Reference variable", |
227 | ! |
data_extract_spec = args$ref, |
228 | ! |
is_single_dataset = is_single_dataset_value |
229 |
), |
|
230 | ! |
teal.transform::data_extract_ui( |
231 | ! |
id = ns("vars"), |
232 | ! |
label = "Associated variables", |
233 | ! |
data_extract_spec = args$vars, |
234 | ! |
is_single_dataset = is_single_dataset_value |
235 |
), |
|
236 | ! |
checkboxInput( |
237 | ! |
ns("association"), |
238 | ! |
"Association with reference variable", |
239 | ! |
value = args$show_association |
240 |
), |
|
241 | ! |
checkboxInput( |
242 | ! |
ns("show_dist"), |
243 | ! |
"Scaled frequencies", |
244 | ! |
value = FALSE |
245 |
), |
|
246 | ! |
checkboxInput( |
247 | ! |
ns("log_transformation"), |
248 | ! |
"Log transformed", |
249 | ! |
value = FALSE |
250 |
), |
|
251 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")), |
252 | ! |
teal.widgets::panel_group( |
253 | ! |
teal.widgets::panel_item( |
254 | ! |
title = "Plot settings", |
255 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("alpha"), "Scatterplot opacity:", c(0.5, 0, 1), ticks = FALSE), |
256 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("size"), "Scatterplot points size:", c(2, 1, 8), ticks = FALSE), |
257 | ! |
checkboxInput(ns("swap_axes"), "Swap axes", value = FALSE), |
258 | ! |
checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = FALSE), |
259 | ! |
selectInput( |
260 | ! |
inputId = ns("distribution_theme"), |
261 | ! |
label = "Distribution theme (by ggplot):", |
262 | ! |
choices = ggplot_themes, |
263 | ! |
selected = args$distribution_theme, |
264 | ! |
multiple = FALSE |
265 |
), |
|
266 | ! |
selectInput( |
267 | ! |
inputId = ns("association_theme"), |
268 | ! |
label = "Association theme (by ggplot):", |
269 | ! |
choices = ggplot_themes, |
270 | ! |
selected = args$association_theme, |
271 | ! |
multiple = FALSE |
272 |
) |
|
273 |
) |
|
274 |
) |
|
275 |
), |
|
276 | ! |
forms = tagList( |
277 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
278 |
), |
|
279 | ! |
pre_output = args$pre_output, |
280 | ! |
post_output = args$post_output |
281 |
) |
|
282 |
} |
|
283 | ||
284 |
# Server function for the association module |
|
285 |
srv_tm_g_association <- function(id, |
|
286 |
data, |
|
287 |
reporter, |
|
288 |
filter_panel_api, |
|
289 |
ref, |
|
290 |
vars, |
|
291 |
plot_height, |
|
292 |
plot_width, |
|
293 |
ggplot2_args, |
|
294 |
decorators) { |
|
295 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
296 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
297 | ! |
checkmate::assert_class(data, "reactive") |
298 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
299 | ||
300 | ! |
moduleServer(id, function(input, output, session) { |
301 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
302 | ||
303 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
304 | ! |
data_extract = list(ref = ref, vars = vars), |
305 | ! |
datasets = data, |
306 | ! |
select_validation_rule = list( |
307 | ! |
ref = shinyvalidate::compose_rules( |
308 | ! |
shinyvalidate::sv_required("A reference variable needs to be selected."), |
309 | ! |
~ if ((.) %in% selector_list()$vars()$select) { |
310 | ! |
"Associated variables and reference variable cannot overlap" |
311 |
} |
|
312 |
), |
|
313 | ! |
vars = shinyvalidate::compose_rules( |
314 | ! |
shinyvalidate::sv_required("An associated variable needs to be selected."), |
315 | ! |
~ if (length(selector_list()$ref()$select) != 0 && selector_list()$ref()$select %in% (.)) { |
316 | ! |
"Associated variables and reference variable cannot overlap" |
317 |
} |
|
318 |
) |
|
319 |
) |
|
320 |
) |
|
321 | ||
322 | ! |
iv_r <- reactive({ |
323 | ! |
iv <- shinyvalidate::InputValidator$new() |
324 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
325 |
}) |
|
326 | ||
327 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
328 | ! |
datasets = data, |
329 | ! |
selector_list = selector_list |
330 |
) |
|
331 | ||
332 | ! |
anl_merged_q <- reactive({ |
333 | ! |
req(anl_merged_input()) |
334 | ! |
data() %>% teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
335 |
}) |
|
336 | ||
337 | ! |
merged <- list( |
338 | ! |
anl_input_r = anl_merged_input, |
339 | ! |
anl_q_r = anl_merged_q |
340 |
) |
|
341 | ||
342 | ! |
output_q <- reactive({ |
343 | ! |
teal::validate_inputs(iv_r()) |
344 | ||
345 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
346 | ! |
teal::validate_has_data(ANL, 3) |
347 | ||
348 | ! |
vars_names <- merged$anl_input_r()$columns_source$vars |
349 | ||
350 | ! |
ref_name <- as.vector(merged$anl_input_r()$columns_source$ref) |
351 | ! |
association <- input$association |
352 | ! |
show_dist <- input$show_dist |
353 | ! |
log_transformation <- input$log_transformation |
354 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
355 | ! |
swap_axes <- input$swap_axes |
356 | ! |
distribution_theme <- input$distribution_theme |
357 | ! |
association_theme <- input$association_theme |
358 | ||
359 | ! |
is_scatterplot <- is.numeric(ANL[[ref_name]]) && any(vapply(ANL[vars_names], is.numeric, logical(1))) |
360 | ! |
if (is_scatterplot) { |
361 | ! |
shinyjs::show("alpha") |
362 | ! |
shinyjs::show("size") |
363 | ! |
alpha <- input$alpha |
364 | ! |
size <- input$size |
365 |
} else { |
|
366 | ! |
shinyjs::hide("alpha") |
367 | ! |
shinyjs::hide("size") |
368 | ! |
alpha <- 0.5 |
369 | ! |
size <- 2 |
370 |
} |
|
371 | ||
372 | ! |
teal::validate_has_data(ANL[, c(ref_name, vars_names)], 3, complete = TRUE, allow_inf = FALSE) |
373 | ||
374 |
# reference |
|
375 | ! |
ref_class <- class(ANL[[ref_name]])[1] |
376 | ! |
if (is.numeric(ANL[[ref_name]]) && log_transformation) { |
377 |
# works for both integers and doubles |
|
378 | ! |
ref_cl_name <- call("log", as.name(ref_name)) |
379 | ! |
ref_cl_lbl <- varname_w_label(ref_name, ANL, prefix = "Log of ") |
380 |
} else { |
|
381 |
# silently ignore when non-numeric even if `log` is selected because some |
|
382 |
# variables may be numeric and others not |
|
383 | ! |
ref_cl_name <- as.name(ref_name) |
384 | ! |
ref_cl_lbl <- varname_w_label(ref_name, ANL) |
385 |
} |
|
386 | ||
387 | ! |
user_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
388 | ! |
user_plot = ggplot2_args[["Bivariate1"]], |
389 | ! |
user_default = ggplot2_args$default |
390 |
) |
|
391 | ||
392 | ! |
ref_call <- bivariate_plot_call( |
393 | ! |
data_name = "ANL", |
394 | ! |
x = ref_cl_name, |
395 | ! |
x_class = ref_class, |
396 | ! |
x_label = ref_cl_lbl, |
397 | ! |
freq = !show_dist, |
398 | ! |
theme = distribution_theme, |
399 | ! |
rotate_xaxis_labels = rotate_xaxis_labels, |
400 | ! |
swap_axes = FALSE, |
401 | ! |
size = size, |
402 | ! |
alpha = alpha, |
403 | ! |
ggplot2_args = user_ggplot2_args |
404 |
) |
|
405 | ||
406 |
# association |
|
407 | ! |
ref_class_cov <- ifelse(association, ref_class, "NULL") |
408 | ||
409 | ! |
var_calls <- lapply(vars_names, function(var_i) { |
410 | ! |
var_class <- class(ANL[[var_i]])[1] |
411 | ! |
if (is.numeric(ANL[[var_i]]) && log_transformation) { |
412 |
# works for both integers and doubles |
|
413 | ! |
var_cl_name <- call("log", as.name(var_i)) |
414 | ! |
var_cl_lbl <- varname_w_label(var_i, ANL, prefix = "Log of ") |
415 |
} else { |
|
416 |
# silently ignore when non-numeric even if `log` is selected because some |
|
417 |
# variables may be numeric and others not |
|
418 | ! |
var_cl_name <- as.name(var_i) |
419 | ! |
var_cl_lbl <- varname_w_label(var_i, ANL) |
420 |
} |
|
421 | ||
422 | ! |
user_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
423 | ! |
user_plot = ggplot2_args[["Bivariate2"]], |
424 | ! |
user_default = ggplot2_args$default |
425 |
) |
|
426 | ||
427 | ! |
bivariate_plot_call( |
428 | ! |
data_name = "ANL", |
429 | ! |
x = ref_cl_name, |
430 | ! |
y = var_cl_name, |
431 | ! |
x_class = ref_class_cov, |
432 | ! |
y_class = var_class, |
433 | ! |
x_label = ref_cl_lbl, |
434 | ! |
y_label = var_cl_lbl, |
435 | ! |
theme = association_theme, |
436 | ! |
freq = !show_dist, |
437 | ! |
rotate_xaxis_labels = rotate_xaxis_labels, |
438 | ! |
swap_axes = swap_axes, |
439 | ! |
alpha = alpha, |
440 | ! |
size = size, |
441 | ! |
ggplot2_args = user_ggplot2_args |
442 |
) |
|
443 |
}) |
|
444 | ||
445 |
# helper function to format variable name |
|
446 | ! |
format_varnames <- function(x) { |
447 | ! |
if (is.numeric(ANL[[x]]) && log_transformation) { |
448 | ! |
varname_w_label(x, ANL, prefix = "Log of ") |
449 |
} else { |
|
450 | ! |
varname_w_label(x, ANL) |
451 |
} |
|
452 |
} |
|
453 | ! |
new_title <- |
454 | ! |
if (association) { |
455 | ! |
switch(as.character(length(vars_names)), |
456 | ! |
"0" = sprintf("Value distribution for %s", ref_cl_lbl), |
457 | ! |
"1" = sprintf( |
458 | ! |
"Association between %s and %s", |
459 | ! |
ref_cl_lbl, |
460 | ! |
format_varnames(vars_names) |
461 |
), |
|
462 | ! |
sprintf( |
463 | ! |
"Associations between %s and: %s", |
464 | ! |
ref_cl_lbl, |
465 | ! |
paste(lapply(vars_names, format_varnames), collapse = ", ") |
466 |
) |
|
467 |
) |
|
468 |
} else { |
|
469 | ! |
switch(as.character(length(vars_names)), |
470 | ! |
"0" = sprintf("Value distribution for %s", ref_cl_lbl), |
471 | ! |
sprintf( |
472 | ! |
"Value distributions for %s and %s", |
473 | ! |
ref_cl_lbl, |
474 | ! |
paste(lapply(vars_names, format_varnames), collapse = ", ") |
475 |
) |
|
476 |
) |
|
477 |
} |
|
478 | ! |
teal.code::eval_code( |
479 | ! |
merged$anl_q_r(), |
480 | ! |
substitute( |
481 | ! |
expr = title <- new_title, |
482 | ! |
env = list(new_title = new_title) |
483 |
) |
|
484 |
) %>% |
|
485 | ! |
teal.code::eval_code( |
486 | ! |
substitute( |
487 | ! |
expr = { |
488 | ! |
plot_top <- plot_calls[[1]] |
489 | ! |
plot_bottom <- plot_calls[[1]] |
490 | ! |
plot <- tern::stack_grobs(grobs = lapply(list(plot_top, plot_bottom), ggplotGrob)) |
491 |
}, |
|
492 | ! |
env = list( |
493 | ! |
plot_calls = do.call( |
494 | ! |
"call", |
495 | ! |
c(list("list", ref_call), var_calls), |
496 | ! |
quote = TRUE |
497 |
) |
|
498 |
) |
|
499 |
) |
|
500 |
) |
|
501 |
}) |
|
502 | ||
503 | ! |
decorated_output_grob_q <- srv_decorate_teal_data( |
504 | ! |
id = "decorator", |
505 | ! |
data = output_q, |
506 | ! |
decorators = select_decorators(decorators, "plot"), |
507 | ! |
expr = { |
508 | ! |
grid::grid.newpage() |
509 | ! |
grid::grid.draw(plot) |
510 |
} |
|
511 |
) |
|
512 | ||
513 | ! |
plot_r <- reactive({ |
514 | ! |
req(iv_r()$is_valid()) |
515 | ! |
req(decorated_output_grob_q())[["plot"]] |
516 |
}) |
|
517 | ||
518 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
519 | ! |
id = "myplot", |
520 | ! |
plot_r = plot_r, |
521 | ! |
height = plot_height, |
522 | ! |
width = plot_width |
523 |
) |
|
524 | ||
525 | ! |
output$title <- renderText({ |
526 | ! |
teal.code::dev_suppress(output_q()[["title"]]) |
527 |
}) |
|
528 | ||
529 | ! |
teal.widgets::verbatim_popup_srv( |
530 | ! |
id = "rcode", |
531 | ! |
verbatim_content = reactive(teal.code::get_code(req(decorated_output_grob_q()))), |
532 | ! |
title = "Association Plot" |
533 |
) |
|
534 | ||
535 |
### REPORTER |
|
536 | ! |
if (with_reporter) { |
537 | ! |
card_fun <- function(comment, label) { |
538 | ! |
card <- teal::report_card_template( |
539 | ! |
title = "Association Plot", |
540 | ! |
label = label, |
541 | ! |
with_filter = with_filter, |
542 | ! |
filter_panel_api = filter_panel_api |
543 |
) |
|
544 | ! |
card$append_text("Plot", "header3") |
545 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
546 | ! |
if (!comment == "") { |
547 | ! |
card$append_text("Comment", "header3") |
548 | ! |
card$append_text(comment) |
549 |
} |
|
550 | ! |
card$append_src(teal.code::get_code(req(decorated_output_grob_q()))) |
551 | ! |
card |
552 |
} |
|
553 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
554 |
} |
|
555 |
### |
|
556 |
}) |
|
557 |
} |
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 decorators `r roxygen_decorators_param("tm_t_crosstable")` |
|
23 |
#' |
|
24 |
#' @note For more examples, please see the vignette "Using cross table" via |
|
25 |
#' `vignette("using-cross-table", package = "teal.modules.general")`. |
|
26 |
#' |
|
27 |
#' @inherit shared_params return |
|
28 |
#' |
|
29 |
#' @section Decorating `tm_t_crosstable`: |
|
30 |
#' |
|
31 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
32 |
#' - `table` (`ElementaryTable` - output of `rtables::build_table`) |
|
33 |
#' |
|
34 |
#' For additional details and examples of decorators, refer to the vignette |
|
35 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
36 |
#' |
|
37 |
#' @examplesShinylive |
|
38 |
#' library(teal.modules.general) |
|
39 |
#' interactive <- function() TRUE |
|
40 |
#' {{ next_example }} |
|
41 |
#' @examplesIf require("rtables", quietly = TRUE) |
|
42 |
#' # general data example |
|
43 |
#' data <- teal_data() |
|
44 |
#' data <- within(data, { |
|
45 |
#' mtcars <- mtcars |
|
46 |
#' for (v in c("cyl", "vs", "am", "gear")) { |
|
47 |
#' mtcars[[v]] <- as.factor(mtcars[[v]]) |
|
48 |
#' } |
|
49 |
#' mtcars[["primary_key"]] <- seq_len(nrow(mtcars)) |
|
50 |
#' }) |
|
51 |
#' join_keys(data) <- join_keys(join_key("mtcars", "mtcars", "primary_key")) |
|
52 |
#' |
|
53 |
#' app <- init( |
|
54 |
#' data = data, |
|
55 |
#' modules = modules( |
|
56 |
#' tm_t_crosstable( |
|
57 |
#' label = "Cross Table", |
|
58 |
#' x = data_extract_spec( |
|
59 |
#' dataname = "mtcars", |
|
60 |
#' select = select_spec( |
|
61 |
#' label = "Select variable:", |
|
62 |
#' choices = variable_choices(data[["mtcars"]], c("cyl", "vs", "am", "gear")), |
|
63 |
#' selected = c("cyl", "gear"), |
|
64 |
#' multiple = TRUE, |
|
65 |
#' ordered = TRUE, |
|
66 |
#' fixed = FALSE |
|
67 |
#' ) |
|
68 |
#' ), |
|
69 |
#' y = data_extract_spec( |
|
70 |
#' dataname = "mtcars", |
|
71 |
#' select = select_spec( |
|
72 |
#' label = "Select variable:", |
|
73 |
#' choices = variable_choices(data[["mtcars"]], c("cyl", "vs", "am", "gear")), |
|
74 |
#' selected = "vs", |
|
75 |
#' multiple = FALSE, |
|
76 |
#' fixed = FALSE |
|
77 |
#' ) |
|
78 |
#' ) |
|
79 |
#' ) |
|
80 |
#' ) |
|
81 |
#' ) |
|
82 |
#' if (interactive()) { |
|
83 |
#' shinyApp(app$ui, app$server) |
|
84 |
#' } |
|
85 |
#' |
|
86 |
#' @examplesShinylive |
|
87 |
#' library(teal.modules.general) |
|
88 |
#' interactive <- function() TRUE |
|
89 |
#' {{ next_example }} |
|
90 |
#' @examplesIf require("rtables", quietly = TRUE) |
|
91 |
#' # CDISC data example |
|
92 |
#' data <- teal_data() |
|
93 |
#' data <- within(data, { |
|
94 |
#' ADSL <- teal.data::rADSL |
|
95 |
#' }) |
|
96 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
97 |
#' |
|
98 |
#' app <- init( |
|
99 |
#' data = data, |
|
100 |
#' modules = modules( |
|
101 |
#' tm_t_crosstable( |
|
102 |
#' label = "Cross Table", |
|
103 |
#' x = data_extract_spec( |
|
104 |
#' dataname = "ADSL", |
|
105 |
#' select = select_spec( |
|
106 |
#' label = "Select variable:", |
|
107 |
#' choices = variable_choices(data[["ADSL"]], subset = function(data) { |
|
108 |
#' idx <- !vapply(data, inherits, logical(1), c("Date", "POSIXct", "POSIXlt")) |
|
109 |
#' return(names(data)[idx]) |
|
110 |
#' }), |
|
111 |
#' selected = "COUNTRY", |
|
112 |
#' multiple = TRUE, |
|
113 |
#' ordered = TRUE, |
|
114 |
#' fixed = FALSE |
|
115 |
#' ) |
|
116 |
#' ), |
|
117 |
#' y = data_extract_spec( |
|
118 |
#' dataname = "ADSL", |
|
119 |
#' select = select_spec( |
|
120 |
#' label = "Select variable:", |
|
121 |
#' choices = variable_choices(data[["ADSL"]], subset = function(data) { |
|
122 |
#' idx <- vapply(data, is.factor, logical(1)) |
|
123 |
#' return(names(data)[idx]) |
|
124 |
#' }), |
|
125 |
#' selected = "SEX", |
|
126 |
#' multiple = FALSE, |
|
127 |
#' fixed = FALSE |
|
128 |
#' ) |
|
129 |
#' ) |
|
130 |
#' ) |
|
131 |
#' ) |
|
132 |
#' ) |
|
133 |
#' if (interactive()) { |
|
134 |
#' shinyApp(app$ui, app$server) |
|
135 |
#' } |
|
136 |
#' |
|
137 |
#' @export |
|
138 |
#' |
|
139 |
tm_t_crosstable <- function(label = "Cross Table", |
|
140 |
x, |
|
141 |
y, |
|
142 |
show_percentage = TRUE, |
|
143 |
show_total = TRUE, |
|
144 |
pre_output = NULL, |
|
145 |
post_output = NULL, |
|
146 |
basic_table_args = teal.widgets::basic_table_args(), |
|
147 |
decorators = NULL) { |
|
148 | ! |
message("Initializing tm_t_crosstable") |
149 | ||
150 |
# Requires Suggested packages |
|
151 | ! |
if (!requireNamespace("rtables", quietly = TRUE)) { |
152 | ! |
stop("Cannot load rtables - please install the package or restart your session.") |
153 |
} |
|
154 | ||
155 |
# Normalize the parameters |
|
156 | ! |
if (inherits(x, "data_extract_spec")) x <- list(x) |
157 | ! |
if (inherits(y, "data_extract_spec")) y <- list(y) |
158 | ||
159 |
# Start of assertions |
|
160 | ! |
checkmate::assert_string(label) |
161 | ! |
checkmate::assert_list(x, types = "data_extract_spec") |
162 | ||
163 | ! |
checkmate::assert_list(y, types = "data_extract_spec") |
164 | ! |
assert_single_selection(y) |
165 | ||
166 | ! |
checkmate::assert_flag(show_percentage) |
167 | ! |
checkmate::assert_flag(show_total) |
168 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
169 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
170 | ! |
checkmate::assert_class(basic_table_args, classes = "basic_table_args") |
171 | ||
172 | ! |
decorators <- normalize_decorators(decorators) |
173 | ! |
assert_decorators(decorators, null.ok = TRUE, "plot") |
174 |
# End of assertions |
|
175 | ||
176 |
# Make UI args |
|
177 | ! |
ui_args <- as.list(environment()) |
178 | ||
179 | ! |
server_args <- list( |
180 | ! |
label = label, |
181 | ! |
x = x, |
182 | ! |
y = y, |
183 | ! |
basic_table_args = basic_table_args, |
184 | ! |
decorators = decorators |
185 |
) |
|
186 | ||
187 | ! |
ans <- module( |
188 | ! |
label = label, |
189 | ! |
server = srv_t_crosstable, |
190 | ! |
ui = ui_t_crosstable, |
191 | ! |
ui_args = ui_args, |
192 | ! |
server_args = server_args, |
193 | ! |
datanames = teal.transform::get_extract_datanames(list(x = x, y = y)) |
194 |
) |
|
195 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
196 | ! |
ans |
197 |
} |
|
198 | ||
199 |
# UI function for the cross-table module |
|
200 |
ui_t_crosstable <- function(id, x, y, show_percentage, show_total, pre_output, post_output, ...) { |
|
201 | ! |
args <- list(...) |
202 | ! |
ns <- NS(id) |
203 | ! |
is_single_dataset <- teal.transform::is_single_dataset(x, y) |
204 | ||
205 | ! |
join_default_options <- c( |
206 | ! |
"Full Join" = "dplyr::full_join", |
207 | ! |
"Inner Join" = "dplyr::inner_join", |
208 | ! |
"Left Join" = "dplyr::left_join", |
209 | ! |
"Right Join" = "dplyr::right_join" |
210 |
) |
|
211 | ||
212 | ! |
teal.widgets::standard_layout( |
213 | ! |
output = teal.widgets::white_small_well( |
214 | ! |
textOutput(ns("title")), |
215 | ! |
teal.widgets::table_with_settings_ui(ns("table")) |
216 |
), |
|
217 | ! |
encoding = tags$div( |
218 |
### Reporter |
|
219 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
220 |
### |
|
221 | ! |
tags$label("Encodings", class = "text-primary"), |
222 | ! |
teal.transform::datanames_input(list(x, y)), |
223 | ! |
teal.transform::data_extract_ui(ns("x"), label = "Row values", x, is_single_dataset = is_single_dataset), |
224 | ! |
teal.transform::data_extract_ui(ns("y"), label = "Column values", y, is_single_dataset = is_single_dataset), |
225 | ! |
teal.widgets::optionalSelectInput( |
226 | ! |
ns("join_fun"), |
227 | ! |
label = "Row to Column type of join", |
228 | ! |
choices = join_default_options, |
229 | ! |
selected = join_default_options[1], |
230 | ! |
multiple = FALSE |
231 |
), |
|
232 | ! |
tags$hr(), |
233 | ! |
teal.widgets::panel_group( |
234 | ! |
teal.widgets::panel_item( |
235 | ! |
title = "Table settings", |
236 | ! |
checkboxInput(ns("show_percentage"), "Show column percentage", value = show_percentage), |
237 | ! |
checkboxInput(ns("show_total"), "Show total column", value = show_total) |
238 |
) |
|
239 |
), |
|
240 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")) |
241 |
), |
|
242 | ! |
forms = tagList( |
243 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
244 |
), |
|
245 | ! |
pre_output = pre_output, |
246 | ! |
post_output = post_output |
247 |
) |
|
248 |
} |
|
249 | ||
250 |
# Server function for the cross-table module |
|
251 |
srv_t_crosstable <- function(id, data, reporter, filter_panel_api, label, x, y, basic_table_args, decorators) { |
|
252 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
253 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
254 | ! |
checkmate::assert_class(data, "reactive") |
255 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
256 | ! |
moduleServer(id, function(input, output, session) { |
257 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
258 | ||
259 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
260 | ! |
data_extract = list(x = x, y = y), |
261 | ! |
datasets = data, |
262 | ! |
select_validation_rule = list( |
263 | ! |
x = shinyvalidate::sv_required("Please define column for row variable."), |
264 | ! |
y = shinyvalidate::sv_required("Please define column for column variable.") |
265 |
) |
|
266 |
) |
|
267 | ||
268 | ! |
iv_r <- reactive({ |
269 | ! |
iv <- shinyvalidate::InputValidator$new() |
270 | ! |
iv$add_rule("join_fun", function(value) { |
271 | ! |
if (!identical(selector_list()$x()$dataname, selector_list()$y()$dataname)) { |
272 | ! |
if (!shinyvalidate::input_provided(value)) { |
273 | ! |
"Please select a joining function." |
274 |
} |
|
275 |
} |
|
276 |
}) |
|
277 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
278 |
}) |
|
279 | ||
280 | ! |
observeEvent( |
281 | ! |
eventExpr = { |
282 | ! |
req(!is.null(selector_list()$x()) && !is.null(selector_list()$y())) |
283 | ! |
list(selector_list()$x(), selector_list()$y()) |
284 |
}, |
|
285 | ! |
handlerExpr = { |
286 | ! |
if (identical(selector_list()$x()$dataname, selector_list()$y()$dataname)) { |
287 | ! |
shinyjs::hide("join_fun") |
288 |
} else { |
|
289 | ! |
shinyjs::show("join_fun") |
290 |
} |
|
291 |
} |
|
292 |
) |
|
293 | ||
294 | ! |
merge_function <- reactive({ |
295 | ! |
if (is.null(input$join_fun)) { |
296 | ! |
"dplyr::full_join" |
297 |
} else { |
|
298 | ! |
input$join_fun |
299 |
} |
|
300 |
}) |
|
301 | ||
302 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
303 | ! |
datasets = data, |
304 | ! |
selector_list = selector_list, |
305 | ! |
merge_function = merge_function |
306 |
) |
|
307 | ||
308 | ! |
anl_merged_q <- reactive({ |
309 | ! |
req(anl_merged_input()) |
310 | ! |
data() %>% |
311 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
312 |
}) |
|
313 | ||
314 | ! |
merged <- list( |
315 | ! |
anl_input_r = anl_merged_input, |
316 | ! |
anl_q_r = anl_merged_q |
317 |
) |
|
318 | ||
319 | ! |
output_q <- reactive({ |
320 | ! |
teal::validate_inputs(iv_r()) |
321 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
322 | ||
323 |
# As this is a summary |
|
324 | ! |
x_name <- as.vector(merged$anl_input_r()$columns_source$x) |
325 | ! |
y_name <- as.vector(merged$anl_input_r()$columns_source$y) |
326 | ||
327 | ! |
teal::validate_has_data(ANL, 3) |
328 | ! |
teal::validate_has_data(ANL[, c(x_name, y_name)], 3, complete = TRUE, allow_inf = FALSE) |
329 | ||
330 | ! |
is_allowed_class <- function(x) is.numeric(x) || is.factor(x) || is.character(x) || is.logical(x) |
331 | ! |
validate(need( |
332 | ! |
all(vapply(ANL[x_name], is_allowed_class, logical(1))), |
333 | ! |
"Selected row variable has an unsupported data type." |
334 |
)) |
|
335 | ! |
validate(need( |
336 | ! |
is_allowed_class(ANL[[y_name]]), |
337 | ! |
"Selected column variable has an unsupported data type." |
338 |
)) |
|
339 | ||
340 | ! |
show_percentage <- input$show_percentage |
341 | ! |
show_total <- input$show_total |
342 | ||
343 | ! |
plot_title <- paste( |
344 | ! |
"Cross-Table of", |
345 | ! |
paste0(varname_w_label(x_name, ANL), collapse = ", "), |
346 | ! |
"(rows)", "vs.", |
347 | ! |
varname_w_label(y_name, ANL), |
348 | ! |
"(columns)" |
349 |
) |
|
350 | ||
351 | ! |
labels_vec <- vapply( |
352 | ! |
x_name, |
353 | ! |
varname_w_label, |
354 | ! |
character(1), |
355 | ! |
ANL |
356 |
) |
|
357 | ||
358 | ! |
teal.code::eval_code( |
359 | ! |
merged$anl_q_r(), |
360 | ! |
substitute( |
361 | ! |
expr = { |
362 | ! |
title <- plot_title |
363 |
}, |
|
364 | ! |
env = list(plot_title = plot_title) |
365 |
) |
|
366 |
) %>% |
|
367 | ! |
teal.code::eval_code( |
368 | ! |
substitute( |
369 | ! |
expr = { |
370 | ! |
table <- basic_tables %>% |
371 | ! |
split_call %>% # styler: off |
372 | ! |
rtables::add_colcounts() %>% |
373 | ! |
tern::analyze_vars( |
374 | ! |
vars = x_name, |
375 | ! |
var_labels = labels_vec, |
376 | ! |
na.rm = FALSE, |
377 | ! |
denom = "N_col", |
378 | ! |
.stats = c("mean_sd", "median", "range", count_value) |
379 |
) |
|
380 |
}, |
|
381 | ! |
env = list( |
382 | ! |
basic_tables = teal.widgets::parse_basic_table_args( |
383 | ! |
basic_table_args = teal.widgets::resolve_basic_table_args(basic_table_args) |
384 |
), |
|
385 | ! |
split_call = if (show_total) { |
386 | ! |
substitute( |
387 | ! |
expr = rtables::split_cols_by( |
388 | ! |
y_name, |
389 | ! |
split_fun = rtables::add_overall_level(label = "Total", first = FALSE) |
390 |
), |
|
391 | ! |
env = list(y_name = y_name) |
392 |
) |
|
393 |
} else { |
|
394 | ! |
substitute(rtables::split_cols_by(y_name), env = list(y_name = y_name)) |
395 |
}, |
|
396 | ! |
x_name = x_name, |
397 | ! |
labels_vec = labels_vec, |
398 | ! |
count_value = ifelse(show_percentage, "count_fraction", "count") |
399 |
) |
|
400 |
) |
|
401 |
) %>% |
|
402 | ! |
teal.code::eval_code( |
403 | ! |
substitute( |
404 | ! |
expr = { |
405 | ! |
ANL <- tern::df_explicit_na(ANL) |
406 | ! |
table <- rtables::build_table(lyt = table, df = ANL[order(ANL[[y_name]]), ]) |
407 |
}, |
|
408 | ! |
env = list(y_name = y_name) |
409 |
) |
|
410 |
) |
|
411 |
}) |
|
412 | ||
413 | ! |
decorated_output_q <- srv_decorate_teal_data( |
414 | ! |
id = "decorator", |
415 | ! |
data = output_q, |
416 | ! |
decorators = select_decorators(decorators, "plot"), |
417 | ! |
expr = table |
418 |
) |
|
419 | ||
420 | ! |
output$title <- renderText(req(decorated_output_q())[["title"]]) |
421 | ||
422 | ! |
table_r <- reactive({ |
423 | ! |
req(iv_r()$is_valid()) |
424 | ! |
req(decorated_output_q())[["table"]] |
425 |
}) |
|
426 | ||
427 | ! |
teal.widgets::table_with_settings_srv( |
428 | ! |
id = "table", |
429 | ! |
table_r = table_r |
430 |
) |
|
431 | ||
432 | ! |
teal.widgets::verbatim_popup_srv( |
433 | ! |
id = "rcode", |
434 | ! |
verbatim_content = reactive(teal.code::get_code(req(decorated_output_q()))), |
435 | ! |
title = "Show R Code for Cross-Table" |
436 |
) |
|
437 | ||
438 |
### REPORTER |
|
439 | ! |
if (with_reporter) { |
440 | ! |
card_fun <- function(comment, label) { |
441 | ! |
card <- teal::report_card_template( |
442 | ! |
title = "Cross Table", |
443 | ! |
label = label, |
444 | ! |
with_filter = with_filter, |
445 | ! |
filter_panel_api = filter_panel_api |
446 |
) |
|
447 | ! |
card$append_text("Table", "header3") |
448 | ! |
card$append_table(table_r()) |
449 | ! |
if (!comment == "") { |
450 | ! |
card$append_text("Comment", "header3") |
451 | ! |
card$append_text(comment) |
452 |
} |
|
453 | ! |
card$append_src(teal.code::get_code(req(decorated_output_q()))) |
454 | ! |
card |
455 |
} |
|
456 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
457 |
} |
|
458 |
### |
|
459 |
}) |
|
460 |
} |
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 |
#' @param decorators `r roxygen_decorators_param("tm_g_response")` |
|
37 |
#' |
|
38 |
#' @inherit shared_params return |
|
39 |
#' |
|
40 |
#' @note For more examples, please see the vignette "Using response plot" via |
|
41 |
#' `vignette("using-response-plot", package = "teal.modules.general")`. |
|
42 |
#' |
|
43 |
#' @section Decorating `tm_g_response`: |
|
44 |
#' |
|
45 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
46 |
#' - `plot` (`ggplot2`) |
|
47 |
#' |
|
48 |
#' For additional details and examples of decorators, refer to the vignette |
|
49 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
50 |
#' |
|
51 |
#' @examplesShinylive |
|
52 |
#' library(teal.modules.general) |
|
53 |
#' interactive <- function() TRUE |
|
54 |
#' {{ next_example }} |
|
55 |
#' @examples |
|
56 |
#' # general data example |
|
57 |
#' data <- teal_data() |
|
58 |
#' data <- within(data, { |
|
59 |
#' require(nestcolor) |
|
60 |
#' mtcars <- mtcars |
|
61 |
#' for (v in c("cyl", "vs", "am", "gear")) { |
|
62 |
#' mtcars[[v]] <- as.factor(mtcars[[v]]) |
|
63 |
#' } |
|
64 |
#' }) |
|
65 |
#' |
|
66 |
#' app <- init( |
|
67 |
#' data = data, |
|
68 |
#' modules = modules( |
|
69 |
#' tm_g_response( |
|
70 |
#' label = "Response Plots", |
|
71 |
#' response = data_extract_spec( |
|
72 |
#' dataname = "mtcars", |
|
73 |
#' select = select_spec( |
|
74 |
#' label = "Select variable:", |
|
75 |
#' choices = variable_choices(data[["mtcars"]], c("cyl", "gear")), |
|
76 |
#' selected = "cyl", |
|
77 |
#' multiple = FALSE, |
|
78 |
#' fixed = FALSE |
|
79 |
#' ) |
|
80 |
#' ), |
|
81 |
#' x = data_extract_spec( |
|
82 |
#' dataname = "mtcars", |
|
83 |
#' select = select_spec( |
|
84 |
#' label = "Select variable:", |
|
85 |
#' choices = variable_choices(data[["mtcars"]], c("vs", "am")), |
|
86 |
#' selected = "vs", |
|
87 |
#' multiple = FALSE, |
|
88 |
#' fixed = FALSE |
|
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 |
#' # CDISC data example |
|
104 |
#' data <- teal_data() |
|
105 |
#' data <- within(data, { |
|
106 |
#' require(nestcolor) |
|
107 |
#' ADSL <- teal.data::rADSL |
|
108 |
#' }) |
|
109 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
110 |
#' |
|
111 |
#' app <- init( |
|
112 |
#' data = data, |
|
113 |
#' modules = modules( |
|
114 |
#' tm_g_response( |
|
115 |
#' label = "Response Plots", |
|
116 |
#' response = data_extract_spec( |
|
117 |
#' dataname = "ADSL", |
|
118 |
#' select = select_spec( |
|
119 |
#' label = "Select variable:", |
|
120 |
#' choices = variable_choices(data[["ADSL"]], c("BMRKR2", "COUNTRY")), |
|
121 |
#' selected = "BMRKR2", |
|
122 |
#' multiple = FALSE, |
|
123 |
#' fixed = FALSE |
|
124 |
#' ) |
|
125 |
#' ), |
|
126 |
#' x = data_extract_spec( |
|
127 |
#' dataname = "ADSL", |
|
128 |
#' select = select_spec( |
|
129 |
#' label = "Select variable:", |
|
130 |
#' choices = variable_choices(data[["ADSL"]], c("SEX", "RACE")), |
|
131 |
#' selected = "RACE", |
|
132 |
#' multiple = FALSE, |
|
133 |
#' fixed = FALSE |
|
134 |
#' ) |
|
135 |
#' ) |
|
136 |
#' ) |
|
137 |
#' ) |
|
138 |
#' ) |
|
139 |
#' if (interactive()) { |
|
140 |
#' shinyApp(app$ui, app$server) |
|
141 |
#' } |
|
142 |
#' |
|
143 |
#' @export |
|
144 |
#' |
|
145 |
tm_g_response <- function(label = "Response Plot", |
|
146 |
response, |
|
147 |
x, |
|
148 |
row_facet = NULL, |
|
149 |
col_facet = NULL, |
|
150 |
coord_flip = FALSE, |
|
151 |
count_labels = TRUE, |
|
152 |
rotate_xaxis_labels = FALSE, |
|
153 |
freq = FALSE, |
|
154 |
plot_height = c(600, 400, 5000), |
|
155 |
plot_width = NULL, |
|
156 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
157 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
158 |
pre_output = NULL, |
|
159 |
post_output = NULL, |
|
160 |
decorators = NULL) { |
|
161 | ! |
message("Initializing tm_g_response") |
162 | ||
163 |
# Normalize the parameters |
|
164 | ! |
if (inherits(response, "data_extract_spec")) response <- list(response) |
165 | ! |
if (inherits(x, "data_extract_spec")) x <- list(x) |
166 | ! |
if (inherits(row_facet, "data_extract_spec")) row_facet <- list(row_facet) |
167 | ! |
if (inherits(col_facet, "data_extract_spec")) col_facet <- list(col_facet) |
168 | ||
169 |
# Start of assertions |
|
170 | ! |
checkmate::assert_string(label) |
171 | ||
172 | ! |
checkmate::assert_list(response, types = "data_extract_spec") |
173 | ! |
if (!all(vapply(response, function(x) !("" %in% x$select$choices), logical(1)))) { |
174 | ! |
stop("'response' should not allow empty values") |
175 |
} |
|
176 | ! |
assert_single_selection(response) |
177 | ||
178 | ! |
checkmate::assert_list(x, types = "data_extract_spec") |
179 | ! |
if (!all(vapply(x, function(x) !("" %in% x$select$choices), logical(1)))) { |
180 | ! |
stop("'x' should not allow empty values") |
181 |
} |
|
182 | ! |
assert_single_selection(x) |
183 | ||
184 | ! |
checkmate::assert_list(row_facet, types = "data_extract_spec", null.ok = TRUE) |
185 | ! |
checkmate::assert_list(col_facet, types = "data_extract_spec", null.ok = TRUE) |
186 | ! |
checkmate::assert_flag(coord_flip) |
187 | ! |
checkmate::assert_flag(count_labels) |
188 | ! |
checkmate::assert_flag(rotate_xaxis_labels) |
189 | ! |
checkmate::assert_flag(freq) |
190 | ||
191 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
192 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
193 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
194 | ! |
checkmate::assert_numeric( |
195 | ! |
plot_width[1], |
196 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
197 |
) |
|
198 | ||
199 | ! |
ggtheme <- match.arg(ggtheme) |
200 | ! |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
201 | ||
202 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
203 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
204 | ||
205 | ! |
decorators <- normalize_decorators(decorators) |
206 | ! |
assert_decorators(decorators, null.ok = TRUE, "plot") |
207 |
# End of assertions |
|
208 | ||
209 |
# Make UI args |
|
210 | ! |
args <- as.list(environment()) |
211 | ||
212 | ! |
data_extract_list <- list( |
213 | ! |
response = response, |
214 | ! |
x = x, |
215 | ! |
row_facet = row_facet, |
216 | ! |
col_facet = col_facet |
217 |
) |
|
218 | ||
219 | ! |
ans <- module( |
220 | ! |
label = label, |
221 | ! |
server = srv_g_response, |
222 | ! |
ui = ui_g_response, |
223 | ! |
ui_args = args, |
224 | ! |
server_args = c( |
225 | ! |
data_extract_list, |
226 | ! |
list( |
227 | ! |
plot_height = plot_height, |
228 | ! |
plot_width = plot_width, |
229 | ! |
ggplot2_args = ggplot2_args, |
230 | ! |
decorators = decorators |
231 |
) |
|
232 |
), |
|
233 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
234 |
) |
|
235 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
236 | ! |
ans |
237 |
} |
|
238 | ||
239 |
# UI function for the response module |
|
240 |
ui_g_response <- function(id, ...) { |
|
241 | ! |
ns <- NS(id) |
242 | ! |
args <- list(...) |
243 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$response, args$x, args$row_facet, args$col_facet) |
244 | ||
245 | ! |
teal.widgets::standard_layout( |
246 | ! |
output = teal.widgets::white_small_well( |
247 | ! |
teal.widgets::plot_with_settings_ui(id = ns("myplot")) |
248 |
), |
|
249 | ! |
encoding = tags$div( |
250 |
### Reporter |
|
251 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
252 |
### |
|
253 | ! |
tags$label("Encodings", class = "text-primary"), |
254 | ! |
teal.transform::datanames_input(args[c("response", "x", "row_facet", "col_facet")]), |
255 | ! |
teal.transform::data_extract_ui( |
256 | ! |
id = ns("response"), |
257 | ! |
label = "Response variable", |
258 | ! |
data_extract_spec = args$response, |
259 | ! |
is_single_dataset = is_single_dataset_value |
260 |
), |
|
261 | ! |
teal.transform::data_extract_ui( |
262 | ! |
id = ns("x"), |
263 | ! |
label = "X variable", |
264 | ! |
data_extract_spec = args$x, |
265 | ! |
is_single_dataset = is_single_dataset_value |
266 |
), |
|
267 | ! |
if (!is.null(args$row_facet)) { |
268 | ! |
teal.transform::data_extract_ui( |
269 | ! |
id = ns("row_facet"), |
270 | ! |
label = "Row facetting", |
271 | ! |
data_extract_spec = args$row_facet, |
272 | ! |
is_single_dataset = is_single_dataset_value |
273 |
) |
|
274 |
}, |
|
275 | ! |
if (!is.null(args$col_facet)) { |
276 | ! |
teal.transform::data_extract_ui( |
277 | ! |
id = ns("col_facet"), |
278 | ! |
label = "Column facetting", |
279 | ! |
data_extract_spec = args$col_facet, |
280 | ! |
is_single_dataset = is_single_dataset_value |
281 |
) |
|
282 |
}, |
|
283 | ! |
shinyWidgets::radioGroupButtons( |
284 | ! |
inputId = ns("freq"), |
285 | ! |
label = NULL, |
286 | ! |
choices = c("frequency", "density"), |
287 | ! |
selected = ifelse(args$freq, "frequency", "density"), |
288 | ! |
justified = TRUE |
289 |
), |
|
290 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")), |
291 | ! |
teal.widgets::panel_group( |
292 | ! |
teal.widgets::panel_item( |
293 | ! |
title = "Plot settings", |
294 | ! |
checkboxInput(ns("count_labels"), "Add count labels", value = args$count_labels), |
295 | ! |
checkboxInput(ns("coord_flip"), "Swap axes", value = args$coord_flip), |
296 | ! |
checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = args$rotate_xaxis_labels), |
297 | ! |
selectInput( |
298 | ! |
inputId = ns("ggtheme"), |
299 | ! |
label = "Theme (by ggplot):", |
300 | ! |
choices = ggplot_themes, |
301 | ! |
selected = args$ggtheme, |
302 | ! |
multiple = FALSE |
303 |
) |
|
304 |
) |
|
305 |
) |
|
306 |
), |
|
307 | ! |
forms = tagList( |
308 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
309 |
), |
|
310 | ! |
pre_output = args$pre_output, |
311 | ! |
post_output = args$post_output |
312 |
) |
|
313 |
} |
|
314 | ||
315 |
# Server function for the response module |
|
316 |
srv_g_response <- function(id, |
|
317 |
data, |
|
318 |
reporter, |
|
319 |
filter_panel_api, |
|
320 |
response, |
|
321 |
x, |
|
322 |
row_facet, |
|
323 |
col_facet, |
|
324 |
plot_height, |
|
325 |
plot_width, |
|
326 |
ggplot2_args, |
|
327 |
decorators) { |
|
328 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
329 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
330 | ! |
checkmate::assert_class(data, "reactive") |
331 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
332 | ! |
moduleServer(id, function(input, output, session) { |
333 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
334 | ||
335 | ! |
data_extract <- list(response = response, x = x, row_facet = row_facet, col_facet = col_facet) |
336 | ||
337 | ! |
rule_diff <- function(other) { |
338 | ! |
function(value) { |
339 | ! |
if (other %in% names(selector_list())) { |
340 | ! |
othervalue <- selector_list()[[other]]()[["select"]] |
341 | ! |
if (!is.null(othervalue)) { |
342 | ! |
if (identical(value, othervalue)) { |
343 | ! |
"Row and column facetting variables must be different." |
344 |
} |
|
345 |
} |
|
346 |
} |
|
347 |
} |
|
348 |
} |
|
349 | ||
350 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
351 | ! |
data_extract = data_extract, |
352 | ! |
datasets = data, |
353 | ! |
select_validation_rule = list( |
354 | ! |
response = shinyvalidate::sv_required("Please define a column for the response variable"), |
355 | ! |
x = shinyvalidate::sv_required("Please define a column for X variable"), |
356 | ! |
row_facet = shinyvalidate::compose_rules( |
357 | ! |
shinyvalidate::sv_optional(), |
358 | ! |
~ if (length(.) > 1) "There must be 1 or no row facetting variable.", |
359 | ! |
rule_diff("col_facet") |
360 |
), |
|
361 | ! |
col_facet = shinyvalidate::compose_rules( |
362 | ! |
shinyvalidate::sv_optional(), |
363 | ! |
~ if (length(.) > 1) "There must be 1 or no column facetting variable.", |
364 | ! |
rule_diff("row_facet") |
365 |
) |
|
366 |
) |
|
367 |
) |
|
368 | ||
369 | ! |
iv_r <- reactive({ |
370 | ! |
iv <- shinyvalidate::InputValidator$new() |
371 | ! |
iv$add_rule("ggtheme", shinyvalidate::sv_required("Please select a theme")) |
372 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
373 |
}) |
|
374 | ||
375 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
376 | ! |
selector_list = selector_list, |
377 | ! |
datasets = data |
378 |
) |
|
379 | ||
380 | ! |
anl_merged_q <- reactive({ |
381 | ! |
req(anl_merged_input()) |
382 | ! |
data() %>% |
383 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
384 |
}) |
|
385 | ||
386 | ! |
merged <- list( |
387 | ! |
anl_input_r = anl_merged_input, |
388 | ! |
anl_q_r = anl_merged_q |
389 |
) |
|
390 | ||
391 | ! |
output_q <- reactive({ |
392 | ! |
teal::validate_inputs(iv_r()) |
393 | ||
394 | ! |
qenv <- merged$anl_q_r() |
395 | ! |
ANL <- qenv[["ANL"]] |
396 | ! |
resp_var <- as.vector(merged$anl_input_r()$columns_source$response) |
397 | ! |
x <- as.vector(merged$anl_input_r()$columns_source$x) |
398 | ||
399 | ! |
validate(need(is.factor(ANL[[resp_var]]), "Please select a factor variable as the response.")) |
400 | ! |
validate(need(is.factor(ANL[[x]]), "Please select a factor variable as the X-Variable.")) |
401 | ! |
teal::validate_has_data(ANL, 10) |
402 | ! |
teal::validate_has_data(ANL[, c(resp_var, x)], 10, complete = TRUE, allow_inf = FALSE) |
403 | ||
404 | ! |
row_facet_name <- if (length(merged$anl_input_r()$columns_source$row_facet) == 0) { |
405 | ! |
character(0) |
406 |
} else { |
|
407 | ! |
as.vector(merged$anl_input_r()$columns_source$row_facet) |
408 |
} |
|
409 | ! |
col_facet_name <- if (length(merged$anl_input_r()$columns_source$col_facet) == 0) { |
410 | ! |
character(0) |
411 |
} else { |
|
412 | ! |
as.vector(merged$anl_input_r()$columns_source$col_facet) |
413 |
} |
|
414 | ||
415 | ! |
freq <- input$freq == "frequency" |
416 | ! |
swap_axes <- input$coord_flip |
417 | ! |
counts <- input$count_labels |
418 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
419 | ! |
ggtheme <- input$ggtheme |
420 | ||
421 | ! |
arg_position <- if (freq) "stack" else "fill" |
422 | ||
423 | ! |
rowf <- if (length(row_facet_name) != 0) as.name(row_facet_name) |
424 | ! |
colf <- if (length(col_facet_name) != 0) as.name(col_facet_name) |
425 | ! |
resp_cl <- as.name(resp_var) |
426 | ! |
x_cl <- as.name(x) |
427 | ||
428 | ! |
if (swap_axes) { |
429 | ! |
qenv <- teal.code::eval_code( |
430 | ! |
qenv, |
431 | ! |
substitute( |
432 | ! |
expr = ANL[[x]] <- with(ANL, forcats::fct_rev(x_cl)), |
433 | ! |
env = list(x = x, x_cl = x_cl) |
434 |
) |
|
435 |
) |
|
436 |
} |
|
437 | ||
438 | ! |
qenv <- teal.code::eval_code( |
439 | ! |
qenv, |
440 | ! |
substitute( |
441 | ! |
expr = ANL[[resp_var]] <- factor(ANL[[resp_var]]), |
442 | ! |
env = list(resp_var = resp_var) |
443 |
) |
|
444 |
) %>% |
|
445 |
# rowf and colf will be a NULL if not set by a user |
|
446 | ! |
teal.code::eval_code( |
447 | ! |
substitute( |
448 | ! |
expr = ANL2 <- ANL %>% |
449 | ! |
dplyr::group_by_at(dplyr::vars(x_cl, resp_cl, rowf, colf)) %>% |
450 | ! |
dplyr::summarise(ns = dplyr::n()) %>% |
451 | ! |
dplyr::group_by_at(dplyr::vars(x_cl, rowf, colf)) %>% |
452 | ! |
dplyr::mutate(sums = sum(ns), percent = round(ns / sums * 100, 1)), |
453 | ! |
env = list(x_cl = x_cl, resp_cl = resp_cl, rowf = rowf, colf = colf) |
454 |
) |
|
455 |
) %>% |
|
456 | ! |
teal.code::eval_code( |
457 | ! |
substitute( |
458 | ! |
expr = ANL3 <- ANL %>% |
459 | ! |
dplyr::group_by_at(dplyr::vars(x_cl, rowf, colf)) %>% |
460 | ! |
dplyr::summarise(ns = dplyr::n()), |
461 | ! |
env = list(x_cl = x_cl, rowf = rowf, colf = colf) |
462 |
) |
|
463 |
) |
|
464 | ||
465 | ! |
plot_call <- substitute( |
466 | ! |
expr = ggplot(ANL2, aes(x = x_cl, y = ns)) + |
467 | ! |
geom_bar(aes(fill = resp_cl), stat = "identity", position = arg_position), |
468 | ! |
env = list( |
469 | ! |
x_cl = x_cl, |
470 | ! |
resp_cl = resp_cl, |
471 | ! |
arg_position = arg_position |
472 |
) |
|
473 |
) |
|
474 | ||
475 | ! |
if (!freq) { |
476 | ! |
plot_call <- substitute( |
477 | ! |
plot_call + expand_limits(y = c(0, 1.1)), |
478 | ! |
env = list(plot_call = plot_call) |
479 |
) |
|
480 |
} |
|
481 | ||
482 | ! |
if (counts) { |
483 | ! |
plot_call <- substitute( |
484 | ! |
expr = plot_call + |
485 | ! |
geom_text( |
486 | ! |
data = ANL2, |
487 | ! |
aes(label = ns, x = x_cl, y = ns, group = resp_cl), |
488 | ! |
col = "white", |
489 | ! |
vjust = "middle", |
490 | ! |
hjust = "middle", |
491 | ! |
position = position_anl2_value |
492 |
) + |
|
493 | ! |
geom_text( |
494 | ! |
data = ANL3, aes(label = ns, x = x_cl, y = anl3_y), |
495 | ! |
hjust = hjust_value, |
496 | ! |
vjust = vjust_value, |
497 | ! |
position = position_anl3_value |
498 |
), |
|
499 | ! |
env = list( |
500 | ! |
plot_call = plot_call, |
501 | ! |
x_cl = x_cl, |
502 | ! |
resp_cl = resp_cl, |
503 | ! |
hjust_value = if (swap_axes) "left" else "middle", |
504 | ! |
vjust_value = if (swap_axes) "middle" else -1, |
505 | ! |
position_anl2_value = if (!freq) quote(position_fill(0.5)) else quote(position_stack(0.5)), # nolint: line_length. |
506 | ! |
anl3_y = if (!freq) 1.1 else as.name("ns"), |
507 | ! |
position_anl3_value = if (!freq) "fill" else "stack" |
508 |
) |
|
509 |
) |
|
510 |
} |
|
511 | ||
512 | ! |
if (swap_axes) { |
513 | ! |
plot_call <- substitute(plot_call + coord_flip(), env = list(plot_call = plot_call)) |
514 |
} |
|
515 | ||
516 | ! |
facet_cl <- facet_ggplot_call(row_facet_name, col_facet_name) |
517 | ||
518 | ! |
if (!is.null(facet_cl)) { |
519 | ! |
plot_call <- substitute(expr = plot_call + facet_cl, env = list(plot_call = plot_call, facet_cl = facet_cl)) |
520 |
} |
|
521 | ||
522 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
523 | ! |
labs = list( |
524 | ! |
x = varname_w_label(x, ANL), |
525 | ! |
y = varname_w_label(resp_var, ANL, prefix = "Proportion of "), |
526 | ! |
fill = varname_w_label(resp_var, ANL) |
527 |
), |
|
528 | ! |
theme = list(legend.position = "bottom") |
529 |
) |
|
530 | ||
531 | ! |
if (rotate_xaxis_labels) { |
532 | ! |
dev_ggplot2_args$theme[["axis.text.x"]] <- quote(element_text(angle = 45, hjust = 1)) |
533 |
} |
|
534 | ||
535 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
536 | ! |
user_plot = ggplot2_args, |
537 | ! |
module_plot = dev_ggplot2_args |
538 |
) |
|
539 | ||
540 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
541 | ! |
all_ggplot2_args, |
542 | ! |
ggtheme = ggtheme |
543 |
) |
|
544 | ||
545 | ! |
plot_call <- substitute(expr = { |
546 | ! |
plot <- plot_call + labs + ggthemes + themes |
547 | ! |
}, env = list( |
548 | ! |
plot_call = plot_call, |
549 | ! |
labs = parsed_ggplot2_args$labs, |
550 | ! |
themes = parsed_ggplot2_args$theme, |
551 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
552 |
)) |
|
553 | ||
554 | ! |
teal.code::eval_code(qenv, plot_call) |
555 |
}) |
|
556 | ||
557 | ! |
decorated_output_plot_q <- srv_decorate_teal_data( |
558 | ! |
id = "decorator", |
559 | ! |
data = output_q, |
560 | ! |
decorators = select_decorators(decorators, "plot"), |
561 | ! |
expr = print(plot) |
562 |
) |
|
563 | ||
564 | ! |
plot_r <- reactive(req(decorated_output_plot_q())[["plot"]]) |
565 | ||
566 |
# Insert the plot into a plot_with_settings module from teal.widgets |
|
567 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
568 | ! |
id = "myplot", |
569 | ! |
plot_r = plot_r, |
570 | ! |
height = plot_height, |
571 | ! |
width = plot_width |
572 |
) |
|
573 | ||
574 | ! |
teal.widgets::verbatim_popup_srv( |
575 | ! |
id = "rcode", |
576 | ! |
verbatim_content = reactive(teal.code::get_code(req(decorated_output_plot_q()))), |
577 | ! |
title = "Show R Code for Response" |
578 |
) |
|
579 | ||
580 |
### REPORTER |
|
581 | ! |
if (with_reporter) { |
582 | ! |
card_fun <- function(comment, label) { |
583 | ! |
card <- teal::report_card_template( |
584 | ! |
title = "Response Plot", |
585 | ! |
label = label, |
586 | ! |
with_filter = with_filter, |
587 | ! |
filter_panel_api = filter_panel_api |
588 |
) |
|
589 | ! |
card$append_text("Plot", "header3") |
590 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
591 | ! |
if (!comment == "") { |
592 | ! |
card$append_text("Comment", "header3") |
593 | ! |
card$append_text(comment) |
594 |
} |
|
595 | ! |
card$append_src(teal.code::get_code(req(decorated_output_plot_q()))) |
596 | ! |
card |
597 |
} |
|
598 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
599 |
} |
|
600 |
### |
|
601 |
}) |
|
602 |
} |
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 |
#' |
|
37 |
#' @return Object of class `teal_module` to be used in `teal` applications. |
|
38 |
#' |
|
39 |
#' @name shared_params |
|
40 |
#' @keywords internal |
|
41 |
NULL |
|
42 | ||
43 |
#' Add labels for facets to a `ggplot2` object |
|
44 |
#' |
|
45 |
#' Enhances a `ggplot2` plot by adding labels that describe |
|
46 |
#' the faceting variables along the x and y axes. |
|
47 |
#' |
|
48 |
#' @param p (`ggplot2`) object to which facet labels will be added. |
|
49 |
#' @param xfacet_label (`character`) Label for the facet along the x-axis. |
|
50 |
#' If `NULL`, no label is added. If a vector, labels are joined with " & ". |
|
51 |
#' @param yfacet_label (`character`) Label for the facet along the y-axis. |
|
52 |
#' Similar behavior to `xfacet_label`. |
|
53 |
#' |
|
54 |
#' @return Returns `grid` or `grob` object (to be drawn with `grid.draw`) |
|
55 |
#' |
|
56 |
#' @examples |
|
57 |
#' library(ggplot2) |
|
58 |
#' library(grid) |
|
59 |
#' |
|
60 |
#' p <- ggplot(mtcars) + |
|
61 |
#' aes(x = mpg, y = disp) + |
|
62 |
#' geom_point() + |
|
63 |
#' facet_grid(gear ~ cyl) |
|
64 |
#' |
|
65 |
#' xfacet_label <- "cylinders" |
|
66 |
#' yfacet_label <- "gear" |
|
67 |
#' res <- add_facet_labels(p, xfacet_label, yfacet_label) |
|
68 |
#' grid.newpage() |
|
69 |
#' grid.draw(res) |
|
70 |
#' |
|
71 |
#' grid.newpage() |
|
72 |
#' grid.draw(add_facet_labels(p, xfacet_label = NULL, yfacet_label)) |
|
73 |
#' grid.newpage() |
|
74 |
#' grid.draw(add_facet_labels(p, xfacet_label, yfacet_label = NULL)) |
|
75 |
#' grid.newpage() |
|
76 |
#' grid.draw(add_facet_labels(p, xfacet_label = NULL, yfacet_label = NULL)) |
|
77 |
#' |
|
78 |
#' @export |
|
79 |
#' |
|
80 |
add_facet_labels <- function(p, xfacet_label = NULL, yfacet_label = NULL) { |
|
81 | ! |
checkmate::assert_class(p, classes = "ggplot") |
82 | ! |
checkmate::assert_character(xfacet_label, null.ok = TRUE, min.len = 1) |
83 | ! |
checkmate::assert_character(yfacet_label, null.ok = TRUE, min.len = 1) |
84 | ! |
if (is.null(xfacet_label) && is.null(yfacet_label)) { |
85 | ! |
return(ggplotGrob(p)) |
86 |
} |
|
87 | ! |
grid::grid.grabExpr({ |
88 | ! |
g <- ggplotGrob(p) |
89 | ||
90 |
# we are going to replace these, so we make sure they have nothing in them |
|
91 | ! |
checkmate::assert_class(g$grobs[[grep("xlab-t", g$layout$name, fixed = TRUE)]], "zeroGrob") |
92 | ! |
checkmate::assert_class(g$grobs[[grep("ylab-r", g$layout$name, fixed = TRUE)]], "zeroGrob") |
93 | ||
94 | ! |
xaxis_label_grob <- g$grobs[[grep("xlab-b", g$layout$name, fixed = TRUE)]] |
95 | ! |
xaxis_label_grob$children[[1]]$label <- paste(xfacet_label, collapse = " & ") |
96 | ! |
yaxis_label_grob <- g$grobs[[grep("ylab-l", g$layout$name, fixed = TRUE)]] |
97 | ! |
yaxis_label_grob$children[[1]]$label <- paste(yfacet_label, collapse = " & ") |
98 | ! |
yaxis_label_grob$children[[1]]$rot <- 270 |
99 | ||
100 | ! |
top_height <- if (is.null(xfacet_label)) 0 else grid::unit(2, "line") |
101 | ! |
right_width <- if (is.null(yfacet_label)) 0 else grid::unit(2, "line") |
102 | ||
103 | ! |
grid::grid.newpage() |
104 | ! |
grid::pushViewport(grid::plotViewport(margins = c(0, 0, top_height, right_width), name = "ggplot")) |
105 | ! |
grid::grid.draw(g) |
106 | ! |
grid::upViewport(1) |
107 | ||
108 |
# draw x facet |
|
109 | ! |
if (!is.null(xfacet_label)) { |
110 | ! |
grid::pushViewport(grid::viewport( |
111 | ! |
x = 0, y = grid::unit(1, "npc") - top_height, width = grid::unit(1, "npc"), |
112 | ! |
height = top_height, just = c("left", "bottom"), name = "topxaxis" |
113 |
)) |
|
114 | ! |
grid::grid.draw(xaxis_label_grob) |
115 | ! |
grid::upViewport(1) |
116 |
} |
|
117 | ||
118 |
# draw y facet |
|
119 | ! |
if (!is.null(yfacet_label)) { |
120 | ! |
grid::pushViewport(grid::viewport( |
121 | ! |
x = grid::unit(1, "npc") - grid::unit(as.numeric(right_width) / 2, "line"), y = 0, width = right_width, |
122 | ! |
height = grid::unit(1, "npc"), just = c("left", "bottom"), name = "rightyaxis" |
123 |
)) |
|
124 | ! |
grid::grid.draw(yaxis_label_grob) |
125 | ! |
grid::upViewport(1) |
126 |
} |
|
127 |
}) |
|
128 |
} |
|
129 | ||
130 |
#' Call a function with a character vector for the `...` argument |
|
131 |
#' |
|
132 |
#' @param fun (`character`) Name of a function where the `...` argument shall be replaced by values from `str_args`. |
|
133 |
#' @param str_args (`character`) A character vector that the function shall be executed with |
|
134 |
#' |
|
135 |
#' @return |
|
136 |
#' Value of call to `fun` with arguments specified in `str_args`. |
|
137 |
#' |
|
138 |
#' @keywords internal |
|
139 |
call_fun_dots <- function(fun, str_args) { |
|
140 | ! |
do.call("call", c(list(fun), lapply(str_args, as.name)), quote = TRUE) |
141 |
} |
|
142 | ||
143 |
#' Generate a string for a variable including its label |
|
144 |
#' |
|
145 |
#' @param var_names (`character`) Name of variable to extract labels from. |
|
146 |
#' @param dataset (`dataset`) Name of analysis dataset. |
|
147 |
#' @param prefix,suffix (`character`) String to paste to the beginning/end of the variable name with label. |
|
148 |
#' @param wrap_width (`numeric`) Number of characters to wrap original label to. Defaults to 80. |
|
149 |
#' |
|
150 |
#' @return (`character`) String with variable name and label. |
|
151 |
#' |
|
152 |
#' @keywords internal |
|
153 |
#' |
|
154 |
varname_w_label <- function(var_names, |
|
155 |
dataset, |
|
156 |
wrap_width = 80, |
|
157 |
prefix = NULL, |
|
158 |
suffix = NULL) { |
|
159 | ! |
add_label <- function(var_names) { |
160 | ! |
label <- vapply( |
161 | ! |
dataset[var_names], function(x) { |
162 | ! |
attr_label <- attr(x, "label") |
163 | ! |
`if`(is.null(attr_label), "", attr_label) |
164 |
}, |
|
165 | ! |
character(1) |
166 |
) |
|
167 | ||
168 | ! |
if (length(label) == 1 && !is.na(label) && !identical(label, "")) { |
169 | ! |
paste0(prefix, label, " [", var_names, "]", suffix) |
170 |
} else { |
|
171 | ! |
var_names |
172 |
} |
|
173 |
} |
|
174 | ||
175 | ! |
if (length(var_names) < 1) { |
176 | ! |
NULL |
177 | ! |
} else if (length(var_names) == 1) { |
178 | ! |
stringr::str_wrap(add_label(var_names), width = wrap_width) |
179 | ! |
} else if (length(var_names) > 1) { |
180 | ! |
stringr::str_wrap(vapply(var_names, add_label, character(1)), width = wrap_width) |
181 |
} |
|
182 |
} |
|
183 | ||
184 |
# see vignette("ggplot2-specs", package="ggplot2") |
|
185 |
shape_names <- c( |
|
186 |
"circle", paste("circle", c("open", "filled", "cross", "plus", "small")), "bullet", |
|
187 |
"square", paste("square", c("open", "filled", "cross", "plus", "triangle")), |
|
188 |
"diamond", paste("diamond", c("open", "filled", "plus")), |
|
189 |
"triangle", paste("triangle", c("open", "filled", "square")), |
|
190 |
paste("triangle down", c("open", "filled")), |
|
191 |
"plus", "cross", "asterisk" |
|
192 |
) |
|
193 | ||
194 |
#' Get icons to represent variable types in dataset |
|
195 |
#' |
|
196 |
#' @param var_type (`character`) of R internal types (classes). |
|
197 |
#' @return (`character`) vector of HTML icons corresponding to data type in each column. |
|
198 |
#' @keywords internal |
|
199 |
variable_type_icons <- function(var_type) { |
|
200 | ! |
checkmate::assert_character(var_type, any.missing = FALSE) |
201 | ||
202 | ! |
class_to_icon <- list( |
203 | ! |
numeric = "arrow-up-1-9", |
204 | ! |
integer = "arrow-up-1-9", |
205 | ! |
logical = "pause", |
206 | ! |
Date = "calendar", |
207 | ! |
POSIXct = "calendar", |
208 | ! |
POSIXlt = "calendar", |
209 | ! |
factor = "chart-bar", |
210 | ! |
character = "keyboard", |
211 | ! |
primary_key = "key", |
212 | ! |
unknown = "circle-question" |
213 |
) |
|
214 | ! |
class_to_icon <- lapply(class_to_icon, function(icon_name) toString(icon(icon_name, lib = "font-awesome"))) |
215 | ||
216 | ! |
unname(vapply( |
217 | ! |
var_type, |
218 | ! |
FUN.VALUE = character(1), |
219 | ! |
FUN = function(class) { |
220 | ! |
if (class == "") { |
221 | ! |
class |
222 | ! |
} else if (is.null(class_to_icon[[class]])) { |
223 | ! |
class_to_icon[["unknown"]] |
224 |
} else { |
|
225 | ! |
class_to_icon[[class]] |
226 |
} |
|
227 |
} |
|
228 |
)) |
|
229 |
} |
|
230 | ||
231 |
#' Include `CSS` files from `/inst/css/` package directory to application header |
|
232 |
#' |
|
233 |
#' `system.file` should not be used to access files in other packages, it does |
|
234 |
#' not work with `devtools`. Therefore, we redefine this method in each package |
|
235 |
#' as needed. Thus, we do not export this method |
|
236 |
#' |
|
237 |
#' @param pattern (`character`) optional, regular expression to match the file names to be included. |
|
238 |
#' |
|
239 |
#' @return HTML code that includes `CSS` files. |
|
240 |
#' @keywords internal |
|
241 |
#' |
|
242 |
include_css_files <- function(pattern = "*") { |
|
243 | ! |
css_files <- list.files( |
244 | ! |
system.file("css", package = "teal.modules.general", mustWork = TRUE), |
245 | ! |
pattern = pattern, full.names = TRUE |
246 |
) |
|
247 | ! |
if (length(css_files) == 0) { |
248 | ! |
return(NULL) |
249 |
} |
|
250 | ! |
singleton(tags$head(lapply(css_files, includeCSS))) |
251 |
} |
|
252 | ||
253 |
#' JavaScript condition to check if a specific tab is active |
|
254 |
#' |
|
255 |
#' @param id (`character(1)`) the id of the tab panel with tabs. |
|
256 |
#' @param name (`character(1)`) the name of the tab. |
|
257 |
#' @return JavaScript expression to be used in `shiny::conditionalPanel()` to determine |
|
258 |
#' if the specified tab is active. |
|
259 |
#' @keywords internal |
|
260 |
#' |
|
261 |
is_tab_active_js <- function(id, name) { |
|
262 |
# supporting the bs3 and higher version at the same time |
|
263 | ! |
sprintf( |
264 | ! |
"$(\"#%1$s > li.active\").text().trim() == '%2$s' || $(\"#%1$s > li a.active\").text().trim() == '%2$s'", |
265 | ! |
id, name |
266 |
) |
|
267 |
} |
|
268 | ||
269 |
#' Assert single selection on `data_extract_spec` object |
|
270 |
#' Helper to reduce code in assertions |
|
271 |
#' @noRd |
|
272 |
#' |
|
273 |
assert_single_selection <- function(x, |
|
274 |
.var.name = checkmate::vname(x)) { # nolint: object_name. |
|
275 | 104x |
if (any(vapply(x, function(.x) .x$select$multiple, logical(1)))) { |
276 | 4x |
stop("'", .var.name, "' should not allow multiple selection") |
277 |
} |
|
278 | 100x |
invisible(TRUE) |
279 |
} |
|
280 | ||
281 |
#' Wrappers around `srv_transform_teal_data` that allows to decorate the data |
|
282 |
#' @inheritParams teal::srv_transform_teal_data |
|
283 |
#' @param expr (`expression` or `reactive`) to evaluate on the output of the decoration. |
|
284 |
#' When an expression it must be inline code. See [within()] |
|
285 |
#' Default is `NULL` which won't evaluate any appending code. |
|
286 |
#' @param expr_is_reactive (`logical(1)`) whether `expr` is a reactive expression |
|
287 |
#' that skips defusing the argument. |
|
288 |
#' @details |
|
289 |
#' `srv_decorate_teal_data` is a wrapper around `srv_transform_teal_data` that |
|
290 |
#' allows to decorate the data with additional expressions. |
|
291 |
#' When original `teal_data` object is in error state, it will show that error |
|
292 |
#' first. |
|
293 |
#' |
|
294 |
#' @keywords internal |
|
295 |
srv_decorate_teal_data <- function(id, data, decorators, expr, expr_is_reactive = FALSE) { |
|
296 | ! |
checkmate::assert_class(data, classes = "reactive") |
297 | ! |
checkmate::assert_list(decorators, "teal_transform_module") |
298 | ! |
checkmate::assert_flag(expr_is_reactive) |
299 | ||
300 | ! |
missing_expr <- missing(expr) |
301 | ! |
if (!missing_expr && !expr_is_reactive) { |
302 | ! |
expr <- rlang::enexpr(expr) |
303 |
} |
|
304 | ||
305 | ! |
moduleServer(id, function(input, output, session) { |
306 | ! |
decorated_output <- srv_transform_teal_data("inner", data = data, transformators = decorators) |
307 | ||
308 | ! |
reactive({ |
309 |
# ensure original errors are displayed and `eval_code` is never executed with NULL |
|
310 | ! |
req(data(), decorated_output()) |
311 | ! |
if (missing_expr) { |
312 | ! |
decorated_output() |
313 | ! |
} else if (expr_is_reactive) { |
314 | ! |
teal.code::eval_code(decorated_output(), expr()) |
315 |
} else { |
|
316 | ! |
teal.code::eval_code(decorated_output(), expr) |
317 |
} |
|
318 |
}) |
|
319 |
}) |
|
320 |
} |
|
321 | ||
322 |
#' @rdname srv_decorate_teal_data |
|
323 |
#' @details |
|
324 |
#' `ui_decorate_teal_data` is a wrapper around `ui_transform_teal_data`. |
|
325 |
#' @keywords internal |
|
326 |
ui_decorate_teal_data <- function(id, decorators, ...) { |
|
327 | ! |
teal::ui_transform_teal_data(NS(id, "inner"), transformators = decorators, ...) |
328 |
} |
|
329 | ||
330 |
#' Internal function to check if decorators is a valid object |
|
331 |
#' @noRd |
|
332 |
check_decorators <- function(x, names = NULL, null.ok = FALSE) { # nolint: object_name. |
|
333 | 5x |
checkmate::qassert(null.ok, "B1") |
334 | ||
335 | 5x |
check_message <- checkmate::check_list( |
336 | 5x |
x, |
337 | 5x |
null.ok = null.ok, |
338 | 5x |
names = "named" |
339 |
) |
|
340 | ||
341 | 5x |
if (!is.null(names)) { |
342 | 5x |
check_message <- if (isTRUE(check_message)) { |
343 | 5x |
out_message <- checkmate::check_names(names(x), subset.of = c("default", names)) |
344 |
# see https://github.com/insightsengineering/teal.logger/issues/101 |
|
345 | 5x |
if (isTRUE(out_message)) { |
346 | 5x |
out_message |
347 |
} else { |
|
348 | ! |
gsub("\\{", "(", gsub("\\}", ")", out_message)) |
349 |
} |
|
350 |
} else { |
|
351 | ! |
check_message |
352 |
} |
|
353 |
} |
|
354 | ||
355 | 5x |
if (!isTRUE(check_message)) { |
356 | ! |
return(check_message) |
357 |
} |
|
358 | ||
359 | 5x |
valid_elements <- vapply( |
360 | 5x |
x, |
361 | 5x |
checkmate::test_list, |
362 | 5x |
types = "teal_transform_module", |
363 | 5x |
null.ok = TRUE, |
364 | 5x |
FUN.VALUE = logical(1L) |
365 |
) |
|
366 | ||
367 | 5x |
if (all(valid_elements)) { |
368 | 5x |
return(TRUE) |
369 |
} |
|
370 | ||
371 | ! |
"May only contain the type 'teal_transform_module' or a named list of 'teal_transform_module'." |
372 |
} |
|
373 | ||
374 |
#' Internal assertion on decorators |
|
375 |
#' @noRd |
|
376 |
assert_decorators <- checkmate::makeAssertionFunction(check_decorators) |
|
377 | ||
378 |
#' Subset decorators based on the scope |
|
379 |
#' |
|
380 |
#' `default` is a protected decorator name that is always included in the output, |
|
381 |
#' if it exists |
|
382 |
#' |
|
383 |
#' @param scope (`character`) a character vector of decorator names to include. |
|
384 |
#' @param decorators (named `list`) of list decorators to subset. |
|
385 |
#' |
|
386 |
#' @return A flat list with all decorators to include. |
|
387 |
#' It can be an empty list if none of the scope exists in `decorators` argument. |
|
388 |
#' @keywords internal |
|
389 |
select_decorators <- function(decorators, scope) { |
|
390 | ! |
checkmate::assert_character(scope, null.ok = TRUE) |
391 | ! |
scope <- intersect(union("default", scope), names(decorators)) |
392 | ! |
c(list(), unlist(decorators[scope], recursive = FALSE)) |
393 |
} |
|
394 | ||
395 |
#' Convert flat list of `teal_transform_module` to named lists |
|
396 |
#' |
|
397 |
#' @param decorators (list of `teal_transform_module`) to normalize. |
|
398 |
#' @return A named list of lists with `teal_transform_module` objects. |
|
399 |
#' @keywords internal |
|
400 |
normalize_decorators <- function(decorators) { |
|
401 | 5x |
if (checkmate::test_list(decorators, "teal_transform_module", null.ok = TRUE)) { |
402 | 5x |
if (checkmate::test_names(names(decorators))) { |
403 | ! |
lapply(decorators, list) |
404 |
} else { |
|
405 | 5x |
list(default = decorators) |
406 |
} |
|
407 |
} else { |
|
408 | ! |
decorators |
409 |
} |
|
410 |
} |
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 |
#' @param decorators `r roxygen_decorators_param("tm_g_scatterplotmatrix")` |
|
19 |
#' |
|
20 |
#' @inherit shared_params return |
|
21 |
#' |
|
22 |
#' @section Decorating `tm_g_scatterplotmatrix`: |
|
23 |
#' |
|
24 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
25 |
#' - `plot` (`trellis` - output of `lattice::splom`) |
|
26 |
#' |
|
27 |
#' For additional details and examples of decorators, refer to the vignette |
|
28 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
29 |
#' |
|
30 |
#' @examplesShinylive |
|
31 |
#' library(teal.modules.general) |
|
32 |
#' interactive <- function() TRUE |
|
33 |
#' {{ next_example }} |
|
34 |
#' @examplesIf require("lattice", quietly = TRUE) |
|
35 |
#' # general data example |
|
36 |
#' data <- teal_data() |
|
37 |
#' data <- within(data, { |
|
38 |
#' countries <- data.frame( |
|
39 |
#' id = c("DE", "FR", "IT", "ES", "PT", "GR", "NL", "BE", "LU", "AT"), |
|
40 |
#' government = factor( |
|
41 |
#' c(2, 2, 2, 1, 2, 2, 1, 1, 1, 2), |
|
42 |
#' labels = c("Monarchy", "Republic") |
|
43 |
#' ), |
|
44 |
#' language_family = factor( |
|
45 |
#' c(1, 3, 3, 3, 3, 2, 1, 1, 3, 1), |
|
46 |
#' labels = c("Germanic", "Hellenic", "Romance") |
|
47 |
#' ), |
|
48 |
#' population = c(83, 67, 60, 47, 10, 11, 17, 11, 0.6, 9), |
|
49 |
#' area = c(357, 551, 301, 505, 92, 132, 41, 30, 2.6, 83), |
|
50 |
#' gdp = c(3.4, 2.7, 2.1, 1.4, 0.3, 0.2, 0.7, 0.5, 0.1, 0.4), |
|
51 |
#' debt = c(2.1, 2.3, 2.4, 2.6, 2.3, 2.4, 2.3, 2.4, 2.3, 2.4) |
|
52 |
#' ) |
|
53 |
#' sales <- data.frame( |
|
54 |
#' id = 1:50, |
|
55 |
#' country_id = sample( |
|
56 |
#' c("DE", "FR", "IT", "ES", "PT", "GR", "NL", "BE", "LU", "AT"), |
|
57 |
#' size = 50, |
|
58 |
#' replace = TRUE |
|
59 |
#' ), |
|
60 |
#' year = sort(sample(2010:2020, 50, replace = TRUE)), |
|
61 |
#' venue = sample(c("small", "medium", "large", "online"), 50, replace = TRUE), |
|
62 |
#' cancelled = sample(c(TRUE, FALSE), 50, replace = TRUE), |
|
63 |
#' quantity = rnorm(50, 100, 20), |
|
64 |
#' costs = rnorm(50, 80, 20), |
|
65 |
#' profit = rnorm(50, 20, 10) |
|
66 |
#' ) |
|
67 |
#' }) |
|
68 |
#' join_keys(data) <- join_keys( |
|
69 |
#' join_key("countries", "countries", "id"), |
|
70 |
#' join_key("sales", "sales", "id"), |
|
71 |
#' join_key("countries", "sales", c("id" = "country_id")) |
|
72 |
#' ) |
|
73 |
#' |
|
74 |
#' app <- init( |
|
75 |
#' data = data, |
|
76 |
#' modules = modules( |
|
77 |
#' tm_g_scatterplotmatrix( |
|
78 |
#' label = "Scatterplot matrix", |
|
79 |
#' variables = list( |
|
80 |
#' data_extract_spec( |
|
81 |
#' dataname = "countries", |
|
82 |
#' select = select_spec( |
|
83 |
#' label = "Select variables:", |
|
84 |
#' choices = variable_choices(data[["countries"]]), |
|
85 |
#' selected = c("area", "gdp", "debt"), |
|
86 |
#' multiple = TRUE, |
|
87 |
#' ordered = TRUE, |
|
88 |
#' fixed = FALSE |
|
89 |
#' ) |
|
90 |
#' ), |
|
91 |
#' data_extract_spec( |
|
92 |
#' dataname = "sales", |
|
93 |
#' filter = filter_spec( |
|
94 |
#' label = "Select variable:", |
|
95 |
#' vars = "country_id", |
|
96 |
#' choices = value_choices(data[["sales"]], "country_id"), |
|
97 |
#' selected = c("DE", "FR", "IT", "ES", "PT", "GR", "NL", "BE", "LU", "AT"), |
|
98 |
#' multiple = TRUE |
|
99 |
#' ), |
|
100 |
#' select = select_spec( |
|
101 |
#' label = "Select variables:", |
|
102 |
#' choices = variable_choices(data[["sales"]], c("quantity", "costs", "profit")), |
|
103 |
#' selected = c("quantity", "costs", "profit"), |
|
104 |
#' multiple = TRUE, |
|
105 |
#' ordered = TRUE, |
|
106 |
#' fixed = FALSE |
|
107 |
#' ) |
|
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 |
#' @examplesIf require("lattice", quietly = TRUE) |
|
122 |
#' # CDISC data example |
|
123 |
#' data <- teal_data() |
|
124 |
#' data <- within(data, { |
|
125 |
#' ADSL <- teal.data::rADSL |
|
126 |
#' ADRS <- teal.data::rADRS |
|
127 |
#' }) |
|
128 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
129 |
#' |
|
130 |
#' app <- init( |
|
131 |
#' data = data, |
|
132 |
#' modules = modules( |
|
133 |
#' tm_g_scatterplotmatrix( |
|
134 |
#' label = "Scatterplot matrix", |
|
135 |
#' variables = list( |
|
136 |
#' data_extract_spec( |
|
137 |
#' dataname = "ADSL", |
|
138 |
#' select = select_spec( |
|
139 |
#' label = "Select variables:", |
|
140 |
#' choices = variable_choices(data[["ADSL"]]), |
|
141 |
#' selected = c("AGE", "RACE", "SEX"), |
|
142 |
#' multiple = TRUE, |
|
143 |
#' ordered = TRUE, |
|
144 |
#' fixed = FALSE |
|
145 |
#' ) |
|
146 |
#' ), |
|
147 |
#' data_extract_spec( |
|
148 |
#' dataname = "ADRS", |
|
149 |
#' filter = filter_spec( |
|
150 |
#' label = "Select endpoints:", |
|
151 |
#' vars = c("PARAMCD", "AVISIT"), |
|
152 |
#' choices = value_choices(data[["ADRS"]], c("PARAMCD", "AVISIT"), c("PARAM", "AVISIT")), |
|
153 |
#' selected = "INVET - END OF INDUCTION", |
|
154 |
#' multiple = TRUE |
|
155 |
#' ), |
|
156 |
#' select = select_spec( |
|
157 |
#' label = "Select variables:", |
|
158 |
#' choices = variable_choices(data[["ADRS"]]), |
|
159 |
#' selected = c("AGE", "AVAL", "ADY"), |
|
160 |
#' multiple = TRUE, |
|
161 |
#' ordered = TRUE, |
|
162 |
#' fixed = FALSE |
|
163 |
#' ) |
|
164 |
#' ) |
|
165 |
#' ) |
|
166 |
#' ) |
|
167 |
#' ) |
|
168 |
#' ) |
|
169 |
#' if (interactive()) { |
|
170 |
#' shinyApp(app$ui, app$server) |
|
171 |
#' } |
|
172 |
#' |
|
173 |
#' @export |
|
174 |
#' |
|
175 |
tm_g_scatterplotmatrix <- function(label = "Scatterplot Matrix", |
|
176 |
variables, |
|
177 |
plot_height = c(600, 200, 2000), |
|
178 |
plot_width = NULL, |
|
179 |
pre_output = NULL, |
|
180 |
post_output = NULL, |
|
181 |
decorators = NULL) { |
|
182 | ! |
message("Initializing tm_g_scatterplotmatrix") |
183 | ||
184 |
# Requires Suggested packages |
|
185 | ! |
if (!requireNamespace("lattice", quietly = TRUE)) { |
186 | ! |
stop("Cannot load lattice - please install the package or restart your session.") |
187 |
} |
|
188 | ||
189 |
# Normalize the parameters |
|
190 | ! |
if (inherits(variables, "data_extract_spec")) variables <- list(variables) |
191 | ||
192 |
# Start of assertions |
|
193 | ! |
checkmate::assert_string(label) |
194 | ! |
checkmate::assert_list(variables, types = "data_extract_spec") |
195 | ||
196 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
197 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
198 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
199 | ! |
checkmate::assert_numeric( |
200 | ! |
plot_width[1], |
201 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
202 |
) |
|
203 | ||
204 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
205 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
206 | ||
207 | ! |
decorators <- normalize_decorators(decorators) |
208 | ! |
assert_decorators(decorators, null.ok = TRUE, "plot") |
209 |
# End of assertions |
|
210 | ||
211 |
# Make UI args |
|
212 | ! |
args <- as.list(environment()) |
213 | ||
214 | ! |
ans <- module( |
215 | ! |
label = label, |
216 | ! |
server = srv_g_scatterplotmatrix, |
217 | ! |
ui = ui_g_scatterplotmatrix, |
218 | ! |
ui_args = args, |
219 | ! |
server_args = list( |
220 | ! |
variables = variables, |
221 | ! |
plot_height = plot_height, |
222 | ! |
plot_width = plot_width, |
223 | ! |
decorators = decorators |
224 |
), |
|
225 | ! |
datanames = teal.transform::get_extract_datanames(variables) |
226 |
) |
|
227 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
228 | ! |
ans |
229 |
} |
|
230 | ||
231 |
# UI function for the scatterplot matrix module |
|
232 |
ui_g_scatterplotmatrix <- function(id, ...) { |
|
233 | ! |
args <- list(...) |
234 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$variables) |
235 | ! |
ns <- NS(id) |
236 | ! |
teal.widgets::standard_layout( |
237 | ! |
output = teal.widgets::white_small_well( |
238 | ! |
textOutput(ns("message")), |
239 | ! |
tags$br(), |
240 | ! |
teal.widgets::plot_with_settings_ui(id = ns("myplot")) |
241 |
), |
|
242 | ! |
encoding = tags$div( |
243 |
### Reporter |
|
244 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
245 |
### |
|
246 | ! |
tags$label("Encodings", class = "text-primary"), |
247 | ! |
teal.transform::datanames_input(args$variables), |
248 | ! |
teal.transform::data_extract_ui( |
249 | ! |
id = ns("variables"), |
250 | ! |
label = "Variables", |
251 | ! |
data_extract_spec = args$variables, |
252 | ! |
is_single_dataset = is_single_dataset_value |
253 |
), |
|
254 | ! |
tags$hr(), |
255 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")), |
256 | ! |
teal.widgets::panel_group( |
257 | ! |
teal.widgets::panel_item( |
258 | ! |
title = "Plot settings", |
259 | ! |
sliderInput( |
260 | ! |
ns("alpha"), "Opacity:", |
261 | ! |
min = 0, max = 1, |
262 | ! |
step = .05, value = .5, ticks = FALSE |
263 |
), |
|
264 | ! |
sliderInput( |
265 | ! |
ns("cex"), "Points size:", |
266 | ! |
min = 0.2, max = 3, |
267 | ! |
step = .05, value = .65, ticks = FALSE |
268 |
), |
|
269 | ! |
checkboxInput(ns("cor"), "Add Correlation", value = FALSE), |
270 | ! |
radioButtons( |
271 | ! |
ns("cor_method"), "Select Correlation Method", |
272 | ! |
choiceNames = c("Pearson", "Kendall", "Spearman"), |
273 | ! |
choiceValues = c("pearson", "kendall", "spearman"), |
274 | ! |
inline = TRUE |
275 |
), |
|
276 | ! |
checkboxInput(ns("cor_na_omit"), "Omit Missing Values", value = TRUE) |
277 |
) |
|
278 |
) |
|
279 |
), |
|
280 | ! |
forms = tagList( |
281 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
282 |
), |
|
283 | ! |
pre_output = args$pre_output, |
284 | ! |
post_output = args$post_output |
285 |
) |
|
286 |
} |
|
287 | ||
288 |
# Server function for the scatterplot matrix module |
|
289 |
srv_g_scatterplotmatrix <- function(id, |
|
290 |
data, |
|
291 |
reporter, |
|
292 |
filter_panel_api, |
|
293 |
variables, |
|
294 |
plot_height, |
|
295 |
plot_width, |
|
296 |
decorators) { |
|
297 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
298 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
299 | ! |
checkmate::assert_class(data, "reactive") |
300 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
301 | ! |
moduleServer(id, function(input, output, session) { |
302 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
303 | ||
304 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
305 | ! |
data_extract = list(variables = variables), |
306 | ! |
datasets = data, |
307 | ! |
select_validation_rule = list( |
308 | ! |
variables = ~ if (length(.) <= 1) "Please select at least 2 columns." |
309 |
) |
|
310 |
) |
|
311 | ||
312 | ! |
iv_r <- reactive({ |
313 | ! |
iv <- shinyvalidate::InputValidator$new() |
314 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
315 |
}) |
|
316 | ||
317 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
318 | ! |
datasets = data, |
319 | ! |
selector_list = selector_list |
320 |
) |
|
321 | ||
322 | ! |
anl_merged_q <- reactive({ |
323 | ! |
req(anl_merged_input()) |
324 | ! |
data() %>% |
325 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
326 |
}) |
|
327 | ||
328 | ! |
merged <- list( |
329 | ! |
anl_input_r = anl_merged_input, |
330 | ! |
anl_q_r = anl_merged_q |
331 |
) |
|
332 | ||
333 |
# plot |
|
334 | ! |
output_q <- reactive({ |
335 | ! |
teal::validate_inputs(iv_r()) |
336 | ||
337 | ! |
qenv <- merged$anl_q_r() |
338 | ! |
ANL <- qenv[["ANL"]] |
339 | ||
340 | ! |
cols_names <- merged$anl_input_r()$columns_source$variables |
341 | ! |
alpha <- input$alpha |
342 | ! |
cex <- input$cex |
343 | ! |
add_cor <- input$cor |
344 | ! |
cor_method <- input$cor_method |
345 | ! |
cor_na_omit <- input$cor_na_omit |
346 | ||
347 | ! |
cor_na_action <- if (isTruthy(cor_na_omit)) { |
348 | ! |
"na.omit" |
349 |
} else { |
|
350 | ! |
"na.fail" |
351 |
} |
|
352 | ||
353 | ! |
teal::validate_has_data(ANL, 10) |
354 | ! |
teal::validate_has_data(ANL[, cols_names, drop = FALSE], 10, complete = TRUE, allow_inf = FALSE) |
355 | ||
356 |
# get labels and proper variable names |
|
357 | ! |
varnames <- varname_w_label(cols_names, ANL, wrap_width = 20) |
358 | ||
359 |
# check character columns. If any, then those are converted to factors |
|
360 | ! |
check_char <- vapply(ANL[, cols_names], is.character, logical(1)) |
361 | ! |
if (any(check_char)) { |
362 | ! |
qenv <- teal.code::eval_code( |
363 | ! |
qenv, |
364 | ! |
substitute( |
365 | ! |
expr = ANL <- ANL[, cols_names] %>% |
366 | ! |
dplyr::mutate_if(is.character, as.factor) %>% |
367 | ! |
droplevels(), |
368 | ! |
env = list(cols_names = cols_names) |
369 |
) |
|
370 |
) |
|
371 |
} else { |
|
372 | ! |
qenv <- teal.code::eval_code( |
373 | ! |
qenv, |
374 | ! |
substitute( |
375 | ! |
expr = ANL <- ANL[, cols_names] %>% |
376 | ! |
droplevels(), |
377 | ! |
env = list(cols_names = cols_names) |
378 |
) |
|
379 |
) |
|
380 |
} |
|
381 | ||
382 | ||
383 |
# create plot |
|
384 | ! |
if (add_cor) { |
385 | ! |
shinyjs::show("cor_method") |
386 | ! |
shinyjs::show("cor_use") |
387 | ! |
shinyjs::show("cor_na_omit") |
388 | ||
389 | ! |
qenv <- teal.code::eval_code( |
390 | ! |
qenv, |
391 | ! |
substitute( |
392 | ! |
expr = { |
393 | ! |
plot <- lattice::splom( |
394 | ! |
ANL, |
395 | ! |
varnames = varnames_value, |
396 | ! |
panel = function(x, y, ...) { |
397 | ! |
lattice::panel.splom(x = x, y = y, ...) |
398 | ! |
cpl <- lattice::current.panel.limits() |
399 | ! |
lattice::panel.text( |
400 | ! |
mean(cpl$xlim), |
401 | ! |
mean(cpl$ylim), |
402 | ! |
get_scatterplotmatrix_stats( |
403 | ! |
x, |
404 | ! |
y, |
405 | ! |
.f = stats::cor.test, |
406 | ! |
.f_args = list(method = cor_method, na.action = cor_na_action) |
407 |
), |
|
408 | ! |
alpha = 0.6, |
409 | ! |
fontsize = 18, |
410 | ! |
fontface = "bold" |
411 |
) |
|
412 |
}, |
|
413 | ! |
pch = 16, |
414 | ! |
alpha = alpha_value, |
415 | ! |
cex = cex_value |
416 |
) |
|
417 |
}, |
|
418 | ! |
env = list( |
419 | ! |
varnames_value = varnames, |
420 | ! |
cor_method = cor_method, |
421 | ! |
cor_na_action = cor_na_action, |
422 | ! |
alpha_value = alpha, |
423 | ! |
cex_value = cex |
424 |
) |
|
425 |
) |
|
426 |
) |
|
427 |
} else { |
|
428 | ! |
shinyjs::hide("cor_method") |
429 | ! |
shinyjs::hide("cor_use") |
430 | ! |
shinyjs::hide("cor_na_omit") |
431 | ! |
qenv <- teal.code::eval_code( |
432 | ! |
qenv, |
433 | ! |
substitute( |
434 | ! |
expr = { |
435 | ! |
plot <- lattice::splom( |
436 | ! |
ANL, |
437 | ! |
varnames = varnames_value, |
438 | ! |
pch = 16, |
439 | ! |
alpha = alpha_value, |
440 | ! |
cex = cex_value |
441 |
) |
|
442 |
}, |
|
443 | ! |
env = list(varnames_value = varnames, alpha_value = alpha, cex_value = cex) |
444 |
) |
|
445 |
) |
|
446 |
} |
|
447 | ! |
qenv |
448 |
}) |
|
449 | ||
450 | ! |
decorated_output_q <- srv_decorate_teal_data( |
451 | ! |
id = "decorator", |
452 | ! |
data = output_q, |
453 | ! |
decorators = select_decorators(decorators, "plot"), |
454 | ! |
expr = print(plot) |
455 |
) |
|
456 | ||
457 | ! |
plot_r <- reactive(req(decorated_output_q())[["plot"]]) |
458 | ||
459 |
# Insert the plot into a plot_with_settings module |
|
460 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
461 | ! |
id = "myplot", |
462 | ! |
plot_r = plot_r, |
463 | ! |
height = plot_height, |
464 | ! |
width = plot_width |
465 |
) |
|
466 | ||
467 |
# show a message if conversion to factors took place |
|
468 | ! |
output$message <- renderText({ |
469 | ! |
req(iv_r()$is_valid()) |
470 | ! |
req(selector_list()$variables()) |
471 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
472 | ! |
cols_names <- unique(unname(do.call(c, merged$anl_input_r()$columns_source))) |
473 | ! |
check_char <- vapply(ANL[, cols_names], is.character, logical(1)) |
474 | ! |
if (any(check_char)) { |
475 | ! |
is_single <- sum(check_char) == 1 |
476 | ! |
paste( |
477 | ! |
"Character", |
478 | ! |
ifelse(is_single, "variable", "variables"), |
479 | ! |
paste0("(", paste(cols_names[check_char], collapse = ", "), ")"), |
480 | ! |
ifelse(is_single, "was", "were"), |
481 | ! |
"converted to", |
482 | ! |
ifelse(is_single, "factor.", "factors.") |
483 |
) |
|
484 |
} else { |
|
485 |
"" |
|
486 |
} |
|
487 |
}) |
|
488 | ||
489 | ! |
teal.widgets::verbatim_popup_srv( |
490 | ! |
id = "rcode", |
491 | ! |
verbatim_content = reactive(teal.code::get_code(req(decorated_output_q()))), |
492 | ! |
title = "Show R Code for Scatterplotmatrix" |
493 |
) |
|
494 | ||
495 |
### REPORTER |
|
496 | ! |
if (with_reporter) { |
497 | ! |
card_fun <- function(comment, label) { |
498 | ! |
card <- teal::report_card_template( |
499 | ! |
title = "Scatter Plot Matrix", |
500 | ! |
label = label, |
501 | ! |
with_filter = with_filter, |
502 | ! |
filter_panel_api = filter_panel_api |
503 |
) |
|
504 | ! |
card$append_text("Plot", "header3") |
505 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
506 | ! |
if (!comment == "") { |
507 | ! |
card$append_text("Comment", "header3") |
508 | ! |
card$append_text(comment) |
509 |
} |
|
510 | ! |
card$append_src(teal.code::get_code(req(decorated_output_q()))) |
511 | ! |
card |
512 |
} |
|
513 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
514 |
} |
|
515 |
### |
|
516 |
}) |
|
517 |
} |
|
518 | ||
519 |
#' Get stats for x-y pairs in scatterplot matrix |
|
520 |
#' |
|
521 |
#' Uses [stats::cor.test()] per default for all numerical input variables and converts results |
|
522 |
#' to character vector. |
|
523 |
#' Could be extended if different stats for different variable types are needed. |
|
524 |
#' Meant to be called from [lattice::panel.text()]. |
|
525 |
#' |
|
526 |
#' Presently we need to use a formula input for `stats::cor.test` because |
|
527 |
#' `na.fail` only gets evaluated when a formula is passed (see below). |
|
528 |
#' ``` |
|
529 |
#' x = c(1,3,5,7,NA) |
|
530 |
#' y = c(3,6,7,8,1) |
|
531 |
#' stats::cor.test(x, y, na.action = "na.fail") |
|
532 |
#' stats::cor.test(~ x + y, na.action = "na.fail") |
|
533 |
#' ``` |
|
534 |
#' |
|
535 |
#' @param x,y (`numeric`) vectors of data values. `x` and `y` must have the same length. |
|
536 |
#' @param .f (`function`) function that accepts x and y as formula input `~ x + y`. |
|
537 |
#' Default `stats::cor.test`. |
|
538 |
#' @param .f_args (`list`) of arguments to be passed to `.f`. |
|
539 |
#' @param round_stat (`integer(1)`) optional, number of decimal places to use when rounding the estimate. |
|
540 |
#' @param round_pval (`integer(1)`) optional, number of decimal places to use when rounding the p-value. |
|
541 |
#' |
|
542 |
#' @return Character with stats. For [stats::cor.test()] correlation coefficient and p-value. |
|
543 |
#' |
|
544 |
#' @examples |
|
545 |
#' set.seed(1) |
|
546 |
#' x <- runif(25, 0, 1) |
|
547 |
#' y <- runif(25, 0, 1) |
|
548 |
#' x[c(3, 10, 18)] <- NA |
|
549 |
#' |
|
550 |
#' get_scatterplotmatrix_stats(x, y, .f = stats::cor.test, .f_args = list(method = "pearson")) |
|
551 |
#' get_scatterplotmatrix_stats(x, y, .f = stats::cor.test, .f_args = list( |
|
552 |
#' method = "pearson", |
|
553 |
#' na.action = na.fail |
|
554 |
#' )) |
|
555 |
#' |
|
556 |
#' @export |
|
557 |
#' |
|
558 |
get_scatterplotmatrix_stats <- function(x, y, |
|
559 |
.f = stats::cor.test, |
|
560 |
.f_args = list(), |
|
561 |
round_stat = 2, |
|
562 |
round_pval = 4) { |
|
563 | 6x |
if (is.numeric(x) && is.numeric(y)) { |
564 | 3x |
stat <- tryCatch(do.call(.f, c(list(~ x + y), .f_args)), error = function(e) NA) |
565 | ||
566 | 3x |
if (anyNA(stat)) { |
567 | 1x |
return("NA") |
568 | 2x |
} else if (all(c("estimate", "p.value") %in% names(stat))) { |
569 | 2x |
return(paste( |
570 | 2x |
c( |
571 | 2x |
paste0(names(stat$estimate), ":", round(stat$estimate, round_stat)), |
572 | 2x |
paste0("P:", round(stat$p.value, round_pval)) |
573 |
), |
|
574 | 2x |
collapse = "\n" |
575 |
)) |
|
576 |
} else { |
|
577 | ! |
stop("function not supported") |
578 |
} |
|
579 |
} else { |
|
580 | 3x |
if ("method" %in% names(.f_args)) { |
581 | 3x |
if (.f_args$method == "pearson") { |
582 | 1x |
return("cor:-") |
583 |
} |
|
584 | 2x |
if (.f_args$method == "kendall") { |
585 | 1x |
return("tau:-") |
586 |
} |
|
587 | 1x |
if (.f_args$method == "spearman") { |
588 | 1x |
return("rho:-") |
589 |
} |
|
590 |
} |
|
591 | ! |
return("-") |
592 |
} |
|
593 |
} |
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`) A vector of datasets which should be |
|
20 |
#' shown and in what order. Names in the vector have to correspond with datasets names. |
|
21 |
#' If vector of `length == 0` (default) then all datasets are shown. |
|
22 |
#' Note: Only datasets of the `data.frame` class are compatible. |
|
23 |
#' @param dt_args (`named list`) Additional arguments to be passed to [DT::datatable()] |
|
24 |
#' (must not include `data` or `options`). |
|
25 |
#' @param dt_options (`named list`) The `options` argument to `DT::datatable`. By default |
|
26 |
#' `list(searching = FALSE, pageLength = 30, lengthMenu = c(5, 15, 30, 100), scrollX = TRUE)` |
|
27 |
#' @param server_rendering (`logical`) should the data table be rendered server side |
|
28 |
#' (see `server` argument of [DT::renderDataTable()]) |
|
29 |
#' @param decorators `r roxygen_decorators_param("tm_data_table")` |
|
30 |
#' |
|
31 |
#' @inherit shared_params return |
|
32 |
#' |
|
33 |
#' @section Decorating `tm_data_table`: |
|
34 |
#' |
|
35 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
36 |
#' - `table` ([DT::datatable()]) |
|
37 |
#' |
|
38 |
#' For additional details and examples of decorators, refer to the vignette |
|
39 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
40 |
#' |
|
41 |
#' @examplesShinylive |
|
42 |
#' library(teal.modules.general) |
|
43 |
#' interactive <- function() TRUE |
|
44 |
#' {{ next_example }} |
|
45 |
#' @examples |
|
46 |
#' # general data example |
|
47 |
#' data <- teal_data() |
|
48 |
#' data <- within(data, { |
|
49 |
#' require(nestcolor) |
|
50 |
#' iris <- iris |
|
51 |
#' }) |
|
52 |
#' |
|
53 |
#' app <- init( |
|
54 |
#' data = data, |
|
55 |
#' modules = modules( |
|
56 |
#' tm_data_table( |
|
57 |
#' variables_selected = list( |
|
58 |
#' iris = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species") |
|
59 |
#' ), |
|
60 |
#' dt_args = list(caption = "IRIS Table Caption") |
|
61 |
#' ) |
|
62 |
#' ) |
|
63 |
#' ) |
|
64 |
#' if (interactive()) { |
|
65 |
#' shinyApp(app$ui, app$server) |
|
66 |
#' } |
|
67 |
#' |
|
68 |
#' @examplesShinylive |
|
69 |
#' library(teal.modules.general) |
|
70 |
#' interactive <- function() TRUE |
|
71 |
#' {{ next_example }} |
|
72 |
#' @examples |
|
73 |
#' # CDISC data example |
|
74 |
#' data <- teal_data() |
|
75 |
#' data <- within(data, { |
|
76 |
#' require(nestcolor) |
|
77 |
#' ADSL <- teal.data::rADSL |
|
78 |
#' }) |
|
79 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
80 |
#' |
|
81 |
#' app <- init( |
|
82 |
#' data = data, |
|
83 |
#' modules = modules( |
|
84 |
#' tm_data_table( |
|
85 |
#' variables_selected = list(ADSL = c("STUDYID", "USUBJID", "SUBJID", "SITEID", "AGE", "SEX")), |
|
86 |
#' dt_args = list(caption = "ADSL Table Caption") |
|
87 |
#' ) |
|
88 |
#' ) |
|
89 |
#' ) |
|
90 |
#' if (interactive()) { |
|
91 |
#' shinyApp(app$ui, app$server) |
|
92 |
#' } |
|
93 |
#' |
|
94 |
#' @export |
|
95 |
#' |
|
96 |
tm_data_table <- function(label = "Data Table", |
|
97 |
variables_selected = list(), |
|
98 |
datasets_selected = character(0), |
|
99 |
dt_args = list(), |
|
100 |
dt_options = list( |
|
101 |
searching = FALSE, |
|
102 |
pageLength = 30, |
|
103 |
lengthMenu = c(5, 15, 30, 100), |
|
104 |
scrollX = TRUE |
|
105 |
), |
|
106 |
server_rendering = FALSE, |
|
107 |
pre_output = NULL, |
|
108 |
post_output = NULL, |
|
109 |
decorators = NULL) { |
|
110 | ! |
message("Initializing tm_data_table") |
111 | ||
112 |
# Start of assertions |
|
113 | ! |
checkmate::assert_string(label) |
114 | ||
115 | ! |
checkmate::assert_list(variables_selected, min.len = 0, types = "character", names = "named") |
116 | ! |
if (length(variables_selected) > 0) { |
117 | ! |
lapply(seq_along(variables_selected), function(i) { |
118 | ! |
checkmate::assert_character(variables_selected[[i]], min.chars = 1, min.len = 1) |
119 | ! |
if (!is.null(names(variables_selected[[i]]))) { |
120 | ! |
checkmate::assert_names(names(variables_selected[[i]])) |
121 |
} |
|
122 |
}) |
|
123 |
} |
|
124 | ||
125 | ! |
checkmate::assert_character(datasets_selected, min.len = 0, min.chars = 1) |
126 | ! |
checkmate::assert( |
127 | ! |
checkmate::check_list(dt_args, len = 0), |
128 | ! |
checkmate::check_subset(names(dt_args), choices = names(formals(DT::datatable))) |
129 |
) |
|
130 | ! |
checkmate::assert_list(dt_options, names = "named") |
131 | ! |
checkmate::assert_flag(server_rendering) |
132 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
133 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
134 | ||
135 | ! |
decorators <- normalize_decorators(decorators) |
136 | ! |
assert_decorators(decorators, null.ok = TRUE, "table") |
137 |
# End of assertions |
|
138 | ||
139 | ! |
ans <- module( |
140 | ! |
label, |
141 | ! |
server = srv_page_data_table, |
142 | ! |
ui = ui_page_data_table, |
143 | ! |
datanames = if (length(datasets_selected) == 0) "all" else datasets_selected, |
144 | ! |
server_args = list( |
145 | ! |
variables_selected = variables_selected, |
146 | ! |
datasets_selected = datasets_selected, |
147 | ! |
dt_args = dt_args, |
148 | ! |
dt_options = dt_options, |
149 | ! |
server_rendering = server_rendering, |
150 | ! |
decorators = decorators |
151 |
), |
|
152 | ! |
ui_args = list( |
153 | ! |
pre_output = pre_output, |
154 | ! |
post_output = post_output |
155 |
) |
|
156 |
) |
|
157 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
158 | ! |
ans |
159 |
} |
|
160 | ||
161 |
# UI page module |
|
162 |
ui_page_data_table <- function(id, pre_output = NULL, post_output = NULL) { |
|
163 | ! |
ns <- NS(id) |
164 | ||
165 | ! |
tagList( |
166 | ! |
include_css_files("custom"), |
167 | ! |
teal.widgets::standard_layout( |
168 | ! |
output = teal.widgets::white_small_well( |
169 | ! |
fluidRow( |
170 | ! |
column( |
171 | ! |
width = 12, |
172 | ! |
checkboxInput( |
173 | ! |
ns("if_distinct"), |
174 | ! |
"Show only distinct rows:", |
175 | ! |
value = FALSE |
176 |
) |
|
177 |
) |
|
178 |
), |
|
179 | ! |
fluidRow( |
180 | ! |
class = "mb-8", |
181 | ! |
column( |
182 | ! |
width = 12, |
183 | ! |
uiOutput(ns("dataset_table")) |
184 |
) |
|
185 |
) |
|
186 |
), |
|
187 | ! |
pre_output = pre_output, |
188 | ! |
post_output = post_output |
189 |
) |
|
190 |
) |
|
191 |
} |
|
192 | ||
193 |
# Server page module |
|
194 |
srv_page_data_table <- function(id, |
|
195 |
data, |
|
196 |
datasets_selected, |
|
197 |
variables_selected, |
|
198 |
dt_args, |
|
199 |
dt_options, |
|
200 |
server_rendering, |
|
201 |
decorators) { |
|
202 | ! |
checkmate::assert_class(data, "reactive") |
203 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
204 | ! |
moduleServer(id, function(input, output, session) { |
205 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
206 | ||
207 | ! |
if_filtered <- reactive(as.logical(input$if_filtered)) |
208 | ! |
if_distinct <- reactive(as.logical(input$if_distinct)) |
209 | ||
210 | ! |
datanames <- isolate(names(data())) |
211 | ! |
datanames <- Filter(function(name) { |
212 | ! |
is.data.frame(isolate(data())[[name]]) |
213 | ! |
}, datanames) |
214 | ||
215 | ! |
if (!identical(datasets_selected, character(0))) { |
216 | ! |
checkmate::assert_subset(datasets_selected, datanames) |
217 | ! |
datanames <- datasets_selected |
218 |
} |
|
219 | ||
220 | ! |
output$dataset_table <- renderUI({ |
221 | ! |
do.call( |
222 | ! |
tabsetPanel, |
223 | ! |
c( |
224 | ! |
list(id = session$ns("dataname_tab")), |
225 | ! |
lapply( |
226 | ! |
datanames, |
227 | ! |
function(x) { |
228 | ! |
dataset <- isolate(data()[[x]]) |
229 | ! |
choices <- names(dataset) |
230 | ! |
labels <- vapply( |
231 | ! |
dataset, |
232 | ! |
function(x) ifelse(is.null(attr(x, "label")), "", attr(x, "label")), |
233 | ! |
character(1) |
234 |
) |
|
235 | ! |
names(choices) <- ifelse( |
236 | ! |
is.na(labels) | labels == "", |
237 | ! |
choices, |
238 | ! |
paste(choices, labels, sep = ": ") |
239 |
) |
|
240 | ! |
variables_selected <- if (!is.null(variables_selected[[x]])) { |
241 | ! |
variables_selected[[x]] |
242 |
} else { |
|
243 | ! |
utils::head(choices) |
244 |
} |
|
245 | ! |
tabPanel( |
246 | ! |
title = x, |
247 | ! |
column( |
248 | ! |
width = 12, |
249 | ! |
div( |
250 | ! |
class = "mt-4", |
251 | ! |
ui_data_table( |
252 | ! |
id = session$ns(x), |
253 | ! |
choices = choices, |
254 | ! |
selected = variables_selected, |
255 | ! |
decorators = decorators |
256 |
) |
|
257 |
) |
|
258 |
) |
|
259 |
) |
|
260 |
} |
|
261 |
) |
|
262 |
) |
|
263 |
) |
|
264 |
}) |
|
265 | ||
266 | ! |
lapply( |
267 | ! |
datanames, |
268 | ! |
function(x) { |
269 | ! |
srv_data_table( |
270 | ! |
id = x, |
271 | ! |
data = data, |
272 | ! |
dataname = x, |
273 | ! |
if_filtered = if_filtered, |
274 | ! |
if_distinct = if_distinct, |
275 | ! |
dt_args = dt_args, |
276 | ! |
dt_options = dt_options, |
277 | ! |
server_rendering = server_rendering, |
278 | ! |
decorators = decorators |
279 |
) |
|
280 |
} |
|
281 |
) |
|
282 |
}) |
|
283 |
} |
|
284 | ||
285 |
# UI function for the data_table module |
|
286 |
ui_data_table <- function(id, |
|
287 |
choices, |
|
288 |
selected, |
|
289 |
decorators) { |
|
290 | ! |
ns <- NS(id) |
291 | ||
292 | ! |
if (!is.null(selected)) { |
293 | ! |
all_choices <- choices |
294 | ! |
choices <- c(selected, setdiff(choices, selected)) |
295 | ! |
names(choices) <- names(all_choices)[match(choices, all_choices)] |
296 |
} |
|
297 | ||
298 | ! |
tagList( |
299 | ! |
teal.widgets::get_dt_rows(ns("data_table"), ns("dt_rows")), |
300 | ! |
fluidRow( |
301 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(decorators, "table")), |
302 | ! |
teal.widgets::optionalSelectInput( |
303 | ! |
ns("variables"), |
304 | ! |
"Select variables:", |
305 | ! |
choices = choices, |
306 | ! |
selected = selected, |
307 | ! |
multiple = TRUE, |
308 | ! |
width = "100%" |
309 |
) |
|
310 |
), |
|
311 | ! |
fluidRow( |
312 | ! |
DT::dataTableOutput(ns("data_table"), width = "100%") |
313 |
) |
|
314 |
) |
|
315 |
} |
|
316 | ||
317 |
# Server function for the data_table module |
|
318 |
srv_data_table <- function(id, |
|
319 |
data, |
|
320 |
dataname, |
|
321 |
if_filtered, |
|
322 |
if_distinct, |
|
323 |
dt_args, |
|
324 |
dt_options, |
|
325 |
server_rendering, |
|
326 |
decorators) { |
|
327 | ! |
moduleServer(id, function(input, output, session) { |
328 | ! |
iv <- shinyvalidate::InputValidator$new() |
329 | ! |
iv$add_rule("variables", shinyvalidate::sv_required("Please select valid variable names")) |
330 | ! |
iv$add_rule("variables", shinyvalidate::sv_in_set( |
331 | ! |
set = names(isolate(data())[[dataname]]), message_fmt = "Not all selected variables exist in the data" |
332 |
)) |
|
333 | ! |
iv$enable() |
334 | ||
335 | ! |
data_table_data <- reactive({ |
336 | ! |
df <- data()[[dataname]] |
337 | ||
338 | ! |
teal::validate_has_data(df, min_nrow = 1L, msg = paste("data", dataname, "is empty")) |
339 | ||
340 | ! |
teal.code::eval_code( |
341 | ! |
data(), |
342 | ! |
substitute( |
343 | ! |
expr = { |
344 | ! |
variables <- vars |
345 | ! |
dataframe_selected <- if (if_distinct) { |
346 | ! |
dplyr::count(dataname, dplyr::across(dplyr::all_of(variables))) |
347 |
} else { |
|
348 | ! |
dataname[variables] |
349 |
} |
|
350 | ! |
dt_args <- args |
351 | ! |
dt_args$options <- dt_options |
352 | ! |
if (!is.null(dt_rows)) { |
353 | ! |
dt_args$options$pageLength <- dt_rows |
354 |
} |
|
355 | ! |
dt_args$data <- dataframe_selected |
356 | ! |
table <- do.call(DT::datatable, dt_args) |
357 |
}, |
|
358 | ! |
env = list( |
359 | ! |
dataname = as.name(dataname), |
360 | ! |
if_distinct = if_distinct(), |
361 | ! |
vars = input$variables, |
362 | ! |
args = dt_args, |
363 | ! |
dt_options = dt_options, |
364 | ! |
dt_rows = input$dt_rows |
365 |
) |
|
366 |
) |
|
367 |
) |
|
368 |
}) |
|
369 | ||
370 | ! |
decorated_data_table_data <- srv_decorate_teal_data( |
371 | ! |
id = "decorator", |
372 | ! |
data = data_table_data, |
373 | ! |
decorators = select_decorators(decorators, "table") |
374 |
) |
|
375 | ||
376 | ! |
output$data_table <- DT::renderDataTable(server = server_rendering, { |
377 | ! |
teal::validate_inputs(iv) |
378 | ! |
req(decorated_data_table_data())[["table"]] |
379 |
}) |
|
380 |
}) |
|
381 |
} |
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 |
interactive <- NULL |