1 |
#' `teal` module: Outliers analysis |
|
2 |
#' |
|
3 |
#' Module to analyze and identify outliers using different methods |
|
4 |
#' such as IQR, Z-score, and Percentiles, and offers visualizations including |
|
5 |
#' box plots, density plots, and cumulative distribution plots to help interpret the outliers. |
|
6 |
#' |
|
7 |
#' @inheritParams teal::module |
|
8 |
#' @inheritParams shared_params |
|
9 |
#' |
|
10 |
#' @param outlier_var (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
11 |
#' Specifies variable(s) to be analyzed for outliers. |
|
12 |
#' @param categorical_var (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
13 |
#' specifies the categorical variable(s) to split the selected outlier variables on. |
|
14 |
#' @param ggplot2_args `r roxygen_ggplot2_args_param("Boxplot", "Density Plot", "Cumulative Distribution Plot")` |
|
15 |
#' |
|
16 |
#' @inherit shared_params return |
|
17 |
#' |
|
18 |
#' @section Decorating Module: |
|
19 |
#' |
|
20 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
21 |
#' - `box_plot` (`ggplot2`) |
|
22 |
#' - `density_plot` (`ggplot2`) |
|
23 |
#' - `cumulative_plot` (`ggplot2`) |
|
24 |
#' - `table` (`listing_df` created with [rlistings::as_listing()]) |
|
25 |
#' |
|
26 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
27 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
28 |
#' See code snippet below: |
|
29 |
#' |
|
30 |
#' ``` |
|
31 |
#' tm_outliers( |
|
32 |
#' ..., # arguments for module |
|
33 |
#' decorators = list( |
|
34 |
#' box_plot = teal_transform_module(...), # applied only to `box_plot` output |
|
35 |
#' density_plot = teal_transform_module(...), # applied only to `density_plot` output |
|
36 |
#' cumulative_plot = teal_transform_module(...), # applied only to `cumulative_plot` output |
|
37 |
#' table = teal_transform_module(...) # applied only to `table` output |
|
38 |
#' ) |
|
39 |
#' ) |
|
40 |
#' ``` |
|
41 |
#' |
|
42 |
#' For additional details and examples of decorators, refer to the vignette |
|
43 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
44 |
#' |
|
45 |
#' @examplesShinylive |
|
46 |
#' library(teal.modules.general) |
|
47 |
#' interactive <- function() TRUE |
|
48 |
#' {{ next_example }} |
|
49 |
#' @examples |
|
50 |
#' |
|
51 |
#' # general data example |
|
52 |
#' data <- teal_data() |
|
53 |
#' data <- within(data, { |
|
54 |
#' CO2 <- CO2 |
|
55 |
#' CO2[["primary_key"]] <- seq_len(nrow(CO2)) |
|
56 |
#' }) |
|
57 |
#' join_keys(data) <- join_keys(join_key("CO2", "CO2", "primary_key")) |
|
58 |
#' |
|
59 |
#' vars <- choices_selected(variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment"))) |
|
60 |
#' |
|
61 |
#' app <- init( |
|
62 |
#' data = data, |
|
63 |
#' modules = modules( |
|
64 |
#' tm_outliers( |
|
65 |
#' outlier_var = list( |
|
66 |
#' data_extract_spec( |
|
67 |
#' dataname = "CO2", |
|
68 |
#' select = select_spec( |
|
69 |
#' label = "Select variable:", |
|
70 |
#' choices = variable_choices(data[["CO2"]], c("conc", "uptake")), |
|
71 |
#' selected = "uptake", |
|
72 |
#' multiple = FALSE, |
|
73 |
#' fixed = FALSE |
|
74 |
#' ) |
|
75 |
#' ) |
|
76 |
#' ), |
|
77 |
#' categorical_var = list( |
|
78 |
#' data_extract_spec( |
|
79 |
#' dataname = "CO2", |
|
80 |
#' filter = filter_spec( |
|
81 |
#' vars = vars, |
|
82 |
#' choices = value_choices(data[["CO2"]], vars$selected), |
|
83 |
#' selected = value_choices(data[["CO2"]], vars$selected), |
|
84 |
#' multiple = TRUE |
|
85 |
#' ) |
|
86 |
#' ) |
|
87 |
#' ) |
|
88 |
#' ) |
|
89 |
#' ) |
|
90 |
#' ) |
|
91 |
#' if (interactive()) { |
|
92 |
#' shinyApp(app$ui, app$server) |
|
93 |
#' } |
|
94 |
#' |
|
95 |
#' @examplesShinylive |
|
96 |
#' library(teal.modules.general) |
|
97 |
#' interactive <- function() TRUE |
|
98 |
#' {{ next_example }} |
|
99 |
#' @examples |
|
100 |
#' |
|
101 |
#' # CDISC data example |
|
102 |
#' data <- teal_data() |
|
103 |
#' data <- within(data, { |
|
104 |
#' ADSL <- teal.data::rADSL |
|
105 |
#' }) |
|
106 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
107 |
#' |
|
108 |
#' fact_vars_adsl <- names(Filter(isTRUE, sapply(data[["ADSL"]], is.factor))) |
|
109 |
#' vars <- choices_selected(variable_choices(data[["ADSL"]], fact_vars_adsl)) |
|
110 |
#' |
|
111 |
#' |
|
112 |
#' |
|
113 |
#' app <- init( |
|
114 |
#' data = data, |
|
115 |
#' modules = modules( |
|
116 |
#' tm_outliers( |
|
117 |
#' outlier_var = list( |
|
118 |
#' data_extract_spec( |
|
119 |
#' dataname = "ADSL", |
|
120 |
#' select = select_spec( |
|
121 |
#' label = "Select variable:", |
|
122 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1")), |
|
123 |
#' selected = "AGE", |
|
124 |
#' multiple = FALSE, |
|
125 |
#' fixed = FALSE |
|
126 |
#' ) |
|
127 |
#' ) |
|
128 |
#' ), |
|
129 |
#' categorical_var = list( |
|
130 |
#' data_extract_spec( |
|
131 |
#' dataname = "ADSL", |
|
132 |
#' filter = filter_spec( |
|
133 |
#' vars = vars, |
|
134 |
#' choices = value_choices(data[["ADSL"]], vars$selected), |
|
135 |
#' selected = value_choices(data[["ADSL"]], vars$selected), |
|
136 |
#' multiple = TRUE |
|
137 |
#' ) |
|
138 |
#' ) |
|
139 |
#' ) |
|
140 |
#' ) |
|
141 |
#' ) |
|
142 |
#' ) |
|
143 |
#' if (interactive()) { |
|
144 |
#' shinyApp(app$ui, app$server) |
|
145 |
#' } |
|
146 |
#' |
|
147 |
#' @export |
|
148 |
#' |
|
149 |
tm_outliers <- function(label = "Outliers Module", |
|
150 |
outlier_var, |
|
151 |
categorical_var = NULL, |
|
152 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
153 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
154 |
plot_height = c(600, 200, 2000), |
|
155 |
plot_width = NULL, |
|
156 |
pre_output = NULL, |
|
157 |
post_output = NULL, |
|
158 |
transformators = list(), |
|
159 |
decorators = list()) { |
|
160 | ! |
message("Initializing tm_outliers") |
161 | ||
162 |
# Normalize the parameters |
|
163 | ! |
if (inherits(outlier_var, "data_extract_spec")) outlier_var <- list(outlier_var) |
164 | ! |
if (inherits(categorical_var, "data_extract_spec")) categorical_var <- list(categorical_var) |
165 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
166 | ||
167 |
# Start of assertions |
|
168 | ! |
checkmate::assert_string(label) |
169 | ! |
checkmate::assert_list(outlier_var, types = "data_extract_spec") |
170 | ||
171 | ! |
checkmate::assert_list(categorical_var, types = "data_extract_spec", null.ok = TRUE) |
172 | ! |
if (is.list(categorical_var)) { |
173 | ! |
lapply(categorical_var, function(x) { |
174 | ! |
if (length(x$filter) > 1L) { |
175 | ! |
stop("tm_outliers: categorical_var data_extract_specs may only specify one filter_spec", call. = FALSE) |
176 |
} |
|
177 |
}) |
|
178 |
} |
|
179 | ||
180 | ! |
ggtheme <- match.arg(ggtheme) |
181 | ||
182 | ! |
plot_choices <- c("Boxplot", "Density Plot", "Cumulative Distribution Plot") |
183 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
184 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
185 | ||
186 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
187 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
188 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
189 | ! |
checkmate::assert_numeric( |
190 | ! |
plot_width[1], |
191 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
192 |
) |
|
193 | ||
194 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
195 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
196 | ||
197 | ! |
available_decorators <- c("box_plot", "density_plot", "cumulative_plot", "table") |
198 | ! |
assert_decorators(decorators, names = available_decorators) |
199 |
# End of assertions |
|
200 | ||
201 |
# Make UI args |
|
202 | ! |
args <- as.list(environment()) |
203 | ||
204 | ! |
data_extract_list <- list( |
205 | ! |
outlier_var = outlier_var, |
206 | ! |
categorical_var = categorical_var |
207 |
) |
|
208 | ||
209 | ||
210 | ! |
ans <- module( |
211 | ! |
label = label, |
212 | ! |
server = srv_outliers, |
213 | ! |
server_args = c( |
214 | ! |
data_extract_list, |
215 | ! |
list( |
216 | ! |
plot_height = plot_height, plot_width = plot_width, ggplot2_args = ggplot2_args, |
217 | ! |
decorators = decorators |
218 |
) |
|
219 |
), |
|
220 | ! |
ui = ui_outliers, |
221 | ! |
ui_args = args, |
222 | ! |
transformators = transformators, |
223 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
224 |
) |
|
225 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
226 | ! |
ans |
227 |
} |
|
228 | ||
229 |
# UI function for the outliers module |
|
230 |
ui_outliers <- function(id, ...) { |
|
231 | ! |
args <- list(...) |
232 | ! |
ns <- NS(id) |
233 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$outlier_var, args$categorical_var) |
234 | ||
235 | ! |
teal.widgets::standard_layout( |
236 | ! |
output = teal.widgets::white_small_well( |
237 | ! |
uiOutput(ns("total_outliers")), |
238 | ! |
DT::dataTableOutput(ns("summary_table")), |
239 | ! |
uiOutput(ns("total_missing")), |
240 | ! |
tags$br(), tags$hr(), |
241 | ! |
tabsetPanel( |
242 | ! |
id = ns("tabs"), |
243 | ! |
tabPanel( |
244 | ! |
"Boxplot", |
245 | ! |
teal.widgets::plot_with_settings_ui(id = ns("box_plot")) |
246 |
), |
|
247 | ! |
tabPanel( |
248 | ! |
"Density Plot", |
249 | ! |
teal.widgets::plot_with_settings_ui(id = ns("density_plot")) |
250 |
), |
|
251 | ! |
tabPanel( |
252 | ! |
"Cumulative Distribution Plot", |
253 | ! |
teal.widgets::plot_with_settings_ui(id = ns("cum_density_plot")) |
254 |
) |
|
255 |
), |
|
256 | ! |
tags$br(), tags$hr(), |
257 | ! |
uiOutput(ns("table_ui_wrap")), |
258 | ! |
DT::dataTableOutput(ns("table_ui")) |
259 |
), |
|
260 | ! |
encoding = tags$div( |
261 |
### Reporter |
|
262 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
263 |
### |
|
264 | ! |
tags$label("Encodings", class = "text-primary"), |
265 | ! |
teal.transform::datanames_input(args[c("outlier_var", "categorical_var")]), |
266 | ! |
teal.transform::data_extract_ui( |
267 | ! |
id = ns("outlier_var"), |
268 | ! |
label = "Variable", |
269 | ! |
data_extract_spec = args$outlier_var, |
270 | ! |
is_single_dataset = is_single_dataset_value |
271 |
), |
|
272 | ! |
if (!is.null(args$categorical_var)) { |
273 | ! |
teal.transform::data_extract_ui( |
274 | ! |
id = ns("categorical_var"), |
275 | ! |
label = "Categorical factor", |
276 | ! |
data_extract_spec = args$categorical_var, |
277 | ! |
is_single_dataset = is_single_dataset_value |
278 |
) |
|
279 |
}, |
|
280 | ! |
conditionalPanel( |
281 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'Boxplot'"), |
282 | ! |
teal.widgets::optionalSelectInput( |
283 | ! |
inputId = ns("boxplot_alts"), |
284 | ! |
label = "Plot type", |
285 | ! |
choices = c("Box plot", "Violin plot"), |
286 | ! |
selected = "Box plot", |
287 | ! |
multiple = FALSE |
288 |
) |
|
289 |
), |
|
290 | ! |
shinyjs::hidden(checkboxInput(ns("split_outliers"), "Define outliers based on group splitting", value = FALSE)), |
291 | ! |
shinyjs::hidden(checkboxInput(ns("order_by_outlier"), "Re-order categories by outliers [by %]", value = FALSE)), |
292 | ! |
teal.widgets::panel_group( |
293 | ! |
teal.widgets::panel_item( |
294 | ! |
title = "Method parameters", |
295 | ! |
collapsed = FALSE, |
296 | ! |
teal.widgets::optionalSelectInput( |
297 | ! |
inputId = ns("method"), |
298 | ! |
label = "Method", |
299 | ! |
choices = c("IQR", "Z-score", "Percentile"), |
300 | ! |
selected = "IQR", |
301 | ! |
multiple = FALSE |
302 |
), |
|
303 | ! |
conditionalPanel( |
304 | ! |
condition = |
305 | ! |
paste0("input['", ns("method"), "'] == 'IQR'"), |
306 | ! |
sliderInput( |
307 | ! |
ns("iqr_slider"), |
308 | ! |
"Outlier range:", |
309 | ! |
min = 1, |
310 | ! |
max = 5, |
311 | ! |
value = 3, |
312 | ! |
step = 0.5 |
313 |
) |
|
314 |
), |
|
315 | ! |
conditionalPanel( |
316 | ! |
condition = |
317 | ! |
paste0("input['", ns("method"), "'] == 'Z-score'"), |
318 | ! |
sliderInput( |
319 | ! |
ns("zscore_slider"), |
320 | ! |
"Outlier range:", |
321 | ! |
min = 1, |
322 | ! |
max = 5, |
323 | ! |
value = 3, |
324 | ! |
step = 0.5 |
325 |
) |
|
326 |
), |
|
327 | ! |
conditionalPanel( |
328 | ! |
condition = |
329 | ! |
paste0("input['", ns("method"), "'] == 'Percentile'"), |
330 | ! |
sliderInput( |
331 | ! |
ns("percentile_slider"), |
332 | ! |
"Outlier range:", |
333 | ! |
min = 0.001, |
334 | ! |
max = 0.5, |
335 | ! |
value = 0.01, |
336 | ! |
step = 0.001 |
337 |
) |
|
338 |
), |
|
339 | ! |
uiOutput(ns("ui_outlier_help")) |
340 |
) |
|
341 |
), |
|
342 | ! |
conditionalPanel( |
343 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'Boxplot'"), |
344 | ! |
ui_decorate_teal_data( |
345 | ! |
ns("d_box_plot"), |
346 | ! |
decorators = select_decorators(args$decorators, "box_plot") |
347 |
) |
|
348 |
), |
|
349 | ! |
conditionalPanel( |
350 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'Density Plot'"), |
351 | ! |
ui_decorate_teal_data( |
352 | ! |
ns("d_density_plot"), |
353 | ! |
decorators = select_decorators(args$decorators, "density_plot") |
354 |
) |
|
355 |
), |
|
356 | ! |
conditionalPanel( |
357 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'Cumulative Distribution Plot'"), |
358 | ! |
ui_decorate_teal_data( |
359 | ! |
ns("d_cumulative_plot"), |
360 | ! |
decorators = select_decorators(args$decorators, "cumulative_plot") |
361 |
) |
|
362 |
), |
|
363 | ! |
ui_decorate_teal_data(ns("d_table"), decorators = select_decorators(args$decorators, "table")), |
364 | ! |
teal.widgets::panel_item( |
365 | ! |
title = "Plot settings", |
366 | ! |
selectInput( |
367 | ! |
inputId = ns("ggtheme"), |
368 | ! |
label = "Theme (by ggplot):", |
369 | ! |
choices = ggplot_themes, |
370 | ! |
selected = args$ggtheme, |
371 | ! |
multiple = FALSE |
372 |
) |
|
373 |
) |
|
374 |
), |
|
375 | ! |
forms = tagList( |
376 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
377 |
), |
|
378 | ! |
pre_output = args$pre_output, |
379 | ! |
post_output = args$post_output |
380 |
) |
|
381 |
} |
|
382 | ||
383 |
# Server function for the outliers module |
|
384 |
# Server function for the outliers module |
|
385 |
srv_outliers <- function(id, data, reporter, filter_panel_api, outlier_var, |
|
386 |
categorical_var, plot_height, plot_width, ggplot2_args, decorators) { |
|
387 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
388 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
389 | ! |
checkmate::assert_class(data, "reactive") |
390 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
391 | ! |
moduleServer(id, function(input, output, session) { |
392 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
393 | ||
394 | ! |
ns <- session$ns |
395 | ||
396 | ! |
vars <- list(outlier_var = outlier_var, categorical_var = categorical_var) |
397 | ||
398 | ! |
rule_diff <- function(other) { |
399 | ! |
function(value) { |
400 | ! |
othervalue <- tryCatch(selector_list()[[other]]()[["select"]], error = function(e) NULL) |
401 | ! |
if (!is.null(othervalue) && identical(othervalue, value)) { |
402 | ! |
"`Variable` and `Categorical factor` cannot be the same" |
403 |
} |
|
404 |
} |
|
405 |
} |
|
406 | ||
407 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
408 | ! |
data_extract = vars, |
409 | ! |
datasets = data, |
410 | ! |
select_validation_rule = list( |
411 | ! |
outlier_var = shinyvalidate::compose_rules( |
412 | ! |
shinyvalidate::sv_required("Please select a variable"), |
413 | ! |
rule_diff("categorical_var") |
414 |
), |
|
415 | ! |
categorical_var = rule_diff("outlier_var") |
416 |
) |
|
417 |
) |
|
418 | ||
419 | ! |
iv_r <- reactive({ |
420 | ! |
iv <- shinyvalidate::InputValidator$new() |
421 | ! |
iv$add_rule("method", shinyvalidate::sv_required("Please select a method")) |
422 | ! |
iv$add_rule("boxplot_alts", shinyvalidate::sv_required("Please select Plot Type")) |
423 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
424 |
}) |
|
425 | ||
426 | ! |
reactive_select_input <- reactive({ |
427 | ! |
if (is.null(selector_list()$categorical_var) || length(selector_list()$categorical_var()$select) == 0) { |
428 | ! |
selector_list()[names(selector_list()) != "categorical_var"] |
429 |
} else { |
|
430 | ! |
selector_list() |
431 |
} |
|
432 |
}) |
|
433 | ||
434 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
435 | ! |
selector_list = reactive_select_input, |
436 | ! |
datasets = data, |
437 | ! |
merge_function = "dplyr::inner_join" |
438 |
) |
|
439 | ||
440 | ! |
anl_merged_q <- reactive({ |
441 | ! |
req(anl_merged_input()) |
442 | ! |
data() %>% |
443 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
444 |
}) |
|
445 | ||
446 | ! |
merged <- list( |
447 | ! |
anl_input_r = anl_merged_input, |
448 | ! |
anl_q_r = anl_merged_q |
449 |
) |
|
450 | ||
451 | ! |
n_outlier_missing <- reactive({ |
452 | ! |
req(iv_r()$is_valid()) |
453 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
454 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
455 | ! |
sum(is.na(ANL[[outlier_var]])) |
456 |
}) |
|
457 | ||
458 |
# Used to create outlier table and the dropdown with additional columns |
|
459 | ! |
dataname_first <- isolate(names(data())[[1]]) |
460 | ||
461 | ! |
common_code_q <- reactive({ |
462 | ! |
req(iv_r()$is_valid()) |
463 | ||
464 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
465 | ! |
qenv <- merged$anl_q_r() |
466 | ||
467 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
468 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
469 | ! |
order_by_outlier <- input$order_by_outlier |
470 | ! |
method <- input$method |
471 | ! |
split_outliers <- input$split_outliers |
472 | ! |
teal::validate_has_data( |
473 |
# missing values in the categorical variable may be used to form a category of its own |
|
474 | ! |
`if`( |
475 | ! |
length(categorical_var) == 0, |
476 | ! |
ANL, |
477 | ! |
ANL[, names(ANL) != categorical_var, drop = FALSE] |
478 |
), |
|
479 | ! |
min_nrow = 10, |
480 | ! |
complete = TRUE, |
481 | ! |
allow_inf = FALSE |
482 |
) |
|
483 | ! |
validate(need(is.numeric(ANL[[outlier_var]]), "`Variable` is not numeric")) |
484 | ! |
validate(need(length(unique(ANL[[outlier_var]])) > 1, "Variable has no variation, i.e. only one unique value")) |
485 | ||
486 |
# show/hide split_outliers |
|
487 | ! |
if (length(categorical_var) == 0) { |
488 | ! |
shinyjs::hide("split_outliers") |
489 | ! |
if (n_outlier_missing() > 0) { |
490 | ! |
qenv <- teal.code::eval_code( |
491 | ! |
qenv, |
492 | ! |
substitute( |
493 | ! |
expr = ANL <- ANL %>% dplyr::filter(!is.na(outlier_var_name)), |
494 | ! |
env = list(outlier_var_name = as.name(outlier_var)) |
495 |
) |
|
496 |
) |
|
497 |
} |
|
498 |
} else { |
|
499 | ! |
validate(need( |
500 | ! |
is.factor(ANL[[categorical_var]]) || |
501 | ! |
is.character(ANL[[categorical_var]]) || |
502 | ! |
is.integer(ANL[[categorical_var]]), |
503 | ! |
"`Categorical factor` must be `factor`, `character`, or `integer`" |
504 |
)) |
|
505 | ||
506 | ! |
if (n_outlier_missing() > 0) { |
507 | ! |
qenv <- teal.code::eval_code( |
508 | ! |
qenv, |
509 | ! |
substitute( |
510 | ! |
expr = ANL <- ANL %>% dplyr::filter(!is.na(outlier_var_name)), |
511 | ! |
env = list(outlier_var_name = as.name(outlier_var)) |
512 |
) |
|
513 |
) |
|
514 |
} |
|
515 | ! |
shinyjs::show("split_outliers") |
516 |
} |
|
517 | ||
518 |
# slider |
|
519 | ! |
outlier_definition_param <- if (method == "IQR") { |
520 | ! |
input$iqr_slider |
521 | ! |
} else if (method == "Z-score") { |
522 | ! |
input$zscore_slider |
523 | ! |
} else if (method == "Percentile") { |
524 | ! |
input$percentile_slider |
525 |
} |
|
526 | ||
527 |
# this is utils function that converts a %>% NULL %>% b into a %>% b |
|
528 | ! |
remove_pipe_null <- function(x) { |
529 | ! |
if (length(x) == 1) { |
530 | ! |
return(x) |
531 |
} |
|
532 | ! |
if (identical(x[[1]], as.name("%>%")) && is.null(x[[3]])) { |
533 | ! |
return(remove_pipe_null(x[[2]])) |
534 |
} |
|
535 | ! |
return(as.call(c(x[[1]], lapply(x[-1], remove_pipe_null)))) |
536 |
} |
|
537 | ||
538 | ! |
qenv <- teal.code::eval_code( |
539 | ! |
qenv, |
540 | ! |
substitute( |
541 | ! |
expr = { |
542 | ! |
ANL_OUTLIER <- ANL %>% |
543 | ! |
group_expr %>% # styler: off |
544 | ! |
dplyr::mutate(is_outlier = { |
545 | ! |
q1_q3 <- stats::quantile(outlier_var_name, probs = c(0.25, 0.75)) |
546 | ! |
iqr <- q1_q3[2] - q1_q3[1] |
547 | ! |
!(outlier_var_name >= q1_q3[1] - 1.5 * iqr & outlier_var_name <= q1_q3[2] + 1.5 * iqr) |
548 |
}) %>% |
|
549 | ! |
calculate_outliers %>% # styler: off |
550 | ! |
ungroup_expr %>% # styler: off |
551 | ! |
dplyr::filter(is_outlier | is_outlier_selected) %>% |
552 | ! |
dplyr::select(-is_outlier) |
553 |
}, |
|
554 | ! |
env = list( |
555 | ! |
calculate_outliers = if (method == "IQR") { |
556 | ! |
substitute( |
557 | ! |
expr = dplyr::mutate(is_outlier_selected = { |
558 | ! |
q1_q3 <- stats::quantile(outlier_var_name, probs = c(0.25, 0.75)) |
559 | ! |
iqr <- q1_q3[2] - q1_q3[1] |
560 |
!( |
|
561 | ! |
outlier_var_name >= q1_q3[1] - outlier_definition_param * iqr & |
562 | ! |
outlier_var_name <= q1_q3[2] + outlier_definition_param * iqr |
563 |
) |
|
564 |
}), |
|
565 | ! |
env = list( |
566 | ! |
outlier_var_name = as.name(outlier_var), |
567 | ! |
outlier_definition_param = outlier_definition_param |
568 |
) |
|
569 |
) |
|
570 | ! |
} else if (method == "Z-score") { |
571 | ! |
substitute( |
572 | ! |
expr = dplyr::mutate( |
573 | ! |
is_outlier_selected = abs(outlier_var_name - mean(outlier_var_name)) / |
574 | ! |
stats::sd(outlier_var_name) > outlier_definition_param |
575 |
), |
|
576 | ! |
env = list( |
577 | ! |
outlier_var_name = as.name(outlier_var), |
578 | ! |
outlier_definition_param = outlier_definition_param |
579 |
) |
|
580 |
) |
|
581 | ! |
} else if (method == "Percentile") { |
582 | ! |
substitute( |
583 | ! |
expr = dplyr::mutate( |
584 | ! |
is_outlier_selected = outlier_var_name < stats::quantile(outlier_var_name, outlier_definition_param) | |
585 | ! |
outlier_var_name > stats::quantile(outlier_var_name, 1 - outlier_definition_param) |
586 |
), |
|
587 | ! |
env = list( |
588 | ! |
outlier_var_name = as.name(outlier_var), |
589 | ! |
outlier_definition_param = outlier_definition_param |
590 |
) |
|
591 |
) |
|
592 |
}, |
|
593 | ! |
outlier_var_name = as.name(outlier_var), |
594 | ! |
group_expr = if (isTRUE(split_outliers) && length(categorical_var) != 0) { |
595 | ! |
substitute(dplyr::group_by(x), list(x = as.name(categorical_var))) |
596 |
}, |
|
597 | ! |
ungroup_expr = if (isTRUE(split_outliers) && length(categorical_var) != 0) { |
598 | ! |
substitute(dplyr::ungroup()) |
599 |
} |
|
600 |
) |
|
601 |
) %>% |
|
602 | ! |
remove_pipe_null() |
603 |
) |
|
604 | ||
605 |
# ANL_OUTLIER_EXTENDED is the base table |
|
606 | ! |
qenv <- teal.code::eval_code( |
607 | ! |
qenv, |
608 | ! |
substitute( |
609 | ! |
expr = { |
610 | ! |
ANL_OUTLIER_EXTENDED <- dplyr::left_join( |
611 | ! |
ANL_OUTLIER, |
612 | ! |
dplyr::select( |
613 | ! |
dataname, |
614 | ! |
dplyr::setdiff(names(dataname), dplyr::setdiff(names(ANL_OUTLIER), join_keys)) |
615 |
), |
|
616 | ! |
by = join_keys |
617 |
) |
|
618 |
}, |
|
619 | ! |
env = list( |
620 | ! |
dataname = as.name(dataname_first), |
621 | ! |
join_keys = as.character(teal.data::join_keys(data())[dataname_first, dataname_first]) |
622 |
) |
|
623 |
) |
|
624 |
) |
|
625 | ||
626 | ! |
qenv <- if (length(categorical_var) > 0) { |
627 | ! |
qenv <- teal.code::eval_code( |
628 | ! |
qenv, |
629 | ! |
substitute( |
630 | ! |
expr = summary_table_pre <- ANL_OUTLIER %>% |
631 | ! |
dplyr::filter(is_outlier_selected) %>% |
632 | ! |
dplyr::select(outlier_var_name, categorical_var_name) %>% |
633 | ! |
dplyr::group_by(categorical_var_name) %>% |
634 | ! |
dplyr::summarise(n_outliers = dplyr::n()) %>% |
635 | ! |
dplyr::right_join( |
636 | ! |
ANL %>% |
637 | ! |
dplyr::select(outlier_var_name, categorical_var_name) %>% |
638 | ! |
dplyr::group_by(categorical_var_name) %>% |
639 | ! |
dplyr::summarise( |
640 | ! |
total_in_cat = dplyr::n(), |
641 | ! |
n_na = sum(is.na(outlier_var_name) | is.na(categorical_var_name)) |
642 |
), |
|
643 | ! |
by = categorical_var |
644 |
) %>% |
|
645 |
# This is important as there may be categorical variables with natural orderings, e.g. AGE. |
|
646 |
# The plots should be displayed by default in increasing order in these situations. |
|
647 |
# dplyr::arrange will sort integer, factor, and character data types in the expected way. |
|
648 | ! |
dplyr::arrange(categorical_var_name) %>% |
649 | ! |
dplyr::mutate( |
650 | ! |
n_outliers = dplyr::if_else(is.na(n_outliers), 0, as.numeric(n_outliers)), |
651 | ! |
display_str = dplyr::if_else( |
652 | ! |
n_outliers > 0, |
653 | ! |
sprintf("%d [%.02f%%]", n_outliers, 100 * n_outliers / total_in_cat), |
654 | ! |
"0" |
655 |
), |
|
656 | ! |
display_str_na = dplyr::if_else( |
657 | ! |
n_na > 0, |
658 | ! |
sprintf("%d [%.02f%%]", n_na, 100 * n_na / total_in_cat), |
659 | ! |
"0" |
660 |
), |
|
661 | ! |
order = seq_along(n_outliers) |
662 |
), |
|
663 | ! |
env = list( |
664 | ! |
categorical_var = categorical_var, |
665 | ! |
categorical_var_name = as.name(categorical_var), |
666 | ! |
outlier_var_name = as.name(outlier_var) |
667 |
) |
|
668 |
) |
|
669 |
) |
|
670 |
# now to handle when user chooses to order based on amount of outliers |
|
671 | ! |
if (order_by_outlier) { |
672 | ! |
qenv <- teal.code::eval_code( |
673 | ! |
qenv, |
674 | ! |
quote( |
675 | ! |
summary_table_pre <- summary_table_pre %>% |
676 | ! |
dplyr::arrange(desc(n_outliers / total_in_cat)) %>% |
677 | ! |
dplyr::mutate(order = seq_len(nrow(summary_table_pre))) |
678 |
) |
|
679 |
) |
|
680 |
} |
|
681 | ||
682 | ! |
teal.code::eval_code( |
683 | ! |
qenv, |
684 | ! |
substitute( |
685 | ! |
expr = { |
686 |
# In order for geom_rug to work properly when reordering takes place inside facet_grid, |
|
687 |
# all tables must have the column used for reording. |
|
688 |
# In this case, the column used for reordering is `order`. |
|
689 | ! |
ANL_OUTLIER <- dplyr::left_join( |
690 | ! |
ANL_OUTLIER, |
691 | ! |
summary_table_pre[, c("order", categorical_var)], |
692 | ! |
by = categorical_var |
693 |
) |
|
694 |
# so that x axis of plot aligns with columns of summary table, from most outliers to least by percentage |
|
695 | ! |
ANL <- ANL %>% |
696 | ! |
dplyr::left_join( |
697 | ! |
dplyr::select(summary_table_pre, categorical_var_name, order), |
698 | ! |
by = categorical_var |
699 |
) %>% |
|
700 | ! |
dplyr::arrange(order) |
701 | ! |
summary_table <- summary_table_pre %>% |
702 | ! |
dplyr::select( |
703 | ! |
categorical_var_name, |
704 | ! |
Outliers = display_str, Missings = display_str_na, Total = total_in_cat |
705 |
) %>% |
|
706 | ! |
dplyr::mutate_all(as.character) %>% |
707 | ! |
tidyr::pivot_longer(-categorical_var_name) %>% |
708 | ! |
tidyr::pivot_wider(names_from = categorical_var, values_from = value) %>% |
709 | ! |
tibble::column_to_rownames("name") |
710 |
}, |
|
711 | ! |
env = list( |
712 | ! |
categorical_var = categorical_var, |
713 | ! |
categorical_var_name = as.name(categorical_var) |
714 |
) |
|
715 |
) |
|
716 |
) |
|
717 |
} else { |
|
718 | ! |
within(qenv, summary_table <- data.frame()) |
719 |
} |
|
720 | ||
721 |
# Generate decoratable object from data |
|
722 | ! |
qenv <- within(qenv, { |
723 | ! |
table <- rlistings::as_listing( |
724 | ! |
tibble::rownames_to_column(summary_table, var = " "), |
725 | ! |
key_cols = character(0L) |
726 |
) |
|
727 |
}) |
|
728 | ||
729 | ! |
if (length(categorical_var) > 0 && nrow(qenv[["ANL_OUTLIER"]]) > 0) { |
730 | ! |
shinyjs::show("order_by_outlier") |
731 |
} else { |
|
732 | ! |
shinyjs::hide("order_by_outlier") |
733 |
} |
|
734 | ||
735 | ! |
qenv |
736 |
}) |
|
737 | ||
738 |
# boxplot/violinplot # nolint commented_code |
|
739 | ! |
box_plot_q <- reactive({ |
740 | ! |
req(common_code_q()) |
741 | ! |
ANL <- common_code_q()[["ANL"]] |
742 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
743 | ||
744 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
745 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
746 | ||
747 |
# validation |
|
748 | ! |
teal::validate_has_data(ANL, 1) |
749 | ||
750 |
# boxplot |
|
751 | ! |
plot_call <- quote(ANL %>% ggplot()) |
752 | ||
753 | ! |
plot_call <- if (input$boxplot_alts == "Box plot") { |
754 | ! |
substitute(expr = plot_call + geom_boxplot(outlier.shape = NA), env = list(plot_call = plot_call)) |
755 | ! |
} else if (input$boxplot_alts == "Violin plot") { |
756 | ! |
substitute(expr = plot_call + geom_violin(), env = list(plot_call = plot_call)) |
757 |
} else { |
|
758 | ! |
NULL |
759 |
} |
|
760 | ||
761 | ! |
plot_call <- if (identical(categorical_var, character(0)) || is.null(categorical_var)) { |
762 | ! |
inner_call <- substitute( |
763 | ! |
expr = plot_call + |
764 | ! |
aes(x = "Entire dataset", y = outlier_var_name) + |
765 | ! |
scale_x_discrete(), |
766 | ! |
env = list(plot_call = plot_call, outlier_var_name = as.name(outlier_var)) |
767 |
) |
|
768 | ! |
if (nrow(ANL_OUTLIER) > 0) { |
769 | ! |
substitute( |
770 | ! |
expr = inner_call + geom_point( |
771 | ! |
data = ANL_OUTLIER, |
772 | ! |
aes(x = "Entire dataset", y = outlier_var_name, color = is_outlier_selected) |
773 |
), |
|
774 | ! |
env = list(inner_call = inner_call, outlier_var_name = as.name(outlier_var)) |
775 |
) |
|
776 |
} else { |
|
777 | ! |
inner_call |
778 |
} |
|
779 |
} else { |
|
780 | ! |
substitute( |
781 | ! |
expr = plot_call + |
782 | ! |
aes(y = outlier_var_name, x = reorder(categorical_var_name, order)) + |
783 | ! |
xlab(categorical_var) + |
784 | ! |
scale_x_discrete() + |
785 | ! |
geom_point( |
786 | ! |
data = ANL_OUTLIER, |
787 | ! |
aes(x = as.factor(categorical_var_name), y = outlier_var_name, color = is_outlier_selected) |
788 |
), |
|
789 | ! |
env = list( |
790 | ! |
plot_call = plot_call, |
791 | ! |
outlier_var_name = as.name(outlier_var), |
792 | ! |
categorical_var_name = as.name(categorical_var), |
793 | ! |
categorical_var = categorical_var |
794 |
) |
|
795 |
) |
|
796 |
} |
|
797 | ||
798 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
799 | ! |
labs = list(color = "Is outlier?"), |
800 | ! |
theme = list(legend.position = "top") |
801 |
) |
|
802 | ||
803 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
804 | ! |
user_plot = ggplot2_args[["Boxplot"]], |
805 | ! |
user_default = ggplot2_args$default, |
806 | ! |
module_plot = dev_ggplot2_args |
807 |
) |
|
808 | ||
809 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
810 | ! |
all_ggplot2_args, |
811 | ! |
ggtheme = input$ggtheme |
812 |
) |
|
813 | ||
814 | ! |
teal.code::eval_code( |
815 | ! |
common_code_q(), |
816 | ! |
substitute( |
817 | ! |
expr = box_plot <- plot_call + |
818 | ! |
scale_color_manual(values = c("TRUE" = "red", "FALSE" = "black")) + |
819 | ! |
labs + ggthemes + themes, |
820 | ! |
env = list( |
821 | ! |
plot_call = plot_call, |
822 | ! |
labs = parsed_ggplot2_args$labs, |
823 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
824 | ! |
themes = parsed_ggplot2_args$theme |
825 |
) |
|
826 |
) |
|
827 |
) |
|
828 |
}) |
|
829 | ||
830 |
# density plot |
|
831 | ! |
density_plot_q <- reactive({ |
832 | ! |
ANL <- common_code_q()[["ANL"]] |
833 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
834 | ||
835 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
836 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
837 | ||
838 |
# validation |
|
839 | ! |
teal::validate_has_data(ANL, 1) |
840 |
# plot |
|
841 | ! |
plot_call <- substitute( |
842 | ! |
expr = ANL %>% |
843 | ! |
ggplot(aes(x = outlier_var_name)) + |
844 | ! |
geom_density() + |
845 | ! |
geom_rug(data = ANL_OUTLIER, aes(x = outlier_var_name, color = is_outlier_selected)) + |
846 | ! |
scale_color_manual(values = c("TRUE" = "red", "FALSE" = "black")), |
847 | ! |
env = list(outlier_var_name = as.name(outlier_var)) |
848 |
) |
|
849 | ||
850 | ! |
plot_call <- if (identical(categorical_var, character(0)) || is.null(categorical_var)) { |
851 | ! |
substitute(expr = plot_call, env = list(plot_call = plot_call)) |
852 |
} else { |
|
853 | ! |
substitute( |
854 | ! |
expr = plot_call + facet_grid(~ reorder(categorical_var_name, order)), |
855 | ! |
env = list(plot_call = plot_call, categorical_var_name = as.name(categorical_var)) |
856 |
) |
|
857 |
} |
|
858 | ||
859 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
860 | ! |
labs = list(color = "Is outlier?"), |
861 | ! |
theme = list(legend.position = "top") |
862 |
) |
|
863 | ||
864 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
865 | ! |
user_plot = ggplot2_args[["Density Plot"]], |
866 | ! |
user_default = ggplot2_args$default, |
867 | ! |
module_plot = dev_ggplot2_args |
868 |
) |
|
869 | ||
870 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
871 | ! |
all_ggplot2_args, |
872 | ! |
ggtheme = input$ggtheme |
873 |
) |
|
874 | ||
875 | ! |
teal.code::eval_code( |
876 | ! |
common_code_q(), |
877 | ! |
substitute( |
878 | ! |
expr = density_plot <- plot_call + labs + ggthemes + themes, |
879 | ! |
env = list( |
880 | ! |
plot_call = plot_call, |
881 | ! |
labs = parsed_ggplot2_args$labs, |
882 | ! |
themes = parsed_ggplot2_args$theme, |
883 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
884 |
) |
|
885 |
) |
|
886 |
) |
|
887 |
}) |
|
888 | ||
889 |
# Cumulative distribution plot |
|
890 | ! |
cumulative_plot_q <- reactive({ |
891 | ! |
qenv <- common_code_q() |
892 | ||
893 | ! |
ANL <- qenv[["ANL"]] |
894 | ! |
ANL_OUTLIER <- qenv[["ANL_OUTLIER"]] |
895 | ||
896 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
897 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
898 | ||
899 |
# validation |
|
900 | ! |
teal::validate_has_data(ANL, 1) |
901 | ||
902 |
# plot |
|
903 | ! |
plot_call <- substitute( |
904 | ! |
expr = ANL %>% ggplot(aes(x = outlier_var_name)) + |
905 | ! |
stat_ecdf(), |
906 | ! |
env = list(outlier_var_name = as.name(outlier_var)) |
907 |
) |
|
908 | ! |
if (length(categorical_var) == 0) { |
909 | ! |
qenv <- teal.code::eval_code( |
910 | ! |
qenv, |
911 | ! |
substitute( |
912 | ! |
expr = { |
913 | ! |
ecdf_df <- ANL %>% |
914 | ! |
dplyr::mutate( |
915 | ! |
y = stats::ecdf(ANL[[outlier_var]])(ANL[[outlier_var]]) |
916 |
) |
|
917 | ||
918 | ! |
outlier_points <- dplyr::left_join( |
919 | ! |
ecdf_df, |
920 | ! |
ANL_OUTLIER, |
921 | ! |
by = dplyr::setdiff(names(ecdf_df), "y") |
922 |
) %>% |
|
923 | ! |
dplyr::filter(!is.na(is_outlier_selected)) |
924 |
}, |
|
925 | ! |
env = list(outlier_var = outlier_var) |
926 |
) |
|
927 |
) |
|
928 |
} else { |
|
929 | ! |
qenv <- teal.code::eval_code( |
930 | ! |
qenv, |
931 | ! |
substitute( |
932 | ! |
expr = { |
933 | ! |
all_categories <- lapply( |
934 | ! |
unique(ANL[[categorical_var]]), |
935 | ! |
function(x) { |
936 | ! |
ANL <- ANL %>% dplyr::filter(get(categorical_var) == x) |
937 | ! |
anl_outlier2 <- ANL_OUTLIER %>% dplyr::filter(get(categorical_var) == x) |
938 | ! |
ecdf_df <- ANL %>% |
939 | ! |
dplyr::mutate(y = stats::ecdf(ANL[[outlier_var]])(ANL[[outlier_var]])) |
940 | ||
941 | ! |
dplyr::left_join( |
942 | ! |
ecdf_df, |
943 | ! |
anl_outlier2, |
944 | ! |
by = dplyr::setdiff(names(ecdf_df), "y") |
945 |
) %>% |
|
946 | ! |
dplyr::filter(!is.na(is_outlier_selected)) |
947 |
} |
|
948 |
) |
|
949 | ! |
outlier_points <- do.call(rbind, all_categories) |
950 |
}, |
|
951 | ! |
env = list(categorical_var = categorical_var, outlier_var = outlier_var) |
952 |
) |
|
953 |
) |
|
954 | ! |
plot_call <- substitute( |
955 | ! |
expr = plot_call + facet_grid(~ reorder(categorical_var_name, order)), |
956 | ! |
env = list(plot_call = plot_call, categorical_var_name = as.name(categorical_var)) |
957 |
) |
|
958 |
} |
|
959 | ||
960 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
961 | ! |
labs = list(color = "Is outlier?"), |
962 | ! |
theme = list(legend.position = "top") |
963 |
) |
|
964 | ||
965 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
966 | ! |
user_plot = ggplot2_args[["Cumulative Distribution Plot"]], |
967 | ! |
user_default = ggplot2_args$default, |
968 | ! |
module_plot = dev_ggplot2_args |
969 |
) |
|
970 | ||
971 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
972 | ! |
all_ggplot2_args, |
973 | ! |
ggtheme = input$ggtheme |
974 |
) |
|
975 | ||
976 | ! |
teal.code::eval_code( |
977 | ! |
qenv, |
978 | ! |
substitute( |
979 | ! |
expr = cumulative_plot <- plot_call + |
980 | ! |
geom_point(data = outlier_points, aes(x = outlier_var_name, y = y, color = is_outlier_selected)) + |
981 | ! |
scale_color_manual(values = c("TRUE" = "red", "FALSE" = "black")) + |
982 | ! |
labs + ggthemes + themes, |
983 | ! |
env = list( |
984 | ! |
plot_call = plot_call, |
985 | ! |
outlier_var_name = as.name(outlier_var), |
986 | ! |
labs = parsed_ggplot2_args$labs, |
987 | ! |
themes = parsed_ggplot2_args$theme, |
988 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
989 |
) |
|
990 |
) |
|
991 |
) |
|
992 |
}) |
|
993 | ||
994 | ! |
current_tab_r <- reactive({ |
995 | ! |
switch(req(input$tabs), |
996 | ! |
"Boxplot" = "box_plot", |
997 | ! |
"Density Plot" = "density_plot", |
998 | ! |
"Cumulative Distribution Plot" = "cumulative_plot" |
999 |
) |
|
1000 |
}) |
|
1001 | ||
1002 | ! |
decorated_q <- mapply( |
1003 | ! |
function(obj_name, q) { |
1004 | ! |
srv_decorate_teal_data( |
1005 | ! |
id = sprintf("d_%s", obj_name), |
1006 | ! |
data = q, |
1007 | ! |
decorators = select_decorators(decorators, obj_name), |
1008 | ! |
expr = reactive({ |
1009 | ! |
substitute( |
1010 | ! |
expr = { |
1011 | ! |
columns_index <- union( |
1012 | ! |
setdiff(names(ANL_OUTLIER), c("is_outlier_selected", "order")), |
1013 | ! |
table_columns |
1014 |
) |
|
1015 | ! |
ANL_OUTLIER_EXTENDED[ANL_OUTLIER_EXTENDED$is_outlier_selected, columns_index] |
1016 | ! |
print(.plot) |
1017 |
}, |
|
1018 | ! |
env = list(table_columns = input$table_ui_columns, .plot = as.name(obj_name)) |
1019 |
) |
|
1020 |
}), |
|
1021 | ! |
expr_is_reactive = TRUE |
1022 |
) |
|
1023 |
}, |
|
1024 | ! |
stats::setNames(nm = c("box_plot", "density_plot", "cumulative_plot")), |
1025 | ! |
c(box_plot_q, density_plot_q, cumulative_plot_q) |
1026 |
) |
|
1027 | ||
1028 | ! |
decorated_final_q_no_table <- reactive(decorated_q[[req(current_tab_r())]]()) |
1029 | ||
1030 | ! |
decorated_final_q <- srv_decorate_teal_data( |
1031 | ! |
"d_table", |
1032 | ! |
data = decorated_final_q_no_table, |
1033 | ! |
decorators = select_decorators(decorators, "table"), |
1034 | ! |
expr = table |
1035 |
) |
|
1036 | ||
1037 | ! |
output$summary_table <- DT::renderDataTable( |
1038 | ! |
expr = { |
1039 | ! |
if (iv_r()$is_valid()) { |
1040 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
1041 | ! |
if (!is.null(categorical_var)) { |
1042 | ! |
DT::datatable( |
1043 | ! |
decorated_final_q()[["summary_table"]], |
1044 | ! |
options = list( |
1045 | ! |
dom = "t", |
1046 | ! |
autoWidth = TRUE, |
1047 | ! |
columnDefs = list(list(width = "200px", targets = "_all")) |
1048 |
) |
|
1049 |
) |
|
1050 |
} |
|
1051 |
} |
|
1052 |
} |
|
1053 |
) |
|
1054 | ||
1055 |
# slider text |
|
1056 | ! |
output$ui_outlier_help <- renderUI({ |
1057 | ! |
req(input$method) |
1058 | ! |
if (input$method == "IQR") { |
1059 | ! |
req(input$iqr_slider) |
1060 | ! |
tags$small( |
1061 | ! |
withMathJax( |
1062 | ! |
helpText( |
1063 | ! |
"Outlier data points (\\(x \\lt Q1 - ", input$iqr_slider, "\\times IQR\\) or \\( |
1064 | ! |
Q3 + ", input$iqr_slider, "\\times IQR \\lt x\\)) |
1065 | ! |
are displayed in red on the plot and can be visualized in the table below." |
1066 |
), |
|
1067 | ! |
if (input$split_outliers) { |
1068 | ! |
withMathJax(helpText("Note: Quantiles are calculated per group.")) |
1069 |
} |
|
1070 |
) |
|
1071 |
) |
|
1072 | ! |
} else if (input$method == "Z-score") { |
1073 | ! |
req(input$zscore_slider) |
1074 | ! |
tags$small( |
1075 | ! |
withMathJax( |
1076 | ! |
helpText( |
1077 | ! |
"Outlier data points (\\(Zscore(x) < -", input$zscore_slider, |
1078 | ! |
"\\) or \\(", input$zscore_slider, "< Zscore(x) \\)) |
1079 | ! |
are displayed in red on the plot and can be visualized in the table below." |
1080 |
), |
|
1081 | ! |
if (input$split_outliers) { |
1082 | ! |
withMathJax(helpText(" Note: Z-scores are calculated per group.")) |
1083 |
} |
|
1084 |
) |
|
1085 |
) |
|
1086 | ! |
} else if (input$method == "Percentile") { |
1087 | ! |
req(input$percentile_slider) |
1088 | ! |
tags$small( |
1089 | ! |
withMathJax( |
1090 | ! |
helpText( |
1091 | ! |
"Outlier/extreme data points (\\( Percentile(x) <", input$percentile_slider, |
1092 | ! |
"\\) or \\(", 1 - input$percentile_slider, " < Percentile(x) \\)) |
1093 | ! |
are displayed in red on the plot and can be visualized in the table below." |
1094 |
), |
|
1095 | ! |
if (input$split_outliers) { |
1096 | ! |
withMathJax(helpText("Note: Percentiles are calculated per group.")) |
1097 |
} |
|
1098 |
) |
|
1099 |
) |
|
1100 |
} |
|
1101 |
}) |
|
1102 | ||
1103 | ! |
box_plot_r <- reactive({ |
1104 | ! |
teal::validate_inputs(iv_r()) |
1105 | ! |
req(decorated_q$box_plot())[["box_plot"]] |
1106 |
}) |
|
1107 | ! |
density_plot_r <- reactive({ |
1108 | ! |
teal::validate_inputs(iv_r()) |
1109 | ! |
req(decorated_q$density_plot())[["density_plot"]] |
1110 |
}) |
|
1111 | ! |
cumulative_plot_r <- reactive({ |
1112 | ! |
teal::validate_inputs(iv_r()) |
1113 | ! |
req(decorated_q$cumulative_plot())[["cumulative_plot"]] |
1114 |
}) |
|
1115 | ||
1116 | ! |
box_pws <- teal.widgets::plot_with_settings_srv( |
1117 | ! |
id = "box_plot", |
1118 | ! |
plot_r = box_plot_r, |
1119 | ! |
height = plot_height, |
1120 | ! |
width = plot_width, |
1121 | ! |
brushing = TRUE |
1122 |
) |
|
1123 | ||
1124 | ! |
density_pws <- teal.widgets::plot_with_settings_srv( |
1125 | ! |
id = "density_plot", |
1126 | ! |
plot_r = density_plot_r, |
1127 | ! |
height = plot_height, |
1128 | ! |
width = plot_width, |
1129 | ! |
brushing = TRUE |
1130 |
) |
|
1131 | ||
1132 | ! |
cum_density_pws <- teal.widgets::plot_with_settings_srv( |
1133 | ! |
id = "cum_density_plot", |
1134 | ! |
plot_r = cumulative_plot_r, |
1135 | ! |
height = plot_height, |
1136 | ! |
width = plot_width, |
1137 | ! |
brushing = TRUE |
1138 |
) |
|
1139 | ||
1140 | ! |
choices <- reactive(teal.transform::variable_choices(data()[[dataname_first]])) |
1141 | ||
1142 | ! |
observeEvent(common_code_q(), { |
1143 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
1144 | ! |
teal.widgets::updateOptionalSelectInput( |
1145 | ! |
session, |
1146 | ! |
inputId = "table_ui_columns", |
1147 | ! |
choices = dplyr::setdiff(choices(), names(ANL_OUTLIER)), |
1148 | ! |
selected = restoreInput(ns("table_ui_columns"), isolate(input$table_ui_columns)) |
1149 |
) |
|
1150 |
}) |
|
1151 | ||
1152 | ! |
output$table_ui <- DT::renderDataTable( |
1153 | ! |
expr = { |
1154 | ! |
tab <- input$tabs |
1155 | ! |
req(tab) # tab is NULL upon app launch, hence will crash without this statement |
1156 | ! |
req(iv_r()$is_valid()) # Same validation as output$table_ui_wrap |
1157 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
1158 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
1159 | ||
1160 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
1161 | ! |
ANL_OUTLIER_EXTENDED <- common_code_q()[["ANL_OUTLIER_EXTENDED"]] |
1162 | ! |
ANL <- common_code_q()[["ANL"]] |
1163 | ||
1164 | ! |
plot_brush <- switch(current_tab_r(), |
1165 | ! |
box_plot = { |
1166 | ! |
box_plot_r() |
1167 | ! |
box_pws$brush() |
1168 |
}, |
|
1169 | ! |
density_plot = { |
1170 | ! |
density_plot_r() |
1171 | ! |
density_pws$brush() |
1172 |
}, |
|
1173 | ! |
cumulative_plot = { |
1174 | ! |
cumulative_plot_r() |
1175 | ! |
cum_density_pws$brush() |
1176 |
} |
|
1177 |
) |
|
1178 | ||
1179 |
# removing unused column ASAP |
|
1180 | ! |
ANL_OUTLIER$order <- ANL$order <- NULL |
1181 | ||
1182 | ! |
display_table <- if (!is.null(plot_brush)) { |
1183 | ! |
if (length(categorical_var) > 0) { |
1184 |
# due to reordering, the x-axis label may be changed to something like "reorder(categorical_var, order)" |
|
1185 | ! |
if (tab == "Boxplot") { |
1186 | ! |
plot_brush$mapping$x <- categorical_var |
1187 |
} else { |
|
1188 |
# the other plots use facetting |
|
1189 |
# so it is panelvar1 that gets relabelled to "reorder(categorical_var, order)" |
|
1190 | ! |
plot_brush$mapping$panelvar1 <- categorical_var |
1191 |
} |
|
1192 |
} else { |
|
1193 | ! |
if (tab == "Boxplot") { |
1194 |
# in boxplot with no categorical variable, there is no column in ANL that would correspond to x-axis |
|
1195 |
# so a column needs to be inserted with the value "Entire dataset" because that's the label used in plot |
|
1196 | ! |
ANL[[plot_brush$mapping$x]] <- "Entire dataset" |
1197 |
} |
|
1198 |
} |
|
1199 | ||
1200 |
# in density and cumulative plots, ANL does not have a column corresponding to y-axis. |
|
1201 |
# so they need to be computed and attached to ANL |
|
1202 | ! |
if (tab == "Density Plot") { |
1203 | ! |
plot_brush$mapping$y <- "density" |
1204 | ! |
ANL$density <- plot_brush$ymin |
1205 |
# either ymin or ymax will work |
|
1206 | ! |
} else if (tab == "Cumulative Distribution Plot") { |
1207 | ! |
plot_brush$mapping$y <- "cdf" |
1208 | ! |
if (length(categorical_var) > 0) { |
1209 | ! |
ANL <- ANL %>% |
1210 | ! |
dplyr::group_by(!!as.name(plot_brush$mapping$panelvar1)) %>% |
1211 | ! |
dplyr::mutate(cdf = stats::ecdf(!!as.name(outlier_var))(!!as.name(outlier_var))) |
1212 |
} else { |
|
1213 | ! |
ANL$cdf <- stats::ecdf(ANL[[outlier_var]])(ANL[[outlier_var]]) |
1214 |
} |
|
1215 |
} |
|
1216 | ||
1217 | ! |
brushed_rows <- brushedPoints(ANL, plot_brush) |
1218 | ! |
if (nrow(brushed_rows) > 0) { |
1219 |
# now we need to remove extra column from ANL so that it will have the same columns as ANL_OUTLIER |
|
1220 |
# so that dplyr::intersect will work |
|
1221 | ! |
if (tab == "Density Plot") { |
1222 | ! |
brushed_rows$density <- NULL |
1223 | ! |
} else if (tab == "Cumulative Distribution Plot") { |
1224 | ! |
brushed_rows$cdf <- NULL |
1225 | ! |
} else if (tab == "Boxplot" && length(categorical_var) == 0) { |
1226 | ! |
brushed_rows[[plot_brush$mapping$x]] <- NULL |
1227 |
} |
|
1228 |
# is_outlier_selected is part of ANL_OUTLIER so needed here |
|
1229 | ! |
brushed_rows$is_outlier_selected <- TRUE |
1230 | ! |
dplyr::intersect(ANL_OUTLIER, brushed_rows) |
1231 |
} else { |
|
1232 | ! |
ANL_OUTLIER[0, ] |
1233 |
} |
|
1234 |
} else { |
|
1235 | ! |
ANL_OUTLIER[ANL_OUTLIER$is_outlier_selected, ] |
1236 |
} |
|
1237 | ||
1238 | ! |
display_table$is_outlier_selected <- NULL |
1239 | ||
1240 |
# Extend the brushed ANL_OUTLIER with additional columns |
|
1241 | ! |
dplyr::left_join( |
1242 | ! |
display_table, |
1243 | ! |
dplyr::select(ANL_OUTLIER_EXTENDED, -"is_outlier_selected"), |
1244 | ! |
by = names(display_table) |
1245 |
) %>% |
|
1246 | ! |
dplyr::select(union(names(display_table), input$table_ui_columns)) |
1247 |
}, |
|
1248 | ! |
options = list( |
1249 | ! |
searching = FALSE, language = list( |
1250 | ! |
zeroRecords = "The brushed area does not contain outlier observations for the currently defined threshold" |
1251 |
), |
|
1252 | ! |
pageLength = input$table_ui_rows |
1253 |
) |
|
1254 |
) |
|
1255 | ||
1256 | ! |
output$total_outliers <- renderUI({ |
1257 | ! |
req(iv_r()$is_valid()) |
1258 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
1259 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
1260 | ! |
teal::validate_has_data(ANL, 1) |
1261 | ! |
ANL_OUTLIER_SELECTED <- ANL_OUTLIER[ANL_OUTLIER$is_outlier_selected, ] |
1262 | ! |
tags$h5( |
1263 | ! |
sprintf( |
1264 | ! |
"%s %d / %d [%.02f%%]", |
1265 | ! |
"Total number of outlier(s):", |
1266 | ! |
nrow(ANL_OUTLIER_SELECTED), |
1267 | ! |
nrow(ANL), |
1268 | ! |
100 * nrow(ANL_OUTLIER_SELECTED) / nrow(ANL) |
1269 |
) |
|
1270 |
) |
|
1271 |
}) |
|
1272 | ||
1273 | ! |
output$total_missing <- renderUI({ |
1274 | ! |
if (n_outlier_missing() > 0) { |
1275 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
1276 | ! |
helpText( |
1277 | ! |
sprintf( |
1278 | ! |
"%s %d / %d [%.02f%%]", |
1279 | ! |
"Total number of row(s) with missing values:", |
1280 | ! |
n_outlier_missing(), |
1281 | ! |
nrow(ANL), |
1282 | ! |
100 * (n_outlier_missing()) / nrow(ANL) |
1283 |
) |
|
1284 |
) |
|
1285 |
} |
|
1286 |
}) |
|
1287 | ||
1288 | ! |
output$table_ui_wrap <- renderUI({ |
1289 | ! |
req(iv_r()$is_valid()) |
1290 | ! |
tagList( |
1291 | ! |
teal.widgets::optionalSelectInput( |
1292 | ! |
inputId = ns("table_ui_columns"), |
1293 | ! |
label = "Choose additional columns", |
1294 | ! |
choices = NULL, |
1295 | ! |
selected = NULL, |
1296 | ! |
multiple = TRUE |
1297 |
), |
|
1298 | ! |
tags$h4("Outlier Table"), |
1299 | ! |
teal.widgets::get_dt_rows(ns("table_ui"), ns("table_ui_rows")) |
1300 |
) |
|
1301 |
}) |
|
1302 | ||
1303 |
# Render R code. |
|
1304 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_final_q()))) |
1305 | ||
1306 | ! |
teal.widgets::verbatim_popup_srv( |
1307 | ! |
id = "rcode", |
1308 | ! |
verbatim_content = source_code_r, |
1309 | ! |
title = "Show R Code for Outlier" |
1310 |
) |
|
1311 | ||
1312 |
### REPORTER |
|
1313 | ! |
if (with_reporter) { |
1314 | ! |
card_fun <- function(comment, label) { |
1315 | ! |
tab_type <- input$tabs |
1316 | ! |
card <- teal::report_card_template( |
1317 | ! |
title = paste0("Outliers - ", tab_type), |
1318 | ! |
label = label, |
1319 | ! |
with_filter = with_filter, |
1320 | ! |
filter_panel_api = filter_panel_api |
1321 |
) |
|
1322 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
1323 | ! |
if (length(categorical_var) > 0) { |
1324 | ! |
summary_table <- decorated_final_q()[["table"]] |
1325 | ! |
card$append_text("Summary Table", "header3") |
1326 | ! |
card$append_table(summary_table) |
1327 |
} |
|
1328 | ! |
card$append_text("Plot", "header3") |
1329 | ! |
if (tab_type == "Boxplot") { |
1330 | ! |
card$append_plot(box_plot_r(), dim = box_pws$dim()) |
1331 | ! |
} else if (tab_type == "Density Plot") { |
1332 | ! |
card$append_plot(density_plot_r(), dim = density_pws$dim()) |
1333 | ! |
} else if (tab_type == "Cumulative Distribution Plot") { |
1334 | ! |
card$append_plot(cumulative_plot_r(), dim = cum_density_pws$dim()) |
1335 |
} |
|
1336 | ! |
if (!comment == "") { |
1337 | ! |
card$append_text("Comment", "header3") |
1338 | ! |
card$append_text(comment) |
1339 |
} |
|
1340 | ! |
card$append_src(source_code_r()) |
1341 | ! |
card |
1342 |
} |
|
1343 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
1344 |
} |
|
1345 |
### |
|
1346 |
}) |
|
1347 |
} |
1 |
#' `teal` module: Principal component analysis |
|
2 |
#' |
|
3 |
#' Module conducts principal component analysis (PCA) on a given dataset and offers different |
|
4 |
#' ways of visualizing the outcomes, including elbow plot, circle plot, biplot, and eigenvector plot. |
|
5 |
#' Additionally, it enables dynamic customization of plot aesthetics, such as opacity, size, and |
|
6 |
#' font size, through UI inputs. |
|
7 |
#' |
|
8 |
#' @inheritParams teal::module |
|
9 |
#' @inheritParams shared_params |
|
10 |
#' @param dat (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
11 |
#' specifying columns used to compute PCA. |
|
12 |
#' @param font_size (`numeric`) optional, specifies font size. |
|
13 |
#' It controls the font size for plot titles, axis labels, and legends. |
|
14 |
#' - If vector of `length == 1` then the font sizes will have a fixed size. |
|
15 |
#' - while vector of `value`, `min`, and `max` allows dynamic adjustment. |
|
16 |
#' @param ggplot2_args `r roxygen_ggplot2_args_param("Elbow plot", "Circle plot", "Biplot", "Eigenvector plot")` |
|
17 |
#' |
|
18 |
#' @inherit shared_params return |
|
19 |
#' |
|
20 |
#' @section Decorating Module: |
|
21 |
#' |
|
22 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
23 |
#' - `elbow_plot` (`ggplot2`) |
|
24 |
#' - `circle_plot` (`ggplot2`) |
|
25 |
#' - `biplot` (`ggplot2`) |
|
26 |
#' - `eigenvector_plot` (`ggplot2`) |
|
27 |
#' |
|
28 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
29 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
30 |
#' See code snippet below: |
|
31 |
#' |
|
32 |
#' ``` |
|
33 |
#' tm_a_pca( |
|
34 |
#' ..., # arguments for module |
|
35 |
#' decorators = list( |
|
36 |
#' elbow_plot = teal_transform_module(...), # applied to the `elbow_plot` output |
|
37 |
#' circle_plot = teal_transform_module(...), # applied to the `circle_plot` output |
|
38 |
#' biplot = teal_transform_module(...), # applied to the `biplot` output |
|
39 |
#' eigenvector_plot = teal_transform_module(...) # applied to the `eigenvector_plot` output |
|
40 |
#' ) |
|
41 |
#' ) |
|
42 |
#' ``` |
|
43 |
#' |
|
44 |
#' For additional details and examples of decorators, refer to the vignette |
|
45 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
46 |
#' |
|
47 |
#' @examplesShinylive |
|
48 |
#' library(teal.modules.general) |
|
49 |
#' interactive <- function() TRUE |
|
50 |
#' {{ next_example }} |
|
51 |
#' @examples |
|
52 |
#' |
|
53 |
#' # general data example |
|
54 |
#' data <- teal_data() |
|
55 |
#' data <- within(data, { |
|
56 |
#' require(nestcolor) |
|
57 |
#' USArrests <- USArrests |
|
58 |
#' }) |
|
59 |
#' |
|
60 |
#' app <- init( |
|
61 |
#' data = data, |
|
62 |
#' modules = modules( |
|
63 |
#' tm_a_pca( |
|
64 |
#' "PCA", |
|
65 |
#' dat = data_extract_spec( |
|
66 |
#' dataname = "USArrests", |
|
67 |
#' select = select_spec( |
|
68 |
#' choices = variable_choices( |
|
69 |
#' data = data[["USArrests"]], c("Murder", "Assault", "UrbanPop", "Rape") |
|
70 |
#' ), |
|
71 |
#' selected = c("Murder", "Assault"), |
|
72 |
#' multiple = TRUE |
|
73 |
#' ), |
|
74 |
#' filter = NULL |
|
75 |
#' ) |
|
76 |
#' ) |
|
77 |
#' ) |
|
78 |
#' ) |
|
79 |
#' if (interactive()) { |
|
80 |
#' shinyApp(app$ui, app$server) |
|
81 |
#' } |
|
82 |
#' |
|
83 |
#' @examplesShinylive |
|
84 |
#' library(teal.modules.general) |
|
85 |
#' interactive <- function() TRUE |
|
86 |
#' {{ next_example }} |
|
87 |
#' @examples |
|
88 |
#' |
|
89 |
#' # CDISC data example |
|
90 |
#' data <- teal_data() |
|
91 |
#' data <- within(data, { |
|
92 |
#' require(nestcolor) |
|
93 |
#' ADSL <- teal.data::rADSL |
|
94 |
#' }) |
|
95 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
96 |
#' |
|
97 |
#' app <- init( |
|
98 |
#' data = data, |
|
99 |
#' modules = modules( |
|
100 |
#' tm_a_pca( |
|
101 |
#' "PCA", |
|
102 |
#' dat = data_extract_spec( |
|
103 |
#' dataname = "ADSL", |
|
104 |
#' select = select_spec( |
|
105 |
#' choices = variable_choices( |
|
106 |
#' data = data[["ADSL"]], c("BMRKR1", "AGE", "EOSDY") |
|
107 |
#' ), |
|
108 |
#' selected = c("BMRKR1", "AGE"), |
|
109 |
#' multiple = TRUE |
|
110 |
#' ), |
|
111 |
#' filter = NULL |
|
112 |
#' ) |
|
113 |
#' ) |
|
114 |
#' ) |
|
115 |
#' ) |
|
116 |
#' if (interactive()) { |
|
117 |
#' shinyApp(app$ui, app$server) |
|
118 |
#' } |
|
119 |
#' |
|
120 |
#' @export |
|
121 |
#' |
|
122 |
tm_a_pca <- function(label = "Principal Component Analysis", |
|
123 |
dat, |
|
124 |
plot_height = c(600, 200, 2000), |
|
125 |
plot_width = NULL, |
|
126 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
127 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
128 |
rotate_xaxis_labels = FALSE, |
|
129 |
font_size = c(12, 8, 20), |
|
130 |
alpha = c(1, 0, 1), |
|
131 |
size = c(2, 1, 8), |
|
132 |
pre_output = NULL, |
|
133 |
post_output = NULL, |
|
134 |
transformators = list(), |
|
135 |
decorators = list()) { |
|
136 | ! |
message("Initializing tm_a_pca") |
137 | ||
138 |
# Normalize the parameters |
|
139 | ! |
if (inherits(dat, "data_extract_spec")) dat <- list(dat) |
140 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
141 | ||
142 |
# Start of assertions |
|
143 | ! |
checkmate::assert_string(label) |
144 | ! |
checkmate::assert_list(dat, types = "data_extract_spec") |
145 | ||
146 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
147 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
148 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
149 | ! |
checkmate::assert_numeric( |
150 | ! |
plot_width[1], |
151 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
152 |
) |
|
153 | ||
154 | ! |
ggtheme <- match.arg(ggtheme) |
155 | ||
156 | ! |
plot_choices <- c("Elbow plot", "Circle plot", "Biplot", "Eigenvector plot") |
157 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
158 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
159 | ||
160 | ! |
checkmate::assert_flag(rotate_xaxis_labels) |
161 | ||
162 | ! |
if (length(font_size) == 1) { |
163 | ! |
checkmate::assert_numeric(font_size, any.missing = FALSE, finite = TRUE, lower = 8, upper = 20) |
164 |
} else { |
|
165 | ! |
checkmate::assert_numeric(font_size, len = 3, any.missing = FALSE, finite = TRUE, lower = 8, upper = 20) |
166 | ! |
checkmate::assert_numeric(font_size[1], lower = font_size[2], upper = font_size[3], .var.name = "font_size") |
167 |
} |
|
168 | ||
169 | ! |
if (length(alpha) == 1) { |
170 | ! |
checkmate::assert_numeric(alpha, any.missing = FALSE, finite = TRUE, lower = 0, upper = 1) |
171 |
} else { |
|
172 | ! |
checkmate::assert_numeric(alpha, len = 3, any.missing = FALSE, finite = TRUE, lower = 0, upper = 1) |
173 | ! |
checkmate::assert_numeric(alpha[1], lower = alpha[2], upper = alpha[3], .var.name = "alpha") |
174 |
} |
|
175 | ||
176 | ! |
if (length(size) == 1) { |
177 | ! |
checkmate::assert_numeric(size, any.missing = FALSE, finite = TRUE, lower = 1, upper = 8) |
178 |
} else { |
|
179 | ! |
checkmate::assert_numeric(size, len = 3, any.missing = FALSE, finite = TRUE, lower = 1, upper = 8) |
180 | ! |
checkmate::assert_numeric(size[1], lower = size[2], upper = size[3], .var.name = "size") |
181 |
} |
|
182 | ||
183 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
184 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
185 | ||
186 | ! |
available_decorators <- c("elbow_plot", "circle_plot", "biplot", "eigenvector_plot") |
187 | ! |
assert_decorators(decorators, available_decorators) |
188 | ||
189 |
# Make UI args |
|
190 | ! |
args <- as.list(environment()) |
191 | ||
192 | ! |
data_extract_list <- list(dat = dat) |
193 | ||
194 | ! |
ans <- module( |
195 | ! |
label = label, |
196 | ! |
server = srv_a_pca, |
197 | ! |
ui = ui_a_pca, |
198 | ! |
ui_args = args, |
199 | ! |
server_args = c( |
200 | ! |
data_extract_list, |
201 | ! |
list( |
202 | ! |
plot_height = plot_height, |
203 | ! |
plot_width = plot_width, |
204 | ! |
ggplot2_args = ggplot2_args, |
205 | ! |
decorators = decorators |
206 |
) |
|
207 |
), |
|
208 | ! |
transformators = transformators, |
209 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
210 |
) |
|
211 | ! |
attr(ans, "teal_bookmarkable") <- FALSE |
212 | ! |
ans |
213 |
} |
|
214 | ||
215 |
# UI function for the PCA module |
|
216 |
ui_a_pca <- function(id, ...) { |
|
217 | ! |
ns <- NS(id) |
218 | ! |
args <- list(...) |
219 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$dat) |
220 | ||
221 | ! |
color_selector <- args$dat |
222 | ! |
for (i in seq_along(color_selector)) { |
223 | ! |
color_selector[[i]]$select$multiple <- FALSE |
224 | ! |
color_selector[[i]]$select$always_selected <- NULL |
225 | ! |
color_selector[[i]]$select$selected <- NULL |
226 |
} |
|
227 | ||
228 | ! |
tagList( |
229 | ! |
include_css_files("custom"), |
230 | ! |
teal.widgets::standard_layout( |
231 | ! |
output = teal.widgets::white_small_well( |
232 | ! |
uiOutput(ns("all_plots")) |
233 |
), |
|
234 | ! |
encoding = tags$div( |
235 |
### Reporter |
|
236 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
237 |
### |
|
238 | ! |
tags$label("Encodings", class = "text-primary"), |
239 | ! |
teal.transform::datanames_input(args["dat"]), |
240 | ! |
teal.transform::data_extract_ui( |
241 | ! |
id = ns("dat"), |
242 | ! |
label = "Data selection", |
243 | ! |
data_extract_spec = args$dat, |
244 | ! |
is_single_dataset = is_single_dataset_value |
245 |
), |
|
246 | ! |
teal.widgets::panel_group( |
247 | ! |
teal.widgets::panel_item( |
248 | ! |
title = "Display", |
249 | ! |
collapsed = FALSE, |
250 | ! |
checkboxGroupInput( |
251 | ! |
ns("tables_display"), |
252 | ! |
"Tables display", |
253 | ! |
choices = c("PC importance" = "importance", "Eigenvectors" = "eigenvector"), |
254 | ! |
selected = c("importance", "eigenvector") |
255 |
), |
|
256 | ! |
radioButtons( |
257 | ! |
ns("plot_type"), |
258 | ! |
label = "Plot type", |
259 | ! |
choices = args$plot_choices, |
260 | ! |
selected = args$plot_choices[1] |
261 |
), |
|
262 | ! |
conditionalPanel( |
263 | ! |
condition = sprintf("input['%s'] == 'Elbow plot'", ns("plot_type")), |
264 | ! |
ui_decorate_teal_data( |
265 | ! |
ns("d_elbow_plot"), |
266 | ! |
decorators = select_decorators(args$decorators, "elbow_plot") |
267 |
) |
|
268 |
), |
|
269 | ! |
conditionalPanel( |
270 | ! |
condition = sprintf("input['%s'] == 'Circle plot'", ns("plot_type")), |
271 | ! |
ui_decorate_teal_data( |
272 | ! |
ns("d_circle_plot"), |
273 | ! |
decorators = select_decorators(args$decorators, "circle_plot") |
274 |
) |
|
275 |
), |
|
276 | ! |
conditionalPanel( |
277 | ! |
condition = sprintf("input['%s'] == 'Biplot'", ns("plot_type")), |
278 | ! |
ui_decorate_teal_data( |
279 | ! |
ns("d_biplot"), |
280 | ! |
decorators = select_decorators(args$decorators, "biplot") |
281 |
) |
|
282 |
), |
|
283 | ! |
conditionalPanel( |
284 | ! |
condition = sprintf("input['%s'] == 'Eigenvector plot'", ns("plot_type")), |
285 | ! |
ui_decorate_teal_data( |
286 | ! |
ns("d_eigenvector_plot"), |
287 | ! |
decorators = select_decorators(args$decorators, "eigenvector_plot") |
288 |
) |
|
289 |
) |
|
290 |
), |
|
291 | ! |
teal.widgets::panel_item( |
292 | ! |
title = "Pre-processing", |
293 | ! |
radioButtons( |
294 | ! |
ns("standardization"), "Standardization", |
295 | ! |
choices = c("None" = "none", "Center" = "center", "Center & Scale" = "center_scale"), |
296 | ! |
selected = "center_scale" |
297 |
), |
|
298 | ! |
radioButtons( |
299 | ! |
ns("na_action"), "NA action", |
300 | ! |
choices = c("None" = "none", "Drop" = "drop"), |
301 | ! |
selected = "none" |
302 |
) |
|
303 |
), |
|
304 | ! |
teal.widgets::panel_item( |
305 | ! |
title = "Selected plot specific settings", |
306 | ! |
collapsed = FALSE, |
307 | ! |
uiOutput(ns("plot_settings")), |
308 | ! |
conditionalPanel( |
309 | ! |
condition = sprintf("input['%s'] == 'Biplot'", ns("plot_type")), |
310 | ! |
list( |
311 | ! |
teal.transform::data_extract_ui( |
312 | ! |
id = ns("response"), |
313 | ! |
label = "Color by", |
314 | ! |
data_extract_spec = color_selector, |
315 | ! |
is_single_dataset = is_single_dataset_value |
316 |
), |
|
317 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("alpha"), "Opacity:", args$alpha, ticks = FALSE), |
318 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("size"), "Points size:", args$size, ticks = FALSE) |
319 |
) |
|
320 |
) |
|
321 |
), |
|
322 | ! |
teal.widgets::panel_item( |
323 | ! |
title = "Plot settings", |
324 | ! |
collapsed = TRUE, |
325 | ! |
conditionalPanel( |
326 | ! |
condition = sprintf( |
327 | ! |
"input['%s'] == 'Elbow plot' || input['%s'] == 'Eigenvector plot'", |
328 | ! |
ns("plot_type"), |
329 | ! |
ns("plot_type") |
330 |
), |
|
331 | ! |
list(checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = args$rotate_xaxis_labels)) |
332 |
), |
|
333 | ! |
selectInput( |
334 | ! |
inputId = ns("ggtheme"), |
335 | ! |
label = "Theme (by ggplot):", |
336 | ! |
choices = ggplot_themes, |
337 | ! |
selected = args$ggtheme, |
338 | ! |
multiple = FALSE |
339 |
), |
|
340 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("font_size"), "Font Size", args$font_size, ticks = FALSE) |
341 |
) |
|
342 |
) |
|
343 |
), |
|
344 | ! |
forms = tagList( |
345 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
346 |
), |
|
347 | ! |
pre_output = args$pre_output, |
348 | ! |
post_output = args$post_output |
349 |
) |
|
350 |
) |
|
351 |
} |
|
352 | ||
353 |
# Server function for the PCA module |
|
354 |
srv_a_pca <- function(id, data, reporter, filter_panel_api, dat, plot_height, plot_width, ggplot2_args, decorators) { |
|
355 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
356 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
357 | ! |
checkmate::assert_class(data, "reactive") |
358 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
359 | ! |
moduleServer(id, function(input, output, session) { |
360 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
361 | ||
362 | ! |
response <- dat |
363 | ||
364 | ! |
for (i in seq_along(response)) { |
365 | ! |
response[[i]]$select$multiple <- FALSE |
366 | ! |
response[[i]]$select$always_selected <- NULL |
367 | ! |
response[[i]]$select$selected <- NULL |
368 | ! |
all_cols <- teal.data::col_labels(isolate(data())[[response[[i]]$dataname]]) |
369 | ! |
ignore_cols <- unlist(teal.data::join_keys(isolate(data()))[[response[[i]]$dataname]]) |
370 | ! |
color_cols <- all_cols[!names(all_cols) %in% ignore_cols] |
371 | ! |
response[[i]]$select$choices <- teal.transform::choices_labeled(names(color_cols), color_cols) |
372 |
} |
|
373 | ||
374 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
375 | ! |
data_extract = list(dat = dat, response = response), |
376 | ! |
datasets = data, |
377 | ! |
select_validation_rule = list( |
378 | ! |
dat = ~ if (length(.) < 2L) "Please select more than 1 variable to perform PCA.", |
379 | ! |
response = shinyvalidate::compose_rules( |
380 | ! |
shinyvalidate::sv_optional(), |
381 | ! |
~ if (isTRUE(is.element(., selector_list()$dat()$select))) { |
382 | ! |
"Response must not have been used for PCA." |
383 |
} |
|
384 |
) |
|
385 |
) |
|
386 |
) |
|
387 | ||
388 | ! |
iv_r <- reactive({ |
389 | ! |
iv <- shinyvalidate::InputValidator$new() |
390 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
391 |
}) |
|
392 | ||
393 | ! |
iv_extra <- shinyvalidate::InputValidator$new() |
394 | ! |
iv_extra$add_rule("x_axis", function(value) { |
395 | ! |
if (isTRUE(input$plot_type %in% c("Circle plot", "Biplot"))) { |
396 | ! |
if (!shinyvalidate::input_provided(value)) { |
397 | ! |
"Need X axis" |
398 |
} |
|
399 |
} |
|
400 |
}) |
|
401 | ! |
iv_extra$add_rule("y_axis", function(value) { |
402 | ! |
if (isTRUE(input$plot_type %in% c("Circle plot", "Biplot"))) { |
403 | ! |
if (!shinyvalidate::input_provided(value)) { |
404 | ! |
"Need Y axis" |
405 |
} |
|
406 |
} |
|
407 |
}) |
|
408 | ! |
rule_dupl <- function(...) { |
409 | ! |
if (isTRUE(input$plot_type %in% c("Circle plot", "Biplot"))) { |
410 | ! |
if (isTRUE(input$x_axis == input$y_axis)) { |
411 | ! |
"Please choose different X and Y axes." |
412 |
} |
|
413 |
} |
|
414 |
} |
|
415 | ! |
iv_extra$add_rule("x_axis", rule_dupl) |
416 | ! |
iv_extra$add_rule("y_axis", rule_dupl) |
417 | ! |
iv_extra$add_rule("variables", function(value) { |
418 | ! |
if (identical(input$plot_type, "Circle plot")) { |
419 | ! |
if (!shinyvalidate::input_provided(value)) { |
420 | ! |
"Need Original Coordinates" |
421 |
} |
|
422 |
} |
|
423 |
}) |
|
424 | ! |
iv_extra$add_rule("pc", function(value) { |
425 | ! |
if (identical(input$plot_type, "Eigenvector plot")) { |
426 | ! |
if (!shinyvalidate::input_provided(value)) { |
427 | ! |
"Need PC" |
428 |
} |
|
429 |
} |
|
430 |
}) |
|
431 | ! |
iv_extra$enable() |
432 | ||
433 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
434 | ! |
selector_list = selector_list, |
435 | ! |
datasets = data |
436 |
) |
|
437 | ||
438 | ! |
anl_merged_q <- reactive({ |
439 | ! |
req(anl_merged_input()) |
440 | ! |
data() %>% |
441 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
442 |
}) |
|
443 | ||
444 | ! |
merged <- list( |
445 | ! |
anl_input_r = anl_merged_input, |
446 | ! |
anl_q_r = anl_merged_q |
447 |
) |
|
448 | ||
449 | ! |
validation <- reactive({ |
450 | ! |
req(merged$anl_q_r()) |
451 |
# inputs |
|
452 | ! |
keep_cols <- as.character(merged$anl_input_r()$columns_source$dat) |
453 | ! |
na_action <- input$na_action |
454 | ! |
standardization <- input$standardization |
455 | ! |
center <- standardization %in% c("center", "center_scale") |
456 | ! |
scale <- standardization == "center_scale" |
457 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
458 | ||
459 | ! |
teal::validate_has_data(ANL, 10) |
460 | ! |
validate(need( |
461 | ! |
na_action != "none" | !anyNA(ANL[keep_cols]), |
462 | ! |
paste( |
463 | ! |
"There are NAs in the dataset. Please deal with them in preprocessing", |
464 | ! |
"or select \"Drop\" in the NA actions inside the encodings panel (left)." |
465 |
) |
|
466 |
)) |
|
467 | ! |
if (scale) { |
468 | ! |
not_single <- vapply(ANL[keep_cols], function(column) length(unique(column)) != 1, FUN.VALUE = logical(1)) |
469 | ||
470 | ! |
msg <- paste0( |
471 | ! |
"You have selected `Center & Scale` under `Standardization` in the `Pre-processing` panel, ", |
472 | ! |
"but one or more of your columns has/have a variance value of zero, indicating all values are identical" |
473 |
) |
|
474 | ! |
validate(need(all(not_single), msg)) |
475 |
} |
|
476 |
}) |
|
477 | ||
478 |
# computation ---- |
|
479 | ! |
computation <- reactive({ |
480 | ! |
validation() |
481 | ||
482 |
# inputs |
|
483 | ! |
keep_cols <- as.character(merged$anl_input_r()$columns_source$dat) |
484 | ! |
na_action <- input$na_action |
485 | ! |
standardization <- input$standardization |
486 | ! |
center <- standardization %in% c("center", "center_scale") |
487 | ! |
scale <- standardization == "center_scale" |
488 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
489 | ||
490 | ! |
qenv <- teal.code::eval_code( |
491 | ! |
merged$anl_q_r(), |
492 | ! |
substitute( |
493 | ! |
expr = keep_columns <- keep_cols, |
494 | ! |
env = list(keep_cols = keep_cols) |
495 |
) |
|
496 |
) |
|
497 | ||
498 | ! |
if (na_action == "drop") { |
499 | ! |
qenv <- teal.code::eval_code( |
500 | ! |
qenv, |
501 | ! |
quote(ANL <- tidyr::drop_na(ANL, keep_columns)) |
502 |
) |
|
503 |
} |
|
504 | ||
505 | ! |
qenv <- teal.code::eval_code( |
506 | ! |
qenv, |
507 | ! |
substitute( |
508 | ! |
expr = pca <- summary(stats::prcomp(ANL[keep_columns], center = center, scale. = scale, retx = TRUE)), |
509 | ! |
env = list(center = center, scale = scale) |
510 |
) |
|
511 |
) |
|
512 | ||
513 | ! |
qenv <- teal.code::eval_code( |
514 | ! |
qenv, |
515 | ! |
quote({ |
516 | ! |
tbl_importance <- dplyr::as_tibble(pca$importance, rownames = "Metric") |
517 | ! |
tbl_importance |
518 |
}) |
|
519 |
) |
|
520 | ||
521 | ! |
teal.code::eval_code( |
522 | ! |
qenv, |
523 | ! |
quote({ |
524 | ! |
tbl_eigenvector <- dplyr::as_tibble(pca$rotation, rownames = "Variable") |
525 | ! |
tbl_eigenvector |
526 |
}) |
|
527 |
) |
|
528 |
}) |
|
529 | ||
530 |
# plot args ---- |
|
531 | ! |
output$plot_settings <- renderUI({ |
532 |
# reactivity triggers |
|
533 | ! |
req(iv_r()$is_valid()) |
534 | ! |
req(computation()) |
535 | ! |
qenv <- computation() |
536 | ||
537 | ! |
ns <- session$ns |
538 | ||
539 | ! |
pca <- qenv[["pca"]] |
540 | ! |
chcs_pcs <- colnames(pca$rotation) |
541 | ! |
chcs_vars <- qenv[["keep_columns"]] |
542 | ||
543 | ! |
tagList( |
544 | ! |
conditionalPanel( |
545 | ! |
condition = sprintf( |
546 | ! |
"input['%s'] == 'Biplot' || input['%s'] == 'Circle plot'", |
547 | ! |
ns("plot_type"), ns("plot_type") |
548 |
), |
|
549 | ! |
list( |
550 | ! |
teal.widgets::optionalSelectInput(ns("x_axis"), "X axis", choices = chcs_pcs, selected = chcs_pcs[1]), |
551 | ! |
teal.widgets::optionalSelectInput(ns("y_axis"), "Y axis", choices = chcs_pcs, selected = chcs_pcs[2]), |
552 | ! |
teal.widgets::optionalSelectInput( |
553 | ! |
ns("variables"), "Original coordinates", |
554 | ! |
choices = chcs_vars, selected = chcs_vars, |
555 | ! |
multiple = TRUE |
556 |
) |
|
557 |
) |
|
558 |
), |
|
559 | ! |
conditionalPanel( |
560 | ! |
condition = sprintf("input['%s'] == 'Elbow plot'", ns("plot_type")), |
561 | ! |
helpText("No plot specific settings available.") |
562 |
), |
|
563 | ! |
conditionalPanel( |
564 | ! |
condition = paste0("input['", ns("plot_type"), "'] == 'Eigenvector plot'"), |
565 | ! |
teal.widgets::optionalSelectInput(ns("pc"), "PC", choices = chcs_pcs, selected = chcs_pcs[1]) |
566 |
) |
|
567 |
) |
|
568 |
}) |
|
569 | ||
570 |
# plot elbow ---- |
|
571 | ! |
plot_elbow <- function(base_q) { |
572 | ! |
ggtheme <- input$ggtheme |
573 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
574 | ! |
font_size <- input$font_size |
575 | ||
576 | ! |
angle_value <- ifelse(isTRUE(rotate_xaxis_labels), 45, 0) |
577 | ! |
hjust_value <- ifelse(isTRUE(rotate_xaxis_labels), 1, 0.5) |
578 | ||
579 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
580 | ! |
labs = list(x = "Principal component", y = "Proportion of variance explained", color = "", fill = "Legend"), |
581 | ! |
theme = list( |
582 | ! |
legend.position = "right", |
583 | ! |
legend.spacing.y = quote(grid::unit(-5, "pt")), |
584 | ! |
legend.title = quote(element_text(vjust = 25)), |
585 | ! |
axis.text.x = substitute( |
586 | ! |
element_text(angle = angle_value, hjust = hjust_value), |
587 | ! |
list(angle_value = angle_value, hjust_value = hjust_value) |
588 |
), |
|
589 | ! |
text = substitute(element_text(size = font_size), list(font_size = font_size)) |
590 |
) |
|
591 |
) |
|
592 | ||
593 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
594 | ! |
teal.widgets::resolve_ggplot2_args( |
595 | ! |
user_plot = ggplot2_args[["Elbow plot"]], |
596 | ! |
user_default = ggplot2_args$default, |
597 | ! |
module_plot = dev_ggplot2_args |
598 |
), |
|
599 | ! |
ggtheme = ggtheme |
600 |
) |
|
601 | ||
602 | ! |
teal.code::eval_code( |
603 | ! |
base_q, |
604 | ! |
substitute( |
605 | ! |
expr = { |
606 | ! |
elb_dat <- pca$importance[c("Proportion of Variance", "Cumulative Proportion"), ] %>% |
607 | ! |
dplyr::as_tibble(rownames = "metric") %>% |
608 | ! |
tidyr::gather("component", "value", -metric) %>% |
609 | ! |
dplyr::mutate( |
610 | ! |
component = factor(component, levels = unique(stringr::str_sort(component, numeric = TRUE))) |
611 |
) |
|
612 | ||
613 | ! |
cols <- c(getOption("ggplot2.discrete.colour"), c("lightblue", "darkred", "black"))[1:3] |
614 | ! |
elbow_plot <- ggplot(mapping = aes_string(x = "component", y = "value")) + |
615 | ! |
geom_bar( |
616 | ! |
aes(fill = "Single variance"), |
617 | ! |
data = dplyr::filter(elb_dat, metric == "Proportion of Variance"), |
618 | ! |
color = "black", |
619 | ! |
stat = "identity" |
620 |
) + |
|
621 | ! |
geom_point( |
622 | ! |
aes(color = "Cumulative variance"), |
623 | ! |
data = dplyr::filter(elb_dat, metric == "Cumulative Proportion") |
624 |
) + |
|
625 | ! |
geom_line( |
626 | ! |
aes(group = 1, color = "Cumulative variance"), |
627 | ! |
data = dplyr::filter(elb_dat, metric == "Cumulative Proportion") |
628 |
) + |
|
629 | ! |
labs + |
630 | ! |
scale_color_manual(values = c("Cumulative variance" = cols[2], "Single variance" = cols[3])) + |
631 | ! |
scale_fill_manual(values = c("Cumulative variance" = cols[2], "Single variance" = cols[1])) + |
632 | ! |
ggthemes + |
633 | ! |
themes |
634 |
}, |
|
635 | ! |
env = list( |
636 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
637 | ! |
labs = parsed_ggplot2_args$labs, |
638 | ! |
themes = parsed_ggplot2_args$theme |
639 |
) |
|
640 |
) |
|
641 |
) |
|
642 |
} |
|
643 | ||
644 |
# plot circle ---- |
|
645 | ! |
plot_circle <- function(base_q) { |
646 | ! |
x_axis <- input$x_axis |
647 | ! |
y_axis <- input$y_axis |
648 | ! |
variables <- input$variables |
649 | ! |
ggtheme <- input$ggtheme |
650 | ||
651 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
652 | ! |
font_size <- input$font_size |
653 | ||
654 | ! |
angle <- ifelse(isTRUE(rotate_xaxis_labels), 45, 0) |
655 | ! |
hjust <- ifelse(isTRUE(rotate_xaxis_labels), 1, 0.5) |
656 | ||
657 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
658 | ! |
theme = list( |
659 | ! |
text = substitute(element_text(size = font_size), list(font_size = font_size)), |
660 | ! |
axis.text.x = substitute( |
661 | ! |
element_text(angle = angle_val, hjust = hjust_val), |
662 | ! |
list(angle_val = angle, hjust_val = hjust) |
663 |
) |
|
664 |
) |
|
665 |
) |
|
666 | ||
667 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
668 | ! |
user_plot = ggplot2_args[["Circle plot"]], |
669 | ! |
user_default = ggplot2_args$default, |
670 | ! |
module_plot = dev_ggplot2_args |
671 |
) |
|
672 | ||
673 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
674 | ! |
all_ggplot2_args, |
675 | ! |
ggtheme = ggtheme |
676 |
) |
|
677 | ||
678 | ! |
teal.code::eval_code( |
679 | ! |
base_q, |
680 | ! |
substitute( |
681 | ! |
expr = { |
682 | ! |
pca_rot <- pca$rotation[, c(x_axis, y_axis)] %>% |
683 | ! |
dplyr::as_tibble(rownames = "label") %>% |
684 | ! |
dplyr::filter(label %in% variables) |
685 | ||
686 | ! |
circle_data <- data.frame( |
687 | ! |
x = cos(seq(0, 2 * pi, length.out = 100)), |
688 | ! |
y = sin(seq(0, 2 * pi, length.out = 100)) |
689 |
) |
|
690 | ||
691 | ! |
circle_plot <- ggplot(pca_rot) + |
692 | ! |
geom_point(aes_string(x = x_axis, y = y_axis)) + |
693 | ! |
geom_label( |
694 | ! |
aes_string(x = x_axis, y = y_axis, label = "label"), |
695 | ! |
nudge_x = 0.1, nudge_y = 0.05, |
696 | ! |
fontface = "bold" |
697 |
) + |
|
698 | ! |
geom_path(aes(x, y, group = 1), data = circle_data) + |
699 | ! |
geom_point(aes(x = x, y = y), data = data.frame(x = 0, y = 0), shape = "x", size = 5) + |
700 | ! |
labs + |
701 | ! |
ggthemes + |
702 | ! |
themes |
703 |
}, |
|
704 | ! |
env = list( |
705 | ! |
x_axis = x_axis, |
706 | ! |
y_axis = y_axis, |
707 | ! |
variables = variables, |
708 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
709 | ! |
labs = `if`(is.null(parsed_ggplot2_args$labs), quote(labs()), parsed_ggplot2_args$labs), |
710 | ! |
themes = parsed_ggplot2_args$theme |
711 |
) |
|
712 |
) |
|
713 |
) |
|
714 |
} |
|
715 | ||
716 |
# plot biplot ---- |
|
717 | ! |
plot_biplot <- function(base_q) { |
718 | ! |
qenv <- base_q |
719 | ||
720 | ! |
ANL <- qenv[["ANL"]] |
721 | ||
722 | ! |
resp_col <- as.character(merged$anl_input_r()$columns_source$response) |
723 | ! |
dat_cols <- as.character(merged$anl_input_r()$columns_source$dat) |
724 | ! |
x_axis <- input$x_axis |
725 | ! |
y_axis <- input$y_axis |
726 | ! |
variables <- input$variables |
727 | ! |
pca <- qenv[["pca"]] |
728 | ||
729 | ! |
ggtheme <- input$ggtheme |
730 | ||
731 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
732 | ! |
alpha <- input$alpha |
733 | ! |
size <- input$size |
734 | ! |
font_size <- input$font_size |
735 | ||
736 | ! |
qenv <- teal.code::eval_code( |
737 | ! |
qenv, |
738 | ! |
substitute( |
739 | ! |
expr = pca_rot <- dplyr::as_tibble(pca$x[, c(x_axis, y_axis)]), |
740 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
741 |
) |
|
742 |
) |
|
743 | ||
744 |
# rot_vars = data frame that displays arrows in the plot, need to be scaled to data |
|
745 | ! |
if (!is.null(input$variables)) { |
746 | ! |
qenv <- teal.code::eval_code( |
747 | ! |
qenv, |
748 | ! |
substitute( |
749 | ! |
expr = { |
750 | ! |
r <- sqrt(qchisq(0.69, df = 2)) * prod(colMeans(pca_rot ^ 2)) ^ (1 / 4) # styler: off |
751 | ! |
v_scale <- rowSums(pca$rotation ^ 2) # styler: off |
752 | ||
753 | ! |
rot_vars <- pca$rotation[, c(x_axis, y_axis)] %>% |
754 | ! |
dplyr::as_tibble(rownames = "label") %>% |
755 | ! |
dplyr::mutate_at(vars(c(x_axis, y_axis)), function(x) r * x / sqrt(max(v_scale))) |
756 |
}, |
|
757 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
758 |
) |
|
759 |
) %>% |
|
760 | ! |
teal.code::eval_code( |
761 | ! |
if (is.logical(pca$center) && !pca$center) { |
762 | ! |
substitute( |
763 | ! |
expr = { |
764 | ! |
rot_vars <- rot_vars %>% |
765 | ! |
tibble::column_to_rownames("label") %>% |
766 | ! |
sweep(1, apply(ANL[keep_columns], 2, mean, na.rm = TRUE)) %>% |
767 | ! |
tibble::rownames_to_column("label") %>% |
768 | ! |
dplyr::mutate( |
769 | ! |
xstart = mean(pca$x[, x_axis], na.rm = TRUE), |
770 | ! |
ystart = mean(pca$x[, y_axis], na.rm = TRUE) |
771 |
) |
|
772 |
}, |
|
773 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
774 |
) |
|
775 |
} else { |
|
776 | ! |
quote(rot_vars <- rot_vars %>% dplyr::mutate(xstart = 0, ystart = 0)) |
777 |
} |
|
778 |
) %>% |
|
779 | ! |
teal.code::eval_code( |
780 | ! |
substitute( |
781 | ! |
expr = rot_vars <- rot_vars %>% dplyr::filter(label %in% variables), |
782 | ! |
env = list(variables = variables) |
783 |
) |
|
784 |
) |
|
785 |
} |
|
786 | ||
787 | ! |
pca_plot_biplot_expr <- list(quote(ggplot())) |
788 | ||
789 | ! |
if (length(resp_col) == 0) { |
790 | ! |
pca_plot_biplot_expr <- c( |
791 | ! |
pca_plot_biplot_expr, |
792 | ! |
substitute( |
793 | ! |
geom_point(aes_string(x = x_axis, y = y_axis), data = pca_rot, alpha = alpha, size = size), |
794 | ! |
list(x_axis = input$x_axis, y_axis = input$y_axis, alpha = input$alpha, size = input$size) |
795 |
) |
|
796 |
) |
|
797 | ! |
dev_labs <- list() |
798 |
} else { |
|
799 | ! |
rp_keys <- setdiff(colnames(ANL), as.character(unlist(merged$anl_input_r()$columns_source))) |
800 | ||
801 | ! |
response <- ANL[[resp_col]] |
802 | ||
803 | ! |
aes_biplot <- substitute( |
804 | ! |
aes_string(x = x_axis, y = y_axis, color = "response"), |
805 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
806 |
) |
|
807 | ||
808 | ! |
qenv <- teal.code::eval_code( |
809 | ! |
qenv, |
810 | ! |
substitute(response <- ANL[[resp_col]], env = list(resp_col = resp_col)) |
811 |
) |
|
812 | ||
813 | ! |
dev_labs <- list(color = varname_w_label(resp_col, ANL)) |
814 | ||
815 | ! |
scales_biplot <- |
816 | ! |
if ( |
817 | ! |
is.character(response) || |
818 | ! |
is.factor(response) || |
819 | ! |
(is.numeric(response) && length(unique(response)) <= 6) |
820 |
) { |
|
821 | ! |
qenv <- teal.code::eval_code( |
822 | ! |
qenv, |
823 | ! |
quote(pca_rot$response <- as.factor(response)) |
824 |
) |
|
825 | ! |
quote(scale_color_brewer(palette = "Dark2")) |
826 | ! |
} else if (inherits(response, "Date")) { |
827 | ! |
qenv <- teal.code::eval_code( |
828 | ! |
qenv, |
829 | ! |
quote(pca_rot$response <- numeric(response)) |
830 |
) |
|
831 | ||
832 | ! |
quote( |
833 | ! |
scale_color_gradient( |
834 | ! |
low = c(getOption("ggplot2.discrete.colour")[2], "darkred")[1], |
835 | ! |
high = c(getOption("ggplot2.discrete.colour"), "lightblue")[1], |
836 | ! |
labels = function(x) as.Date(x, origin = "1970-01-01") |
837 |
) |
|
838 |
) |
|
839 |
} else { |
|
840 | ! |
qenv <- teal.code::eval_code( |
841 | ! |
qenv, |
842 | ! |
quote(pca_rot$response <- response) |
843 |
) |
|
844 | ! |
quote(scale_color_gradient( |
845 | ! |
low = c(getOption("ggplot2.discrete.colour")[2], "darkred")[1], |
846 | ! |
high = c(getOption("ggplot2.discrete.colour"), "lightblue")[1] |
847 |
)) |
|
848 |
} |
|
849 | ||
850 | ! |
pca_plot_biplot_expr <- c( |
851 | ! |
pca_plot_biplot_expr, |
852 | ! |
substitute( |
853 | ! |
geom_point(aes_biplot, data = pca_rot, alpha = alpha, size = size), |
854 | ! |
env = list(aes_biplot = aes_biplot, alpha = alpha, size = size) |
855 |
), |
|
856 | ! |
scales_biplot |
857 |
) |
|
858 |
} |
|
859 | ||
860 | ! |
if (!is.null(input$variables)) { |
861 | ! |
pca_plot_biplot_expr <- c( |
862 | ! |
pca_plot_biplot_expr, |
863 | ! |
substitute( |
864 | ! |
geom_segment( |
865 | ! |
aes_string(x = "xstart", y = "ystart", xend = x_axis, yend = y_axis), |
866 | ! |
data = rot_vars, |
867 | ! |
lineend = "round", linejoin = "round", |
868 | ! |
arrow = grid::arrow(length = grid::unit(0.5, "cm")) |
869 |
), |
|
870 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
871 |
), |
|
872 | ! |
substitute( |
873 | ! |
geom_label( |
874 | ! |
aes_string( |
875 | ! |
x = x_axis, |
876 | ! |
y = y_axis, |
877 | ! |
label = "label" |
878 |
), |
|
879 | ! |
data = rot_vars, |
880 | ! |
nudge_y = 0.1, |
881 | ! |
fontface = "bold" |
882 |
), |
|
883 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
884 |
), |
|
885 | ! |
quote(geom_point(aes(x = xstart, y = ystart), data = rot_vars, shape = "x", size = 5)) |
886 |
) |
|
887 |
} |
|
888 | ||
889 | ! |
angle <- ifelse(isTRUE(rotate_xaxis_labels), 45, 0) |
890 | ! |
hjust <- ifelse(isTRUE(rotate_xaxis_labels), 1, 0.5) |
891 | ||
892 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
893 | ! |
labs = dev_labs, |
894 | ! |
theme = list( |
895 | ! |
text = substitute(element_text(size = font_size), list(font_size = font_size)), |
896 | ! |
axis.text.x = substitute( |
897 | ! |
element_text(angle = angle_val, hjust = hjust_val), |
898 | ! |
list(angle_val = angle, hjust_val = hjust) |
899 |
) |
|
900 |
) |
|
901 |
) |
|
902 | ||
903 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
904 | ! |
user_plot = ggplot2_args[["Biplot"]], |
905 | ! |
user_default = ggplot2_args$default, |
906 | ! |
module_plot = dev_ggplot2_args |
907 |
) |
|
908 | ||
909 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
910 | ! |
all_ggplot2_args, |
911 | ! |
ggtheme = ggtheme |
912 |
) |
|
913 | ||
914 | ! |
pca_plot_biplot_expr <- c( |
915 | ! |
pca_plot_biplot_expr, |
916 | ! |
parsed_ggplot2_args |
917 |
) |
|
918 | ||
919 | ! |
teal.code::eval_code( |
920 | ! |
qenv, |
921 | ! |
substitute( |
922 | ! |
expr = { |
923 | ! |
biplot <- plot_call |
924 |
}, |
|
925 | ! |
env = list( |
926 | ! |
plot_call = Reduce(function(x, y) call("+", x, y), pca_plot_biplot_expr) |
927 |
) |
|
928 |
) |
|
929 |
) |
|
930 |
} |
|
931 | ||
932 |
# plot eigenvector_plot ---- |
|
933 | ! |
plot_eigenvector <- function(base_q) { |
934 | ! |
pc <- input$pc |
935 | ! |
ggtheme <- input$ggtheme |
936 | ||
937 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
938 | ! |
font_size <- input$font_size |
939 | ||
940 | ! |
angle <- ifelse(rotate_xaxis_labels, 45, 0) |
941 | ! |
hjust <- ifelse(rotate_xaxis_labels, 1, 0.5) |
942 | ||
943 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
944 | ! |
theme = list( |
945 | ! |
text = substitute(element_text(size = font_size), list(font_size = font_size)), |
946 | ! |
axis.text.x = substitute( |
947 | ! |
element_text(angle = angle_val, hjust = hjust_val), |
948 | ! |
list(angle_val = angle, hjust_val = hjust) |
949 |
) |
|
950 |
) |
|
951 |
) |
|
952 | ||
953 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
954 | ! |
user_plot = ggplot2_args[["Eigenvector plot"]], |
955 | ! |
user_default = ggplot2_args$default, |
956 | ! |
module_plot = dev_ggplot2_args |
957 |
) |
|
958 | ||
959 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
960 | ! |
all_ggplot2_args, |
961 | ! |
ggtheme = ggtheme |
962 |
) |
|
963 | ||
964 | ! |
ggplot_exprs <- c( |
965 | ! |
list( |
966 | ! |
quote(ggplot(pca_rot)), |
967 | ! |
substitute( |
968 | ! |
geom_bar( |
969 | ! |
aes_string(x = "Variable", y = pc), |
970 | ! |
stat = "identity", |
971 | ! |
color = "black", |
972 | ! |
fill = c(getOption("ggplot2.discrete.colour"), "lightblue")[1] |
973 |
), |
|
974 | ! |
env = list(pc = pc) |
975 |
), |
|
976 | ! |
substitute( |
977 | ! |
geom_text( |
978 | ! |
aes( |
979 | ! |
x = Variable, |
980 | ! |
y = pc_name, |
981 | ! |
label = round(pc_name, 3), |
982 | ! |
vjust = ifelse(pc_name > 0, -0.5, 1.3) |
983 |
) |
|
984 |
), |
|
985 | ! |
env = list(pc_name = as.name(pc)) |
986 |
) |
|
987 |
), |
|
988 | ! |
parsed_ggplot2_args$labs, |
989 | ! |
parsed_ggplot2_args$ggtheme, |
990 | ! |
parsed_ggplot2_args$theme |
991 |
) |
|
992 | ||
993 | ! |
teal.code::eval_code( |
994 | ! |
base_q, |
995 | ! |
substitute( |
996 | ! |
expr = { |
997 | ! |
pca_rot <- pca$rotation[, pc, drop = FALSE] %>% |
998 | ! |
dplyr::as_tibble(rownames = "Variable") |
999 | ! |
eigenvector_plot <- plot_call |
1000 |
}, |
|
1001 | ! |
env = list( |
1002 | ! |
pc = pc, |
1003 | ! |
plot_call = Reduce(function(x, y) call("+", x, y), ggplot_exprs) |
1004 |
) |
|
1005 |
) |
|
1006 |
) |
|
1007 |
} |
|
1008 | ||
1009 |
# qenvs --- |
|
1010 | ! |
output_q <- lapply( |
1011 | ! |
list( |
1012 | ! |
elbow_plot = plot_elbow, |
1013 | ! |
circle_plot = plot_circle, |
1014 | ! |
biplot = plot_biplot, |
1015 | ! |
eigenvector_plot = plot_eigenvector |
1016 |
), |
|
1017 | ! |
function(fun) { |
1018 | ! |
reactive({ |
1019 | ! |
req(computation()) |
1020 | ! |
teal::validate_inputs(iv_r()) |
1021 | ! |
teal::validate_inputs(iv_extra, header = "Plot settings are required") |
1022 | ! |
fun(computation()) |
1023 |
}) |
|
1024 |
} |
|
1025 |
) |
|
1026 | ||
1027 | ! |
decorated_q <- mapply( |
1028 | ! |
function(obj_name, q) { |
1029 | ! |
srv_decorate_teal_data( |
1030 | ! |
id = sprintf("d_%s", obj_name), |
1031 | ! |
data = q, |
1032 | ! |
decorators = select_decorators(decorators, obj_name), |
1033 | ! |
expr = reactive({ |
1034 | ! |
substitute(print(.plot), env = list(.plot = as.name(obj_name))) |
1035 |
}), |
|
1036 | ! |
expr_is_reactive = TRUE |
1037 |
) |
|
1038 |
}, |
|
1039 | ! |
names(output_q), |
1040 | ! |
output_q |
1041 |
) |
|
1042 | ||
1043 |
# plot final ---- |
|
1044 | ! |
decorated_output_q <- reactive({ |
1045 | ! |
switch(req(input$plot_type), |
1046 | ! |
"Elbow plot" = decorated_q$elbow_plot(), |
1047 | ! |
"Circle plot" = decorated_q$circle_plot(), |
1048 | ! |
"Biplot" = decorated_q$biplot(), |
1049 | ! |
"Eigenvector plot" = decorated_q$eigenvector_plot(), |
1050 | ! |
stop("Unknown plot") |
1051 |
) |
|
1052 |
}) |
|
1053 | ||
1054 | ! |
plot_r <- reactive({ |
1055 | ! |
plot_name <- gsub(" ", "_", tolower(req(input$plot_type))) |
1056 | ! |
req(decorated_output_q())[[plot_name]] |
1057 |
}) |
|
1058 | ||
1059 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
1060 | ! |
id = "pca_plot", |
1061 | ! |
plot_r = plot_r, |
1062 | ! |
height = plot_height, |
1063 | ! |
width = plot_width, |
1064 | ! |
graph_align = "center" |
1065 |
) |
|
1066 | ||
1067 |
# tables ---- |
|
1068 | ! |
output$tbl_importance <- renderTable( |
1069 | ! |
expr = { |
1070 | ! |
req("importance" %in% input$tables_display, computation()) |
1071 | ! |
computation()[["tbl_importance"]] |
1072 |
}, |
|
1073 | ! |
bordered = TRUE, |
1074 | ! |
align = "c", |
1075 | ! |
digits = 3 |
1076 |
) |
|
1077 | ||
1078 | ! |
output$tbl_importance_ui <- renderUI({ |
1079 | ! |
req("importance" %in% input$tables_display) |
1080 | ! |
tags$div( |
1081 | ! |
align = "center", |
1082 | ! |
tags$h4("Principal components importance"), |
1083 | ! |
tableOutput(session$ns("tbl_importance")), |
1084 | ! |
tags$hr() |
1085 |
) |
|
1086 |
}) |
|
1087 | ||
1088 | ! |
output$tbl_eigenvector <- renderTable( |
1089 | ! |
expr = { |
1090 | ! |
req("eigenvector" %in% input$tables_display, req(computation())) |
1091 | ! |
computation()[["tbl_eigenvector"]] |
1092 |
}, |
|
1093 | ! |
bordered = TRUE, |
1094 | ! |
align = "c", |
1095 | ! |
digits = 3 |
1096 |
) |
|
1097 | ||
1098 | ! |
output$tbl_eigenvector_ui <- renderUI({ |
1099 | ! |
req("eigenvector" %in% input$tables_display) |
1100 | ! |
tags$div( |
1101 | ! |
align = "center", |
1102 | ! |
tags$h4("Eigenvectors"), |
1103 | ! |
tableOutput(session$ns("tbl_eigenvector")), |
1104 | ! |
tags$hr() |
1105 |
) |
|
1106 |
}) |
|
1107 | ||
1108 | ! |
output$all_plots <- renderUI({ |
1109 | ! |
teal::validate_inputs(iv_r()) |
1110 | ! |
teal::validate_inputs(iv_extra, header = "Plot settings are required") |
1111 | ||
1112 | ! |
validation() |
1113 | ! |
tags$div( |
1114 | ! |
class = "overflow-scroll", |
1115 | ! |
uiOutput(session$ns("tbl_importance_ui")), |
1116 | ! |
uiOutput(session$ns("tbl_eigenvector_ui")), |
1117 | ! |
teal.widgets::plot_with_settings_ui(id = session$ns("pca_plot")) |
1118 |
) |
|
1119 |
}) |
|
1120 | ||
1121 |
# Render R code. |
|
1122 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_output_q()))) |
1123 | ||
1124 | ! |
teal.widgets::verbatim_popup_srv( |
1125 | ! |
id = "rcode", |
1126 | ! |
verbatim_content = source_code_r, |
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(source_code_r()) |
1150 | ! |
card |
1151 |
} |
|
1152 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
1153 |
} |
|
1154 |
### |
|
1155 |
}) |
|
1156 |
} |
1 |
#' `teal` module: Variable browser |
|
2 |
#' |
|
3 |
#' Module provides provides a detailed summary and visualization of variable distributions |
|
4 |
#' for `data.frame` objects, with interactive features to customize analysis. |
|
5 |
#' |
|
6 |
#' Numeric columns with fewer than 30 distinct values can be treated as either discrete |
|
7 |
#' or continuous with a checkbox allowing users to switch how they are treated(if < 6 unique values |
|
8 |
#' then the default is discrete, otherwise it is continuous). |
|
9 |
#' |
|
10 |
#' @inheritParams teal::module |
|
11 |
#' @inheritParams shared_params |
|
12 |
#' @param parent_dataname (`character(1)`) string specifying a parent dataset. |
|
13 |
#' If it exists in `datanames` then an extra checkbox will be shown to |
|
14 |
#' allow users to not show variables in other datasets which exist in this `dataname`. |
|
15 |
#' This is typically used to remove `ADSL` columns in `CDISC` data. |
|
16 |
#' In non `CDISC` data this can be ignored. Defaults to `"ADSL"`. |
|
17 |
#' @param datasets_selected (`character`) `r lifecycle::badge("deprecated")` vector of datasets to show, please |
|
18 |
#' use the `datanames` argument. |
|
19 |
#' |
|
20 |
#' @inherit shared_params return |
|
21 |
#' |
|
22 |
#' @examplesShinylive |
|
23 |
#' library(teal.modules.general) |
|
24 |
#' interactive <- function() TRUE |
|
25 |
#' {{ next_example }} |
|
26 |
# nolint start: line_length_linter. |
|
27 |
#' @examples |
|
28 |
# nolint end: line_length_linter. |
|
29 |
#' # general data example |
|
30 |
#' data <- teal_data() |
|
31 |
#' data <- within(data, { |
|
32 |
#' iris <- iris |
|
33 |
#' mtcars <- mtcars |
|
34 |
#' women <- women |
|
35 |
#' faithful <- faithful |
|
36 |
#' CO2 <- CO2 |
|
37 |
#' }) |
|
38 |
#' |
|
39 |
#' app <- init( |
|
40 |
#' data = data, |
|
41 |
#' modules = modules( |
|
42 |
#' tm_variable_browser( |
|
43 |
#' label = "Variable browser" |
|
44 |
#' ) |
|
45 |
#' ) |
|
46 |
#' ) |
|
47 |
#' if (interactive()) { |
|
48 |
#' shinyApp(app$ui, app$server) |
|
49 |
#' } |
|
50 |
#' |
|
51 |
#' @examplesShinylive |
|
52 |
#' library(teal.modules.general) |
|
53 |
#' interactive <- function() TRUE |
|
54 |
#' {{ next_example }} |
|
55 |
# nolint start: line_length_linter. |
|
56 |
#' @examples |
|
57 |
# nolint end: line_length_linter. |
|
58 |
#' # CDISC example data |
|
59 |
#' library(sparkline) |
|
60 |
#' data <- teal_data() |
|
61 |
#' data <- within(data, { |
|
62 |
#' ADSL <- teal.data::rADSL |
|
63 |
#' ADTTE <- teal.data::rADTTE |
|
64 |
#' }) |
|
65 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
66 |
#' |
|
67 |
#' app <- init( |
|
68 |
#' data = data, |
|
69 |
#' modules = modules( |
|
70 |
#' tm_variable_browser( |
|
71 |
#' label = "Variable browser" |
|
72 |
#' ) |
|
73 |
#' ) |
|
74 |
#' ) |
|
75 |
#' if (interactive()) { |
|
76 |
#' shinyApp(app$ui, app$server) |
|
77 |
#' } |
|
78 |
#' |
|
79 |
#' @export |
|
80 |
#' |
|
81 |
tm_variable_browser <- function(label = "Variable Browser", |
|
82 |
datasets_selected = deprecated(), |
|
83 |
datanames = if (missing(datasets_selected)) "all" else datasets_selected, |
|
84 |
parent_dataname = "ADSL", |
|
85 |
pre_output = NULL, |
|
86 |
post_output = NULL, |
|
87 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
88 |
transformators = list()) { |
|
89 | ! |
message("Initializing tm_variable_browser") |
90 | ||
91 |
# Start of assertions |
|
92 | ! |
checkmate::assert_string(label) |
93 | ! |
if (!missing(datasets_selected)) { |
94 | ! |
lifecycle::deprecate_soft( |
95 | ! |
when = "0.4.0", |
96 | ! |
what = "tm_variable_browser(datasets_selected)", |
97 | ! |
with = "tm_variable_browser(datanames)", |
98 | ! |
details = c( |
99 | ! |
"If both `datasets_selected` and `datanames` are set `datasets_selected` will be silently ignored.", |
100 | ! |
i = 'Use `tm_variable_browser(datanames = "all")` to keep the previous behavior and avoid this warning.' |
101 |
) |
|
102 |
) |
|
103 |
} |
|
104 | ! |
checkmate::assert_character(datanames, min.len = 0, min.chars = 1, null.ok = TRUE) |
105 | ! |
checkmate::assert_character(parent_dataname, min.len = 0, max.len = 1) |
106 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
107 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
108 | ! |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
109 |
# End of assertions |
|
110 | ||
111 | ! |
datanames_module <- if (identical(datanames, "all") || is.null(datanames)) { |
112 | ! |
datanames |
113 |
} else { |
|
114 | ! |
union(datanames, parent_dataname) |
115 |
} |
|
116 | ||
117 | ! |
ans <- module( |
118 | ! |
label, |
119 | ! |
server = srv_variable_browser, |
120 | ! |
ui = ui_variable_browser, |
121 | ! |
datanames = datanames_module, |
122 | ! |
server_args = list( |
123 | ! |
datanames = if (is.null(datanames)) "all" else datanames, |
124 | ! |
parent_dataname = parent_dataname, |
125 | ! |
ggplot2_args = ggplot2_args |
126 |
), |
|
127 | ! |
ui_args = list( |
128 | ! |
pre_output = pre_output, |
129 | ! |
post_output = post_output |
130 |
), |
|
131 | ! |
transformators = transformators |
132 |
) |
|
133 |
# `shiny` inputs are stored properly but the majority of the module is state of `datatable` which is not stored. |
|
134 | ! |
attr(ans, "teal_bookmarkable") <- NULL |
135 | ! |
ans |
136 |
} |
|
137 | ||
138 |
# UI function for the variable browser module |
|
139 |
ui_variable_browser <- function(id, |
|
140 |
pre_output = NULL, |
|
141 |
post_output = NULL) { |
|
142 | ! |
ns <- NS(id) |
143 | ||
144 | ! |
tagList( |
145 | ! |
include_css_files("custom"), |
146 | ! |
shinyjs::useShinyjs(), |
147 | ! |
teal.widgets::standard_layout( |
148 | ! |
output = fluidRow( |
149 | ! |
htmlwidgets::getDependency("sparkline"), # needed for sparklines to work |
150 | ! |
column( |
151 | ! |
6, |
152 |
# variable browser |
|
153 | ! |
teal.widgets::white_small_well( |
154 | ! |
uiOutput(ns("ui_variable_browser")), |
155 | ! |
shinyjs::hidden({ |
156 | ! |
checkboxInput(ns("show_parent_vars"), "Show parent dataset variables", value = FALSE) |
157 |
}) |
|
158 |
) |
|
159 |
), |
|
160 | ! |
column( |
161 | ! |
6, |
162 | ! |
teal.widgets::white_small_well( |
163 |
### Reporter |
|
164 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
165 |
### |
|
166 | ! |
tags$div( |
167 | ! |
class = "block", |
168 | ! |
uiOutput(ns("ui_histogram_display")) |
169 |
), |
|
170 | ! |
tags$div( |
171 | ! |
class = "block", |
172 | ! |
uiOutput(ns("ui_numeric_display")) |
173 |
), |
|
174 | ! |
teal.widgets::plot_with_settings_ui(ns("variable_plot")), |
175 | ! |
tags$br(), |
176 |
# input user-defined text size |
|
177 | ! |
teal.widgets::panel_item( |
178 | ! |
title = "Plot settings", |
179 | ! |
collapsed = TRUE, |
180 | ! |
selectInput( |
181 | ! |
inputId = ns("ggplot_theme"), label = "ggplot2 theme", |
182 | ! |
choices = ggplot_themes, |
183 | ! |
selected = "grey" |
184 |
), |
|
185 | ! |
fluidRow( |
186 | ! |
column(6, sliderInput( |
187 | ! |
inputId = ns("font_size"), label = "font size", |
188 | ! |
min = 5L, max = 30L, value = 15L, step = 1L, ticks = FALSE |
189 |
)), |
|
190 | ! |
column(6, sliderInput( |
191 | ! |
inputId = ns("label_rotation"), label = "rotate x labels", |
192 | ! |
min = 0L, max = 90L, value = 45L, step = 1, ticks = FALSE |
193 |
)) |
|
194 |
) |
|
195 |
), |
|
196 | ! |
tags$br(), |
197 | ! |
teal.widgets::get_dt_rows(ns("variable_summary_table"), ns("variable_summary_table_rows")), |
198 | ! |
DT::dataTableOutput(ns("variable_summary_table")) |
199 |
) |
|
200 |
) |
|
201 |
), |
|
202 | ! |
pre_output = pre_output, |
203 | ! |
post_output = post_output |
204 |
) |
|
205 |
) |
|
206 |
} |
|
207 | ||
208 |
# Server function for the variable browser module |
|
209 |
srv_variable_browser <- function(id, |
|
210 |
data, |
|
211 |
reporter, |
|
212 |
filter_panel_api, |
|
213 |
datanames, parent_dataname, ggplot2_args) { |
|
214 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
215 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
216 | ! |
checkmate::assert_class(data, "reactive") |
217 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
218 | ! |
moduleServer(id, function(input, output, session) { |
219 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
220 | ||
221 |
# if there are < this number of unique records then a numeric |
|
222 |
# variable can be treated as a factor and all factors with < this groups |
|
223 |
# have their values plotted |
|
224 | ! |
.unique_records_for_factor <- 30 |
225 |
# if there are < this number of unique records then a numeric |
|
226 |
# variable is by default treated as a factor |
|
227 | ! |
.unique_records_default_as_factor <- 6 # nolint: object_length. |
228 | ||
229 | ! |
varname_numeric_as_factor <- reactiveValues() |
230 | ||
231 | ! |
datanames <- Filter(function(name) { |
232 | ! |
is.data.frame(isolate(data())[[name]]) |
233 | ! |
}, if (identical(datanames, "all")) names(isolate(data())) else datanames) |
234 | ||
235 | ! |
output$ui_variable_browser <- renderUI({ |
236 | ! |
ns <- session$ns |
237 | ! |
do.call( |
238 | ! |
tabsetPanel, |
239 | ! |
c( |
240 | ! |
id = ns("tabset_panel"), |
241 | ! |
do.call( |
242 | ! |
tagList, |
243 | ! |
lapply(datanames, function(dataname) { |
244 | ! |
tabPanel( |
245 | ! |
dataname, |
246 | ! |
tags$div( |
247 | ! |
class = "mt-4", |
248 | ! |
textOutput(ns(paste0("dataset_summary_", dataname))) |
249 |
), |
|
250 | ! |
tags$div( |
251 | ! |
class = "mt-4", |
252 | ! |
teal.widgets::get_dt_rows( |
253 | ! |
ns(paste0("variable_browser_", dataname)), |
254 | ! |
ns(paste0("variable_browser_", dataname, "_rows")) |
255 |
), |
|
256 | ! |
DT::dataTableOutput(ns(paste0("variable_browser_", dataname)), width = "100%") |
257 |
) |
|
258 |
) |
|
259 |
}) |
|
260 |
) |
|
261 |
) |
|
262 |
) |
|
263 |
}) |
|
264 | ||
265 |
# conditionally display checkbox |
|
266 | ! |
shinyjs::toggle( |
267 | ! |
id = "show_parent_vars", |
268 | ! |
condition = length(parent_dataname) > 0 && parent_dataname %in% datanames |
269 |
) |
|
270 | ||
271 | ! |
columns_names <- new.env() |
272 | ||
273 |
# plot_var$data holds the name of the currently selected dataset |
|
274 |
# plot_var$variable[[<dataset_name>]] holds the name of the currently selected |
|
275 |
# variable for dataset <dataset_name> |
|
276 | ! |
plot_var <- reactiveValues(data = NULL, variable = list()) |
277 | ||
278 | ! |
establish_updating_selection(datanames, input, plot_var, columns_names) |
279 | ||
280 |
# validations |
|
281 | ! |
validation_checks <- validate_input(input, plot_var, data) |
282 | ||
283 |
# data_for_analysis is a list with two elements: a column from a dataset and the column label |
|
284 | ! |
plotted_data <- reactive({ |
285 | ! |
validation_checks() |
286 | ||
287 | ! |
get_plotted_data(input, plot_var, data) |
288 |
}) |
|
289 | ||
290 | ! |
treat_numeric_as_factor <- reactive({ |
291 | ! |
if (is_num_var_short(.unique_records_for_factor, input, plotted_data)) { |
292 | ! |
input$numeric_as_factor |
293 |
} else { |
|
294 | ! |
FALSE |
295 |
} |
|
296 |
}) |
|
297 | ||
298 | ! |
render_tabset_panel_content( |
299 | ! |
input = input, |
300 | ! |
output = output, |
301 | ! |
data = data, |
302 | ! |
datanames = datanames, |
303 | ! |
parent_dataname = parent_dataname, |
304 | ! |
columns_names = columns_names, |
305 | ! |
plot_var = plot_var |
306 |
) |
|
307 |
# add used-defined text size to ggplot arguments passed from caller frame |
|
308 | ! |
all_ggplot2_args <- reactive({ |
309 | ! |
user_text <- teal.widgets::ggplot2_args( |
310 | ! |
theme = list( |
311 | ! |
"text" = ggplot2::element_text(size = input[["font_size"]]), |
312 | ! |
"axis.text.x" = ggplot2::element_text(angle = input[["label_rotation"]], hjust = 1) |
313 |
) |
|
314 |
) |
|
315 | ! |
user_theme <- utils::getFromNamespace(sprintf("theme_%s", input[["ggplot_theme"]]), ns = "ggplot2") |
316 | ! |
user_theme <- user_theme() |
317 |
# temporary fix to circumvent assertion issue with resolve_ggplot2_args |
|
318 |
# drop problematic elements |
|
319 | ! |
user_theme <- user_theme[grep("strip.text.y.left", names(user_theme), fixed = TRUE, invert = TRUE)] |
320 | ||
321 | ! |
teal.widgets::resolve_ggplot2_args( |
322 | ! |
user_plot = user_text, |
323 | ! |
user_default = teal.widgets::ggplot2_args(theme = user_theme), |
324 | ! |
module_plot = ggplot2_args |
325 |
) |
|
326 |
}) |
|
327 | ||
328 | ! |
output$ui_numeric_display <- renderUI({ |
329 | ! |
validation_checks() |
330 | ! |
dataname <- input$tabset_panel |
331 | ! |
varname <- plot_var$variable[[dataname]] |
332 | ! |
df <- data()[[dataname]] |
333 | ||
334 | ! |
numeric_ui <- tagList( |
335 | ! |
fluidRow( |
336 | ! |
tags$div( |
337 | ! |
class = "col-md-4", |
338 | ! |
tags$br(), |
339 | ! |
shinyWidgets::switchInput( |
340 | ! |
inputId = session$ns("display_density"), |
341 | ! |
label = "Show density", |
342 | ! |
value = `if`(is.null(isolate(input$display_density)), TRUE, isolate(input$display_density)), |
343 | ! |
width = "50%", |
344 | ! |
labelWidth = "100px", |
345 | ! |
handleWidth = "50px" |
346 |
) |
|
347 |
), |
|
348 | ! |
tags$div( |
349 | ! |
class = "col-md-4", |
350 | ! |
tags$br(), |
351 | ! |
shinyWidgets::switchInput( |
352 | ! |
inputId = session$ns("remove_outliers"), |
353 | ! |
label = "Remove outliers", |
354 | ! |
value = `if`(is.null(isolate(input$remove_outliers)), FALSE, isolate(input$remove_outliers)), |
355 | ! |
width = "50%", |
356 | ! |
labelWidth = "100px", |
357 | ! |
handleWidth = "50px" |
358 |
) |
|
359 |
), |
|
360 | ! |
tags$div( |
361 | ! |
class = "col-md-4", |
362 | ! |
uiOutput(session$ns("outlier_definition_slider_ui")) |
363 |
) |
|
364 |
), |
|
365 | ! |
tags$div( |
366 | ! |
class = "ml-4", |
367 | ! |
uiOutput(session$ns("ui_density_help")), |
368 | ! |
uiOutput(session$ns("ui_outlier_help")) |
369 |
) |
|
370 |
) |
|
371 | ||
372 | ! |
observeEvent(input$numeric_as_factor, ignoreInit = TRUE, { |
373 | ! |
varname_numeric_as_factor[[plot_var$variable[[dataname]]]] <- input$numeric_as_factor |
374 |
}) |
|
375 | ||
376 | ! |
if (is.numeric(df[[varname]])) { |
377 | ! |
unique_entries <- length(unique(df[[varname]])) |
378 | ! |
if (unique_entries < .unique_records_for_factor && unique_entries > 0) { |
379 | ! |
list( |
380 | ! |
checkboxInput( |
381 | ! |
session$ns("numeric_as_factor"), |
382 | ! |
"Treat variable as factor", |
383 | ! |
value = `if`( |
384 | ! |
is.null(varname_numeric_as_factor[[varname]]), |
385 | ! |
unique_entries < .unique_records_default_as_factor, |
386 | ! |
varname_numeric_as_factor[[varname]] |
387 |
) |
|
388 |
), |
|
389 | ! |
conditionalPanel("!input.numeric_as_factor", ns = session$ns, numeric_ui) |
390 |
) |
|
391 | ! |
} else if (unique_entries > 0) { |
392 | ! |
numeric_ui |
393 |
} |
|
394 |
} else { |
|
395 | ! |
NULL |
396 |
} |
|
397 |
}) |
|
398 | ||
399 | ! |
output$ui_histogram_display <- renderUI({ |
400 | ! |
validation_checks() |
401 | ! |
dataname <- input$tabset_panel |
402 | ! |
varname <- plot_var$variable[[dataname]] |
403 | ! |
df <- data()[[dataname]] |
404 | ||
405 | ! |
numeric_ui <- tagList(fluidRow( |
406 | ! |
tags$div( |
407 | ! |
class = "col-md-4", |
408 | ! |
shinyWidgets::switchInput( |
409 | ! |
inputId = session$ns("remove_NA_hist"), |
410 | ! |
label = "Remove NA values", |
411 | ! |
value = FALSE, |
412 | ! |
width = "50%", |
413 | ! |
labelWidth = "100px", |
414 | ! |
handleWidth = "50px" |
415 |
) |
|
416 |
) |
|
417 |
)) |
|
418 | ||
419 | ! |
var <- df[[varname]] |
420 | ! |
if (anyNA(var) && (is.factor(var) || is.character(var) || is.logical(var))) { |
421 | ! |
groups <- unique(as.character(var)) |
422 | ! |
len_groups <- length(groups) |
423 | ! |
if (len_groups >= .unique_records_for_factor) { |
424 | ! |
NULL |
425 |
} else { |
|
426 | ! |
numeric_ui |
427 |
} |
|
428 |
} else { |
|
429 | ! |
NULL |
430 |
} |
|
431 |
}) |
|
432 | ||
433 | ! |
output$outlier_definition_slider_ui <- renderUI({ |
434 | ! |
req(input$remove_outliers) |
435 | ! |
sliderInput( |
436 | ! |
inputId = session$ns("outlier_definition_slider"), |
437 | ! |
tags$div( |
438 | ! |
class = "teal-tooltip", |
439 | ! |
tagList( |
440 | ! |
"Outlier definition:", |
441 | ! |
icon("circle-info"), |
442 | ! |
tags$span( |
443 | ! |
class = "tooltiptext", |
444 | ! |
paste( |
445 | ! |
"Use the slider to choose the cut-off value to define outliers; the larger the value the", |
446 | ! |
"further below Q1/above Q3 points have to be in order to be classed as outliers" |
447 |
) |
|
448 |
) |
|
449 |
) |
|
450 |
), |
|
451 | ! |
min = 1, |
452 | ! |
max = 5, |
453 | ! |
value = 3, |
454 | ! |
step = 0.5 |
455 |
) |
|
456 |
}) |
|
457 | ||
458 | ! |
output$ui_density_help <- renderUI({ |
459 | ! |
req(is.logical(input$display_density)) |
460 | ! |
if (input$display_density) { |
461 | ! |
tags$small(helpText(paste( |
462 | ! |
"Kernel density estimation with gaussian kernel", |
463 | ! |
"and bandwidth function bw.nrd0 (R default)" |
464 |
))) |
|
465 |
} else { |
|
466 | ! |
NULL |
467 |
} |
|
468 |
}) |
|
469 | ||
470 | ! |
output$ui_outlier_help <- renderUI({ |
471 | ! |
req(is.logical(input$remove_outliers), input$outlier_definition_slider) |
472 | ! |
if (input$remove_outliers) { |
473 | ! |
tags$small( |
474 | ! |
helpText( |
475 | ! |
withMathJax(paste0( |
476 | ! |
"Outlier data points (\\( X \\lt Q1 - ", input$outlier_definition_slider, "\\times IQR \\) or |
477 | ! |
\\(Q3 + ", input$outlier_definition_slider, "\\times IQR \\lt X\\)) |
478 | ! |
have not been displayed on the graph and will not be used for any kernel density estimations, ", |
479 | ! |
"although their values remain in the statisics table below." |
480 |
)) |
|
481 |
) |
|
482 |
) |
|
483 |
} else { |
|
484 | ! |
NULL |
485 |
} |
|
486 |
}) |
|
487 | ||
488 | ||
489 | ! |
variable_plot_r <- reactive({ |
490 | ! |
display_density <- `if`(is.null(input$display_density), FALSE, input$display_density) |
491 | ! |
remove_outliers <- `if`(is.null(input$remove_outliers), FALSE, input$remove_outliers) |
492 | ||
493 | ! |
if (remove_outliers) { |
494 | ! |
req(input$outlier_definition_slider) |
495 | ! |
outlier_definition <- as.numeric(input$outlier_definition_slider) |
496 |
} else { |
|
497 | ! |
outlier_definition <- 0 |
498 |
} |
|
499 | ||
500 | ! |
plot_var_summary( |
501 | ! |
var = plotted_data()$data, |
502 | ! |
var_lab = plotted_data()$var_description, |
503 | ! |
wrap_character = 15, |
504 | ! |
numeric_as_factor = treat_numeric_as_factor(), |
505 | ! |
remove_NA_hist = input$remove_NA_hist, |
506 | ! |
display_density = display_density, |
507 | ! |
outlier_definition = outlier_definition, |
508 | ! |
records_for_factor = .unique_records_for_factor, |
509 | ! |
ggplot2_args = all_ggplot2_args() |
510 |
) |
|
511 |
}) |
|
512 | ||
513 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
514 | ! |
id = "variable_plot", |
515 | ! |
plot_r = variable_plot_r, |
516 | ! |
height = c(500, 200, 2000) |
517 |
) |
|
518 | ||
519 | ! |
output$variable_summary_table <- DT::renderDataTable({ |
520 | ! |
var_summary_table( |
521 | ! |
plotted_data()$data, |
522 | ! |
treat_numeric_as_factor(), |
523 | ! |
input$variable_summary_table_rows, |
524 | ! |
if (!is.null(input$remove_outliers) && input$remove_outliers) { |
525 | ! |
req(input$outlier_definition_slider) |
526 | ! |
as.numeric(input$outlier_definition_slider) |
527 |
} else { |
|
528 | ! |
0 |
529 |
} |
|
530 |
) |
|
531 |
}) |
|
532 | ||
533 |
### REPORTER |
|
534 | ! |
if (with_reporter) { |
535 | ! |
card_fun <- function(comment) { |
536 | ! |
card <- teal::TealReportCard$new() |
537 | ! |
card$set_name("Variable Browser Plot") |
538 | ! |
card$append_text("Variable Browser Plot", "header2") |
539 | ! |
if (with_filter) card$append_fs(filter_panel_api$get_filter_state()) |
540 | ! |
card$append_text("Plot", "header3") |
541 | ! |
card$append_plot(variable_plot_r(), dim = pws$dim()) |
542 | ! |
if (!comment == "") { |
543 | ! |
card$append_text("Comment", "header3") |
544 | ! |
card$append_text(comment) |
545 |
} |
|
546 | ! |
card |
547 |
} |
|
548 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
549 |
} |
|
550 |
### |
|
551 |
}) |
|
552 |
} |
|
553 | ||
554 |
#' Summarize NAs. |
|
555 |
#' |
|
556 |
#' Summarizes occurrence of missing values in vector. |
|
557 |
#' @param x vector of any type and length |
|
558 |
#' @return Character string describing `NA` occurrence. |
|
559 |
#' @keywords internal |
|
560 |
var_missings_info <- function(x) { |
|
561 | ! |
sprintf("%s [%s%%]", sum(is.na(x)), round(mean(is.na(x) * 100), 2)) |
562 |
} |
|
563 | ||
564 |
#' Summarizes variable |
|
565 |
#' |
|
566 |
#' Creates html summary with statistics relevant to data type. For numeric values it returns central |
|
567 |
#' tendency measures, for factor returns level counts, for Date date range, for other just |
|
568 |
#' number of levels. |
|
569 |
#' |
|
570 |
#' @param x vector of any type |
|
571 |
#' @param numeric_as_factor `logical` should the numeric variable be treated as a factor |
|
572 |
#' @param dt_rows `numeric` current/latest `DT` page length |
|
573 |
#' @param outlier_definition If 0 no outliers are removed, otherwise |
|
574 |
#' outliers (those more than `outlier_definition*IQR below/above Q1/Q3` be removed) |
|
575 |
#' @return text with simple statistics. |
|
576 |
#' @keywords internal |
|
577 |
var_summary_table <- function(x, numeric_as_factor, dt_rows, outlier_definition) { |
|
578 | ! |
if (is.null(dt_rows)) { |
579 | ! |
dt_rows <- 10 |
580 |
} |
|
581 | ! |
if (is.numeric(x) && !numeric_as_factor) { |
582 | ! |
req(!any(is.infinite(x))) |
583 | ||
584 | ! |
x <- remove_outliers_from(x, outlier_definition) |
585 | ||
586 | ! |
qvals <- round(stats::quantile(x, na.rm = TRUE, probs = c(0.25, 0.5, 0.75), type = 2), 2) |
587 |
# classical central tendency measures |
|
588 | ||
589 | ! |
summary <- |
590 | ! |
data.frame( |
591 | ! |
Statistic = c("min", "Q1", "median", "mean", "Q3", "max", "sd", "n"), |
592 | ! |
Value = c( |
593 | ! |
round(min(x, na.rm = TRUE), 2), |
594 | ! |
qvals[1], |
595 | ! |
qvals[2], |
596 | ! |
round(mean(x, na.rm = TRUE), 2), |
597 | ! |
qvals[3], |
598 | ! |
round(max(x, na.rm = TRUE), 2), |
599 | ! |
round(stats::sd(x, na.rm = TRUE), 2), |
600 | ! |
length(x[!is.na(x)]) |
601 |
) |
|
602 |
) |
|
603 | ||
604 | ! |
DT::datatable(summary, rownames = FALSE, options = list(dom = "<t>", pageLength = dt_rows)) |
605 | ! |
} else if (is.factor(x) || is.character(x) || (is.numeric(x) && numeric_as_factor) || is.logical(x)) { |
606 |
# make sure factor is ordered numeric |
|
607 | ! |
if (is.numeric(x)) { |
608 | ! |
x <- factor(x, levels = sort(unique(x))) |
609 |
} |
|
610 | ||
611 | ! |
level_counts <- table(x) |
612 | ! |
max_levels_signif <- nchar(level_counts) |
613 | ||
614 | ! |
if (!all(is.na(x))) { |
615 | ! |
levels <- names(level_counts) |
616 | ! |
counts <- sprintf( |
617 | ! |
"%s [%.2f%%]", |
618 | ! |
format(level_counts, width = max_levels_signif), prop.table(level_counts) * 100 |
619 |
) |
|
620 |
} else { |
|
621 | ! |
levels <- character(0) |
622 | ! |
counts <- numeric(0) |
623 |
} |
|
624 | ||
625 | ! |
summary <- data.frame( |
626 | ! |
Level = levels, |
627 | ! |
Count = counts, |
628 | ! |
stringsAsFactors = FALSE |
629 |
) |
|
630 | ||
631 |
# sort the dataset in decreasing order of counts (needed as character variables default to alphabetical) |
|
632 | ! |
summary <- summary[order(summary$Count, decreasing = TRUE), ] |
633 | ||
634 | ! |
dom_opts <- if (nrow(summary) <= 10) { |
635 | ! |
"<t>" |
636 |
} else { |
|
637 | ! |
"<lf<t>ip>" |
638 |
} |
|
639 | ! |
DT::datatable(summary, rownames = FALSE, options = list(dom = dom_opts, pageLength = dt_rows)) |
640 | ! |
} else if (inherits(x, "Date") || inherits(x, "POSIXct") || inherits(x, "POSIXlt")) { |
641 | ! |
summary <- |
642 | ! |
data.frame( |
643 | ! |
Statistic = c("min", "median", "max"), |
644 | ! |
Value = c( |
645 | ! |
min(x, na.rm = TRUE), |
646 | ! |
stats::median(x, na.rm = TRUE), |
647 | ! |
max(x, na.rm = TRUE) |
648 |
) |
|
649 |
) |
|
650 | ! |
DT::datatable(summary, rownames = FALSE, options = list(dom = "<t>", pageLength = dt_rows)) |
651 |
} else { |
|
652 | ! |
NULL |
653 |
} |
|
654 |
} |
|
655 | ||
656 |
#' Plot variable |
|
657 |
#' |
|
658 |
#' Creates summary plot with statistics relevant to data type. |
|
659 |
#' |
|
660 |
#' @inheritParams shared_params |
|
661 |
#' @param var vector of any type to be plotted. For numeric variables it produces histogram with |
|
662 |
#' density line, for factors it creates frequency plot |
|
663 |
#' @param var_lab text describing selected variable to be displayed on the plot |
|
664 |
#' @param wrap_character (`numeric`) number of characters at which to wrap text values of `var` |
|
665 |
#' @param numeric_as_factor (`logical`) should the numeric variable be treated as a factor |
|
666 |
#' @param display_density (`logical`) should density estimation be displayed for numeric values |
|
667 |
#' @param remove_NA_hist (`logical`) should `NA` values be removed for histogram of factor like variables |
|
668 |
#' @param outlier_definition if 0 no outliers are removed, otherwise |
|
669 |
#' outliers (those more than outlier_definition*IQR below/above Q1/Q3 be removed) |
|
670 |
#' @param records_for_factor (`numeric`) if the number of factor levels is >= than this value then |
|
671 |
#' a graph of the factors isn't shown, only a list of values |
|
672 |
#' |
|
673 |
#' @return plot |
|
674 |
#' @keywords internal |
|
675 |
plot_var_summary <- function(var, |
|
676 |
var_lab, |
|
677 |
wrap_character = NULL, |
|
678 |
numeric_as_factor, |
|
679 |
display_density = is.numeric(var), |
|
680 |
remove_NA_hist = FALSE, # nolint: object_name. |
|
681 |
outlier_definition, |
|
682 |
records_for_factor, |
|
683 |
ggplot2_args) { |
|
684 | ! |
checkmate::assert_character(var_lab) |
685 | ! |
checkmate::assert_numeric(wrap_character, null.ok = TRUE) |
686 | ! |
checkmate::assert_flag(numeric_as_factor) |
687 | ! |
checkmate::assert_flag(display_density) |
688 | ! |
checkmate::assert_logical(remove_NA_hist, null.ok = TRUE) |
689 | ! |
checkmate::assert_number(outlier_definition, lower = 0, finite = TRUE) |
690 | ! |
checkmate::assert_integerish(records_for_factor, lower = 0, len = 1, any.missing = FALSE) |
691 | ! |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
692 | ||
693 | ! |
grid::grid.newpage() |
694 | ||
695 | ! |
plot_main <- if (is.factor(var) || is.character(var) || is.logical(var)) { |
696 | ! |
groups <- unique(as.character(var)) |
697 | ! |
len_groups <- length(groups) |
698 | ! |
if (len_groups >= records_for_factor) { |
699 | ! |
grid::textGrob( |
700 | ! |
sprintf( |
701 | ! |
"%s unique values\n%s:\n %s\n ...\n %s", |
702 | ! |
len_groups, |
703 | ! |
var_lab, |
704 | ! |
paste(utils::head(groups), collapse = ",\n "), |
705 | ! |
paste(utils::tail(groups), collapse = ",\n ") |
706 |
), |
|
707 | ! |
x = grid::unit(1, "line"), |
708 | ! |
y = grid::unit(1, "npc") - grid::unit(1, "line"), |
709 | ! |
just = c("left", "top") |
710 |
) |
|
711 |
} else { |
|
712 | ! |
if (!is.null(wrap_character)) { |
713 | ! |
var <- stringr::str_wrap(var, width = wrap_character) |
714 |
} |
|
715 | ! |
var <- if (isTRUE(remove_NA_hist)) as.vector(stats::na.omit(var)) else var |
716 | ! |
ggplot(data.frame(var), aes(x = forcats::fct_infreq(as.factor(var)))) + |
717 | ! |
geom_bar( |
718 | ! |
stat = "count", aes(fill = ifelse(is.na(var), "withcolor", "")), show.legend = FALSE |
719 |
) + |
|
720 | ! |
scale_fill_manual(values = c("gray50", "tan")) |
721 |
} |
|
722 | ! |
} else if (is.numeric(var)) { |
723 | ! |
validate(need(any(!is.na(var)), "No data left to visualize.")) |
724 | ||
725 |
# Filter out NA |
|
726 | ! |
var <- var[which(!is.na(var))] |
727 | ||
728 | ! |
validate(need(!any(is.infinite(var)), "Cannot display graph when data includes infinite values")) |
729 | ||
730 | ! |
if (numeric_as_factor) { |
731 | ! |
var <- factor(var) |
732 | ! |
ggplot(NULL, aes(x = var)) + |
733 | ! |
geom_histogram(stat = "count") |
734 |
} else { |
|
735 |
# remove outliers |
|
736 | ! |
if (outlier_definition != 0) { |
737 | ! |
number_records <- length(var) |
738 | ! |
var <- remove_outliers_from(var, outlier_definition) |
739 | ! |
number_outliers <- number_records - length(var) |
740 | ! |
outlier_text <- paste0( |
741 | ! |
number_outliers, " outliers (", |
742 | ! |
round(number_outliers / number_records * 100, 2), |
743 | ! |
"% of non-missing records) not shown" |
744 |
) |
|
745 | ! |
validate(need( |
746 | ! |
length(var) > 1, |
747 | ! |
"At least two data points must remain after removing outliers for this graph to be displayed" |
748 |
)) |
|
749 |
} |
|
750 |
## histogram |
|
751 | ! |
binwidth <- get_bin_width(var) |
752 | ! |
p <- ggplot(data = data.frame(var = var), aes(x = var, y = after_stat(count))) + |
753 | ! |
geom_histogram(binwidth = binwidth) + |
754 | ! |
scale_y_continuous( |
755 | ! |
sec.axis = sec_axis( |
756 | ! |
trans = ~ . / nrow(data.frame(var = var)), |
757 | ! |
labels = scales::percent, |
758 | ! |
name = "proportion (in %)" |
759 |
) |
|
760 |
) |
|
761 | ||
762 | ! |
if (display_density) { |
763 | ! |
p <- p + geom_density(aes(y = after_stat(count * binwidth))) |
764 |
} |
|
765 | ||
766 | ! |
if (outlier_definition != 0) { |
767 | ! |
p <- p + annotate( |
768 | ! |
geom = "text", |
769 | ! |
label = outlier_text, |
770 | ! |
x = Inf, y = Inf, |
771 | ! |
hjust = 1.02, vjust = 1.2, |
772 | ! |
color = "black", |
773 |
# explicitly modify geom text size according |
|
774 | ! |
size = ggplot2_args[["theme"]][["text"]][["size"]] / 3.5 |
775 |
) |
|
776 |
} |
|
777 | ! |
p |
778 |
} |
|
779 | ! |
} else if (inherits(var, "Date") || inherits(var, "POSIXct") || inherits(var, "POSIXlt")) { |
780 | ! |
var_num <- as.numeric(var) |
781 | ! |
binwidth <- get_bin_width(var_num, 1) |
782 | ! |
p <- ggplot(data = data.frame(var = var), aes(x = var, y = after_stat(count))) + |
783 | ! |
geom_histogram(binwidth = binwidth) |
784 |
} else { |
|
785 | ! |
grid::textGrob( |
786 | ! |
paste(strwrap( |
787 | ! |
utils::capture.output(utils::str(var)), |
788 | ! |
width = .9 * grid::convertWidth(grid::unit(1, "npc"), "char", TRUE) |
789 | ! |
), collapse = "\n"), |
790 | ! |
x = grid::unit(1, "line"), y = grid::unit(1, "npc") - grid::unit(1, "line"), just = c("left", "top") |
791 |
) |
|
792 |
} |
|
793 | ||
794 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
795 | ! |
labs = list(x = var_lab) |
796 |
) |
|
797 |
### |
|
798 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
799 | ! |
ggplot2_args, |
800 | ! |
module_plot = dev_ggplot2_args |
801 |
) |
|
802 | ||
803 | ! |
if (is.ggplot(plot_main)) { |
804 | ! |
if (is.numeric(var) && !numeric_as_factor) { |
805 |
# numeric not as factor |
|
806 | ! |
plot_main <- plot_main + |
807 | ! |
theme_light() + |
808 | ! |
list( |
809 | ! |
labs = do.call("labs", all_ggplot2_args$labs), |
810 | ! |
theme = do.call("theme", all_ggplot2_args$theme) |
811 |
) |
|
812 |
} else { |
|
813 |
# factor low number of levels OR numeric as factor OR Date |
|
814 | ! |
plot_main <- plot_main + |
815 | ! |
theme_light() + |
816 | ! |
list( |
817 | ! |
labs = do.call("labs", all_ggplot2_args$labs), |
818 | ! |
theme = do.call("theme", all_ggplot2_args$theme) |
819 |
) |
|
820 |
} |
|
821 | ! |
plot_main <- ggplotGrob(plot_main) |
822 |
} |
|
823 | ||
824 | ! |
grid::grid.draw(plot_main) |
825 | ! |
plot_main |
826 |
} |
|
827 | ||
828 |
is_num_var_short <- function(.unique_records_for_factor, input, data_for_analysis) { |
|
829 | ! |
length(unique(data_for_analysis()$data)) < .unique_records_for_factor && !is.null(input$numeric_as_factor) |
830 |
} |
|
831 | ||
832 |
#' Validates the variable browser inputs |
|
833 |
#' |
|
834 |
#' @param input (`session$input`) the `shiny` session input |
|
835 |
#' @param plot_var (`list`) list of a data frame and an array of variable names |
|
836 |
#' @param data (`teal_data`) the datasets passed to the module |
|
837 |
#' |
|
838 |
#' @returns `logical` TRUE if validations pass; a `shiny` validation error otherwise |
|
839 |
#' @keywords internal |
|
840 |
validate_input <- function(input, plot_var, data) { |
|
841 | ! |
reactive({ |
842 | ! |
dataset_name <- req(input$tabset_panel) |
843 | ! |
varname <- plot_var$variable[[dataset_name]] |
844 | ||
845 | ! |
validate(need(dataset_name, "No data selected")) |
846 | ! |
validate(need(varname, "No variable selected")) |
847 | ! |
df <- data()[[dataset_name]] |
848 | ! |
teal::validate_has_data(df, 1) |
849 | ! |
teal::validate_has_variable(varname = varname, data = df, "Variable not available") |
850 | ||
851 | ! |
TRUE |
852 |
}) |
|
853 |
} |
|
854 | ||
855 |
get_plotted_data <- function(input, plot_var, data) { |
|
856 | ! |
dataset_name <- input$tabset_panel |
857 | ! |
varname <- plot_var$variable[[dataset_name]] |
858 | ! |
df <- data()[[dataset_name]] |
859 | ||
860 | ! |
var_description <- teal.data::col_labels(df)[[varname]] |
861 | ! |
list(data = df[[varname]], var_description = var_description) |
862 |
} |
|
863 | ||
864 |
#' Renders the left-hand side `tabset` panel of the module |
|
865 |
#' |
|
866 |
#' @param datanames (`character`) the name of the dataset |
|
867 |
#' @param parent_dataname (`character`) the name of a parent `dataname` to filter out variables from |
|
868 |
#' @param data (`teal_data`) the object containing all datasets |
|
869 |
#' @param input (`session$input`) the `shiny` session input |
|
870 |
#' @param output (`session$output`) the `shiny` session output |
|
871 |
#' @param columns_names (`environment`) the environment containing bindings for each dataset |
|
872 |
#' @param plot_var (`list`) the list containing the currently selected dataset (tab) and its column names |
|
873 |
#' @keywords internal |
|
874 |
render_tabset_panel_content <- function(datanames, parent_dataname, output, data, input, columns_names, plot_var) { |
|
875 | ! |
lapply(datanames, render_single_tab, |
876 | ! |
input = input, |
877 | ! |
output = output, |
878 | ! |
data = data, |
879 | ! |
parent_dataname = parent_dataname, |
880 | ! |
columns_names = columns_names, |
881 | ! |
plot_var = plot_var |
882 |
) |
|
883 |
} |
|
884 | ||
885 |
#' Renders a single tab in the left-hand side tabset panel |
|
886 |
#' |
|
887 |
#' Renders a single tab in the left-hand side tabset panel. The rendered tab contains |
|
888 |
#' information about one dataset out of many presented in the module. |
|
889 |
#' |
|
890 |
#' @param dataset_name (`character`) the name of the dataset contained in the rendered tab |
|
891 |
#' @param parent_dataname (`character`) the name of a parent `dataname` to filter out variables from |
|
892 |
#' @inheritParams render_tabset_panel_content |
|
893 |
#' @keywords internal |
|
894 |
render_single_tab <- function(dataset_name, parent_dataname, output, data, input, columns_names, plot_var) { |
|
895 | ! |
render_tab_header(dataset_name, output, data) |
896 | ||
897 | ! |
render_tab_table( |
898 | ! |
dataset_name = dataset_name, |
899 | ! |
parent_dataname = parent_dataname, |
900 | ! |
output = output, |
901 | ! |
data = data, |
902 | ! |
input = input, |
903 | ! |
columns_names = columns_names, |
904 | ! |
plot_var = plot_var |
905 |
) |
|
906 |
} |
|
907 | ||
908 |
#' Renders the text headlining a single tab in the left-hand side tabset panel |
|
909 |
#' |
|
910 |
#' @param dataset_name (`character`) the name of the dataset of the tab |
|
911 |
#' @inheritParams render_tabset_panel_content |
|
912 |
#' @keywords internal |
|
913 |
render_tab_header <- function(dataset_name, output, data) { |
|
914 | ! |
dataset_ui_id <- paste0("dataset_summary_", dataset_name) |
915 | ! |
output[[dataset_ui_id]] <- renderText({ |
916 | ! |
df <- data()[[dataset_name]] |
917 | ! |
join_keys <- teal.data::join_keys(data()) |
918 | ! |
if (!is.null(join_keys)) { |
919 | ! |
key <- teal.data::join_keys(data())[dataset_name, dataset_name] |
920 |
} else { |
|
921 | ! |
key <- NULL |
922 |
} |
|
923 | ! |
sprintf( |
924 | ! |
"Dataset with %s unique key rows and %s variables", |
925 | ! |
nrow(unique(`if`(length(key) > 0, df[, key, drop = FALSE], df))), |
926 | ! |
ncol(df) |
927 |
) |
|
928 |
}) |
|
929 |
} |
|
930 | ||
931 |
#' Renders the table for a single dataset in the left-hand side tabset panel |
|
932 |
#' |
|
933 |
#' The table contains column names, column labels, |
|
934 |
#' small summary about NA values and `sparkline` (if appropriate). |
|
935 |
#' |
|
936 |
#' @param dataset_name (`character`) the name of the dataset |
|
937 |
#' @param parent_dataname (`character`) the name of a parent `dataname` to filter out variables from |
|
938 |
#' @inheritParams render_tabset_panel_content |
|
939 |
#' @keywords internal |
|
940 |
render_tab_table <- function(dataset_name, parent_dataname, output, data, input, columns_names, plot_var) { |
|
941 | ! |
table_ui_id <- paste0("variable_browser_", dataset_name) |
942 | ||
943 | ! |
output[[table_ui_id]] <- DT::renderDataTable({ |
944 | ! |
df <- data()[[dataset_name]] |
945 | ||
946 | ! |
get_vars_df <- function(input, dataset_name, parent_name, data) { |
947 | ! |
data_cols <- colnames(df) |
948 | ! |
if (isTRUE(input$show_parent_vars)) { |
949 | ! |
data_cols |
950 | ! |
} else if (dataset_name != parent_name && parent_name %in% names(data)) { |
951 | ! |
setdiff(data_cols, colnames(data()[[parent_name]])) |
952 |
} else { |
|
953 | ! |
data_cols |
954 |
} |
|
955 |
} |
|
956 | ||
957 | ! |
if (length(parent_dataname) > 0) { |
958 | ! |
df_vars <- get_vars_df(input, dataset_name, parent_dataname, data) |
959 | ! |
df <- df[df_vars] |
960 |
} |
|
961 | ||
962 | ! |
if (is.null(df) || ncol(df) == 0) { |
963 | ! |
columns_names[[dataset_name]] <- character(0) |
964 | ! |
df_output <- data.frame( |
965 | ! |
Type = character(0), |
966 | ! |
Variable = character(0), |
967 | ! |
Label = character(0), |
968 | ! |
Missings = character(0), |
969 | ! |
Sparklines = character(0), |
970 | ! |
stringsAsFactors = FALSE |
971 |
) |
|
972 |
} else { |
|
973 |
# extract data variable labels |
|
974 | ! |
labels <- teal.data::col_labels(df) |
975 | ||
976 | ! |
columns_names[[dataset_name]] <- names(labels) |
977 | ||
978 |
# calculate number of missing values |
|
979 | ! |
missings <- vapply( |
980 | ! |
df, |
981 | ! |
var_missings_info, |
982 | ! |
FUN.VALUE = character(1), |
983 | ! |
USE.NAMES = FALSE |
984 |
) |
|
985 | ||
986 |
# get icons proper for the data types |
|
987 | ! |
icons <- vapply(df, function(x) class(x)[1L], character(1L)) |
988 | ||
989 | ! |
join_keys <- teal.data::join_keys(data()) |
990 | ! |
if (!is.null(join_keys)) { |
991 | ! |
icons[intersect(join_keys[dataset_name, dataset_name], colnames(df))] <- "primary_key" |
992 |
} |
|
993 | ! |
icons <- variable_type_icons(icons) |
994 | ||
995 |
# generate sparklines |
|
996 | ! |
sparklines_html <- vapply( |
997 | ! |
df, |
998 | ! |
create_sparklines, |
999 | ! |
FUN.VALUE = character(1), |
1000 | ! |
USE.NAMES = FALSE |
1001 |
) |
|
1002 | ||
1003 | ! |
df_output <- data.frame( |
1004 | ! |
Type = icons, |
1005 | ! |
Variable = names(labels), |
1006 | ! |
Label = labels, |
1007 | ! |
Missings = missings, |
1008 | ! |
Sparklines = sparklines_html, |
1009 | ! |
stringsAsFactors = FALSE |
1010 |
) |
|
1011 |
} |
|
1012 | ||
1013 |
# Select row 1 as default / fallback |
|
1014 | ! |
selected_ix <- 1 |
1015 |
# Define starting page index (base-0 index of the first item on page |
|
1016 |
# note: in many cases it's not the item itself |
|
1017 | ! |
selected_page_ix <- 0 |
1018 | ||
1019 |
# Retrieve current selected variable if any |
|
1020 | ! |
isolated_variable <- isolate(plot_var$variable[[dataset_name]]) |
1021 | ||
1022 | ! |
if (!is.null(isolated_variable)) { |
1023 | ! |
index <- which(columns_names[[dataset_name]] == isolated_variable)[1] |
1024 | ! |
if (!is.null(index) && !is.na(index) && length(index) > 0) selected_ix <- index |
1025 |
} |
|
1026 | ||
1027 |
# Retrieve the index of the first item of the current page |
|
1028 |
# it works with varying number of entries on the page (10, 25, ...) |
|
1029 | ! |
table_id_sel <- paste0("variable_browser_", dataset_name, "_state") |
1030 | ! |
dt_state <- isolate(input[[table_id_sel]]) |
1031 | ! |
if (selected_ix != 1 && !is.null(dt_state)) { |
1032 | ! |
selected_page_ix <- floor(selected_ix / dt_state$length) * dt_state$length |
1033 |
} |
|
1034 | ||
1035 | ! |
DT::datatable( |
1036 | ! |
df_output, |
1037 | ! |
escape = FALSE, |
1038 | ! |
rownames = FALSE, |
1039 | ! |
selection = list(mode = "single", target = "row", selected = selected_ix), |
1040 | ! |
options = list( |
1041 | ! |
fnDrawCallback = htmlwidgets::JS("function() { HTMLWidgets.staticRender(); }"), |
1042 | ! |
pageLength = input[[paste0(table_ui_id, "_rows")]], |
1043 | ! |
displayStart = selected_page_ix |
1044 |
) |
|
1045 |
) |
|
1046 |
}) |
|
1047 |
} |
|
1048 | ||
1049 |
#' Creates observers updating the currently selected column |
|
1050 |
#' |
|
1051 |
#' The created observers update the column currently selected in the left-hand side |
|
1052 |
#' tabset panel. |
|
1053 |
#' |
|
1054 |
#' @note |
|
1055 |
#' Creates an observer for each dataset (each tab in the tabset panel). |
|
1056 |
#' |
|
1057 |
#' @inheritParams render_tabset_panel_content |
|
1058 |
#' @keywords internal |
|
1059 |
establish_updating_selection <- function(datanames, input, plot_var, columns_names) { |
|
1060 | ! |
lapply(datanames, function(dataset_name) { |
1061 | ! |
table_ui_id <- paste0("variable_browser_", dataset_name) |
1062 | ! |
table_id_sel <- paste0(table_ui_id, "_rows_selected") |
1063 | ! |
observeEvent(input[[table_id_sel]], { |
1064 | ! |
plot_var$data <- dataset_name |
1065 | ! |
plot_var$variable[[dataset_name]] <- columns_names[[dataset_name]][input[[table_id_sel]]] |
1066 |
}) |
|
1067 |
}) |
|
1068 |
} |
|
1069 | ||
1070 |
get_bin_width <- function(x_vec, scaling_factor = 2) { |
|
1071 | ! |
x_vec <- x_vec[!is.na(x_vec)] |
1072 | ! |
qntls <- stats::quantile(x_vec, probs = c(0.1, 0.25, 0.75, 0.9), type = 2) |
1073 | ! |
iqr <- qntls[3] - qntls[2] |
1074 | ! |
binwidth <- max(scaling_factor * iqr / length(x_vec) ^ (1 / 3), sqrt(qntls[4] - qntls[1])) # styler: off |
1075 | ! |
binwidth <- ifelse(binwidth == 0, 1, binwidth) |
1076 |
# to ensure at least two bins when variable span is very small |
|
1077 | ! |
x_span <- diff(range(x_vec)) |
1078 | ! |
if (isTRUE(x_span / binwidth >= 2)) binwidth else x_span / 2 |
1079 |
} |
|
1080 | ||
1081 |
#' Removes the outlier observation from an array |
|
1082 |
#' |
|
1083 |
#' @param var (`numeric`) a numeric vector |
|
1084 |
#' @param outlier_definition (`numeric`) if `0` then no outliers are removed, otherwise |
|
1085 |
#' outliers (those more than `outlier_definition*IQR below/above Q1/Q3`) are removed |
|
1086 |
#' @returns (`numeric`) vector without the outlier values |
|
1087 |
#' @keywords internal |
|
1088 |
remove_outliers_from <- function(var, outlier_definition) { |
|
1089 | 3x |
if (outlier_definition == 0) { |
1090 | 1x |
return(var) |
1091 |
} |
|
1092 | 2x |
q1_q3 <- stats::quantile(var, probs = c(0.25, 0.75), type = 2, na.rm = TRUE) |
1093 | 2x |
iqr <- q1_q3[2] - q1_q3[1] |
1094 | 2x |
var[var >= q1_q3[1] - outlier_definition * iqr & var <= q1_q3[2] + outlier_definition * iqr] |
1095 |
} |
|
1096 | ||
1097 | ||
1098 |
# sparklines ---- |
|
1099 | ||
1100 |
#' S3 generic for `sparkline` widget HTML |
|
1101 |
#' |
|
1102 |
#' Generates the `sparkline` HTML code corresponding to the input array. |
|
1103 |
#' For numeric variables creates a box plot, for character and factors - bar plot. |
|
1104 |
#' Produces an empty string for variables of other types. |
|
1105 |
#' |
|
1106 |
#' @param arr vector of any type and length |
|
1107 |
#' @param width `numeric` the width of the `sparkline` widget (pixels) |
|
1108 |
#' @param bar_spacing `numeric` the spacing between the bars (in pixels) |
|
1109 |
#' @param bar_width `numeric` the width of the bars (in pixels) |
|
1110 |
#' @param ... `list` additional options passed to bar plots of `jquery.sparkline`; |
|
1111 |
#' see [`jquery.sparkline docs`](https://omnipotent.net/jquery.sparkline/#common) |
|
1112 |
#' |
|
1113 |
#' @return Character string containing HTML code of the `sparkline` HTML widget. |
|
1114 |
#' @keywords internal |
|
1115 |
create_sparklines <- function(arr, width = 150, ...) { |
|
1116 | ! |
if (all(is.null(arr))) { |
1117 | ! |
return("") |
1118 |
} |
|
1119 | ! |
UseMethod("create_sparklines") |
1120 |
} |
|
1121 | ||
1122 |
#' @rdname create_sparklines |
|
1123 |
#' @keywords internal |
|
1124 |
#' @export |
|
1125 |
create_sparklines.logical <- function(arr, ...) { |
|
1126 | ! |
create_sparklines(as.factor(arr)) |
1127 |
} |
|
1128 | ||
1129 |
#' @rdname create_sparklines |
|
1130 |
#' @keywords internal |
|
1131 |
#' @export |
|
1132 |
create_sparklines.numeric <- function(arr, width = 150, ...) { |
|
1133 | ! |
if (any(is.infinite(arr))) { |
1134 | ! |
return(as.character(tags$code("infinite values", class = "text-blue"))) |
1135 |
} |
|
1136 | ! |
if (length(arr) > 100000) { |
1137 | ! |
return(as.character(tags$code("Too many rows (>100000)", class = "text-blue"))) |
1138 |
} |
|
1139 | ||
1140 | ! |
arr <- arr[!is.na(arr)] |
1141 | ! |
sparkline::spk_chr(unname(arr), type = "box", width = width, ...) |
1142 |
} |
|
1143 | ||
1144 |
#' @rdname create_sparklines |
|
1145 |
#' @keywords internal |
|
1146 |
#' @export |
|
1147 |
create_sparklines.character <- function(arr, ...) { |
|
1148 | ! |
return(create_sparklines(as.factor(arr))) |
1149 |
} |
|
1150 | ||
1151 | ||
1152 |
#' @rdname create_sparklines |
|
1153 |
#' @keywords internal |
|
1154 |
#' @export |
|
1155 |
create_sparklines.factor <- function(arr, width = 150, bar_spacing = 5, bar_width = 20, ...) { |
|
1156 | ! |
decreasing_order <- TRUE |
1157 | ||
1158 | ! |
counts <- table(arr) |
1159 | ! |
if (length(counts) >= 100) { |
1160 | ! |
return(as.character(tags$code("> 99 levels", class = "text-blue"))) |
1161 | ! |
} else if (length(counts) == 0) { |
1162 | ! |
return(as.character(tags$code("no levels", class = "text-blue"))) |
1163 | ! |
} else if (length(counts) == 1) { |
1164 | ! |
return(as.character(tags$code("one level", class = "text-blue"))) |
1165 |
} |
|
1166 | ||
1167 |
# Summarize the occurences of different levels |
|
1168 |
# and get the maximum and minimum number of occurences |
|
1169 |
# This is needed for the sparkline to correctly display the bar plots |
|
1170 |
# Otherwise they are cropped |
|
1171 | ! |
counts <- sort(counts, decreasing = decreasing_order, method = "radix") |
1172 | ! |
max_value <- if (decreasing_order) counts[1] else counts[length[counts]] |
1173 | ! |
max_value <- unname(max_value) |
1174 | ||
1175 | ! |
sparkline::spk_chr( |
1176 | ! |
unname(counts), |
1177 | ! |
type = "bar", |
1178 | ! |
chartRangeMin = 0, |
1179 | ! |
chartRangeMax = max_value, |
1180 | ! |
width = width, |
1181 | ! |
barWidth = bar_width, |
1182 | ! |
barSpacing = bar_spacing, |
1183 | ! |
tooltipFormatter = custom_sparkline_formatter(names(counts), as.vector(counts)) |
1184 |
) |
|
1185 |
} |
|
1186 | ||
1187 |
#' @rdname create_sparklines |
|
1188 |
#' @keywords internal |
|
1189 |
#' @export |
|
1190 |
create_sparklines.Date <- function(arr, width = 150, bar_spacing = 5, bar_width = 20, ...) { |
|
1191 | ! |
arr_num <- as.numeric(arr) |
1192 | ! |
arr_num <- sort(arr_num, decreasing = FALSE, method = "radix") |
1193 | ! |
binwidth <- get_bin_width(arr_num, 1) |
1194 | ! |
bins <- floor(diff(range(arr_num)) / binwidth) + 1 |
1195 | ! |
if (all(is.na(bins))) { |
1196 | ! |
return(as.character(tags$code("only NA", class = "text-blue"))) |
1197 | ! |
} else if (bins == 1) { |
1198 | ! |
return(as.character(tags$code("one date", class = "text-blue"))) |
1199 |
} |
|
1200 | ! |
counts <- as.vector(unname(base::table(cut(arr_num, breaks = bins)))) |
1201 | ! |
max_value <- max(counts) |
1202 | ||
1203 | ! |
start_bins <- as.integer(seq(1, length(arr_num), length.out = bins)) |
1204 | ! |
labels_start <- as.character(as.Date(arr_num[start_bins], origin = as.Date("1970-01-01"))) |
1205 | ! |
labels <- paste("Start:", labels_start) |
1206 | ||
1207 | ! |
sparkline::spk_chr( |
1208 | ! |
unname(counts), |
1209 | ! |
type = "bar", |
1210 | ! |
chartRangeMin = 0, |
1211 | ! |
chartRangeMax = max_value, |
1212 | ! |
width = width, |
1213 | ! |
barWidth = bar_width, |
1214 | ! |
barSpacing = bar_spacing, |
1215 | ! |
tooltipFormatter = custom_sparkline_formatter(labels, counts) |
1216 |
) |
|
1217 |
} |
|
1218 | ||
1219 |
#' @rdname create_sparklines |
|
1220 |
#' @keywords internal |
|
1221 |
#' @export |
|
1222 |
create_sparklines.POSIXct <- function(arr, width = 150, bar_spacing = 5, bar_width = 20, ...) { |
|
1223 | ! |
arr_num <- as.numeric(arr) |
1224 | ! |
arr_num <- sort(arr_num, decreasing = FALSE, method = "radix") |
1225 | ! |
binwidth <- get_bin_width(arr_num, 1) |
1226 | ! |
bins <- floor(diff(range(arr_num)) / binwidth) + 1 |
1227 | ! |
if (all(is.na(bins))) { |
1228 | ! |
return(as.character(tags$code("only NA", class = "text-blue"))) |
1229 | ! |
} else if (bins == 1) { |
1230 | ! |
return(as.character(tags$code("one date-time", class = "text-blue"))) |
1231 |
} |
|
1232 | ! |
counts <- as.vector(unname(base::table(cut(arr_num, breaks = bins)))) |
1233 | ! |
max_value <- max(counts) |
1234 | ||
1235 | ! |
start_bins <- as.integer(seq(1, length(arr_num), length.out = bins)) |
1236 | ! |
labels_start <- as.character(format(as.POSIXct(arr_num[start_bins], origin = as.Date("1970-01-01")), "%Y-%m-%d")) |
1237 | ! |
labels <- paste("Start:", labels_start) |
1238 | ||
1239 | ! |
sparkline::spk_chr( |
1240 | ! |
unname(counts), |
1241 | ! |
type = "bar", |
1242 | ! |
chartRangeMin = 0, |
1243 | ! |
chartRangeMax = max_value, |
1244 | ! |
width = width, |
1245 | ! |
barWidth = bar_width, |
1246 | ! |
barSpacing = bar_spacing, |
1247 | ! |
tooltipFormatter = custom_sparkline_formatter(labels, counts) |
1248 |
) |
|
1249 |
} |
|
1250 | ||
1251 |
#' @rdname create_sparklines |
|
1252 |
#' @keywords internal |
|
1253 |
#' @export |
|
1254 |
create_sparklines.POSIXlt <- function(arr, width = 150, bar_spacing = 5, bar_width = 20, ...) { |
|
1255 | ! |
arr_num <- as.numeric(arr) |
1256 | ! |
arr_num <- sort(arr_num, decreasing = FALSE, method = "radix") |
1257 | ! |
binwidth <- get_bin_width(arr_num, 1) |
1258 | ! |
bins <- floor(diff(range(arr_num)) / binwidth) + 1 |
1259 | ! |
if (all(is.na(bins))) { |
1260 | ! |
return(as.character(tags$code("only NA", class = "text-blue"))) |
1261 | ! |
} else if (bins == 1) { |
1262 | ! |
return(as.character(tags$code("one date-time", class = "text-blue"))) |
1263 |
} |
|
1264 | ! |
counts <- as.vector(unname(base::table(cut(arr_num, breaks = bins)))) |
1265 | ! |
max_value <- max(counts) |
1266 | ||
1267 | ! |
start_bins <- as.integer(seq(1, length(arr_num), length.out = bins)) |
1268 | ! |
labels_start <- as.character(format(as.POSIXct(arr_num[start_bins], origin = as.Date("1970-01-01")), "%Y-%m-%d")) |
1269 | ! |
labels <- paste("Start:", labels_start) |
1270 | ||
1271 | ! |
sparkline::spk_chr( |
1272 | ! |
unname(counts), |
1273 | ! |
type = "bar", |
1274 | ! |
chartRangeMin = 0, |
1275 | ! |
chartRangeMax = max_value, |
1276 | ! |
width = width, |
1277 | ! |
barWidth = bar_width, |
1278 | ! |
barSpacing = bar_spacing, |
1279 | ! |
tooltipFormatter = custom_sparkline_formatter(labels, counts) |
1280 |
) |
|
1281 |
} |
|
1282 | ||
1283 |
#' @rdname create_sparklines |
|
1284 |
#' @keywords internal |
|
1285 |
#' @export |
|
1286 |
create_sparklines.default <- function(arr, width = 150, ...) { |
|
1287 | ! |
as.character(tags$code("unsupported variable type", class = "text-blue")) |
1288 |
} |
|
1289 | ||
1290 |
custom_sparkline_formatter <- function(labels, counts) { |
|
1291 | ! |
htmlwidgets::JS( |
1292 | ! |
sprintf( |
1293 | ! |
"function(sparkline, options, field) { |
1294 | ! |
return 'ID: ' + %s[field[0].offset] + '<br>' + 'Count: ' + %s[field[0].offset]; |
1295 |
}", |
|
1296 | ! |
jsonlite::toJSON(labels), |
1297 | ! |
jsonlite::toJSON(counts) |
1298 |
) |
|
1299 |
) |
|
1300 |
} |
1 |
#' `teal` module: Scatterplot |
|
2 |
#' |
|
3 |
#' Generates a customizable scatterplot using `ggplot2`. |
|
4 |
#' This module allows users to select variables for the x and y axes, |
|
5 |
#' color and size encodings, faceting options, and more. It supports log transformations, |
|
6 |
#' trend line additions, and dynamic adjustments of point opacity and size through UI controls. |
|
7 |
#' |
|
8 |
#' @note For more examples, please see the vignette "Using scatterplot" via |
|
9 |
#' `vignette("using-scatterplot", package = "teal.modules.general")`. |
|
10 |
#' |
|
11 |
#' @inheritParams teal::module |
|
12 |
#' @inheritParams shared_params |
|
13 |
#' @param x (`data_extract_spec` or `list` of multiple `data_extract_spec`) Specifies |
|
14 |
#' variable names selected to plot along the x-axis by default. |
|
15 |
#' @param y (`data_extract_spec` or `list` of multiple `data_extract_spec`) Specifies |
|
16 |
#' variable names selected to plot along the y-axis by default. |
|
17 |
#' @param color_by (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
18 |
#' defines the color encoding. If `NULL` then no color encoding option will be displayed. |
|
19 |
#' @param size_by (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
20 |
#' defines the point size encoding. If `NULL` then no size encoding option will be displayed. |
|
21 |
#' @param row_facet (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
22 |
#' specifies the variable(s) for faceting rows. |
|
23 |
#' @param col_facet (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
24 |
#' specifies the variable(s) for faceting columns. |
|
25 |
#' @param shape (`character`) optional, character vector with the names of the |
|
26 |
#' shape, e.g. `c("triangle", "square", "circle")`. It defaults to `shape_names`. This is a complete list from |
|
27 |
#' `vignette("ggplot2-specs", package="ggplot2")`. |
|
28 |
#' @param max_deg (`integer`) optional, maximum degree for the polynomial trend line. Must not be less than 1. |
|
29 |
#' @param table_dec (`integer`) optional, number of decimal places used to round numeric values in the table. |
|
30 |
#' |
|
31 |
#' @inherit shared_params return |
|
32 |
#' |
|
33 |
#' @section Decorating Module: |
|
34 |
#' |
|
35 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
36 |
#' - `plot` (`ggplot2`) |
|
37 |
#' |
|
38 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
39 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
40 |
#' See code snippet below: |
|
41 |
#' |
|
42 |
#' ``` |
|
43 |
#' tm_g_scatterplot( |
|
44 |
#' ..., # arguments for module |
|
45 |
#' decorators = list( |
|
46 |
#' plot = teal_transform_module(...) # applied to the `plot` output |
|
47 |
#' ) |
|
48 |
#' ) |
|
49 |
#' ``` |
|
50 |
#' |
|
51 |
#' For additional details and examples of decorators, refer to the vignette |
|
52 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
53 |
#' |
|
54 |
#' |
|
55 |
#' @examplesShinylive |
|
56 |
#' library(teal.modules.general) |
|
57 |
#' interactive <- function() TRUE |
|
58 |
#' {{ next_example }} |
|
59 |
# nolint start: line_length_linter. |
|
60 |
#' @examples |
|
61 |
# nolint end: line_length_linter. |
|
62 |
#' # general data example |
|
63 |
#' data <- teal_data() |
|
64 |
#' data <- within(data, { |
|
65 |
#' require(nestcolor) |
|
66 |
#' CO2 <- CO2 |
|
67 |
#' }) |
|
68 |
#' |
|
69 |
#' app <- init( |
|
70 |
#' data = data, |
|
71 |
#' modules = modules( |
|
72 |
#' tm_g_scatterplot( |
|
73 |
#' label = "Scatterplot Choices", |
|
74 |
#' x = data_extract_spec( |
|
75 |
#' dataname = "CO2", |
|
76 |
#' select = select_spec( |
|
77 |
#' label = "Select variable:", |
|
78 |
#' choices = variable_choices(data[["CO2"]], c("conc", "uptake")), |
|
79 |
#' selected = "conc", |
|
80 |
#' multiple = FALSE, |
|
81 |
#' fixed = FALSE |
|
82 |
#' ) |
|
83 |
#' ), |
|
84 |
#' y = data_extract_spec( |
|
85 |
#' dataname = "CO2", |
|
86 |
#' select = select_spec( |
|
87 |
#' label = "Select variable:", |
|
88 |
#' choices = variable_choices(data[["CO2"]], c("conc", "uptake")), |
|
89 |
#' selected = "uptake", |
|
90 |
#' multiple = FALSE, |
|
91 |
#' fixed = FALSE |
|
92 |
#' ) |
|
93 |
#' ), |
|
94 |
#' color_by = data_extract_spec( |
|
95 |
#' dataname = "CO2", |
|
96 |
#' select = select_spec( |
|
97 |
#' label = "Select variable:", |
|
98 |
#' choices = variable_choices( |
|
99 |
#' data[["CO2"]], |
|
100 |
#' c("Plant", "Type", "Treatment", "conc", "uptake") |
|
101 |
#' ), |
|
102 |
#' selected = NULL, |
|
103 |
#' multiple = FALSE, |
|
104 |
#' fixed = FALSE |
|
105 |
#' ) |
|
106 |
#' ), |
|
107 |
#' size_by = data_extract_spec( |
|
108 |
#' dataname = "CO2", |
|
109 |
#' select = select_spec( |
|
110 |
#' label = "Select variable:", |
|
111 |
#' choices = variable_choices(data[["CO2"]], c("conc", "uptake")), |
|
112 |
#' selected = "uptake", |
|
113 |
#' multiple = FALSE, |
|
114 |
#' fixed = FALSE |
|
115 |
#' ) |
|
116 |
#' ), |
|
117 |
#' row_facet = data_extract_spec( |
|
118 |
#' dataname = "CO2", |
|
119 |
#' select = select_spec( |
|
120 |
#' label = "Select variable:", |
|
121 |
#' choices = variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment")), |
|
122 |
#' selected = NULL, |
|
123 |
#' multiple = FALSE, |
|
124 |
#' fixed = FALSE |
|
125 |
#' ) |
|
126 |
#' ), |
|
127 |
#' col_facet = data_extract_spec( |
|
128 |
#' dataname = "CO2", |
|
129 |
#' select = select_spec( |
|
130 |
#' label = "Select variable:", |
|
131 |
#' choices = variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment")), |
|
132 |
#' selected = NULL, |
|
133 |
#' multiple = FALSE, |
|
134 |
#' fixed = FALSE |
|
135 |
#' ) |
|
136 |
#' ) |
|
137 |
#' ) |
|
138 |
#' ) |
|
139 |
#' ) |
|
140 |
#' if (interactive()) { |
|
141 |
#' shinyApp(app$ui, app$server) |
|
142 |
#' } |
|
143 |
#' |
|
144 |
#' @examplesShinylive |
|
145 |
#' library(teal.modules.general) |
|
146 |
#' interactive <- function() TRUE |
|
147 |
#' {{ next_example }} |
|
148 |
# nolint start: line_length_linter. |
|
149 |
#' @examples |
|
150 |
# nolint end: line_length_linter. |
|
151 |
#' # CDISC data example |
|
152 |
#' data <- teal_data() |
|
153 |
#' data <- within(data, { |
|
154 |
#' require(nestcolor) |
|
155 |
#' ADSL <- teal.data::rADSL |
|
156 |
#' }) |
|
157 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
158 |
#' |
|
159 |
#' app <- init( |
|
160 |
#' data = data, |
|
161 |
#' modules = modules( |
|
162 |
#' tm_g_scatterplot( |
|
163 |
#' label = "Scatterplot Choices", |
|
164 |
#' x = data_extract_spec( |
|
165 |
#' dataname = "ADSL", |
|
166 |
#' select = select_spec( |
|
167 |
#' label = "Select variable:", |
|
168 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1", "BMRKR2")), |
|
169 |
#' selected = "AGE", |
|
170 |
#' multiple = FALSE, |
|
171 |
#' fixed = FALSE |
|
172 |
#' ) |
|
173 |
#' ), |
|
174 |
#' y = data_extract_spec( |
|
175 |
#' dataname = "ADSL", |
|
176 |
#' select = select_spec( |
|
177 |
#' label = "Select variable:", |
|
178 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1", "BMRKR2")), |
|
179 |
#' selected = "BMRKR1", |
|
180 |
#' multiple = FALSE, |
|
181 |
#' fixed = FALSE |
|
182 |
#' ) |
|
183 |
#' ), |
|
184 |
#' color_by = data_extract_spec( |
|
185 |
#' dataname = "ADSL", |
|
186 |
#' select = select_spec( |
|
187 |
#' label = "Select variable:", |
|
188 |
#' choices = variable_choices( |
|
189 |
#' data[["ADSL"]], |
|
190 |
#' c("AGE", "BMRKR1", "BMRKR2", "RACE", "REGION1") |
|
191 |
#' ), |
|
192 |
#' selected = NULL, |
|
193 |
#' multiple = FALSE, |
|
194 |
#' fixed = FALSE |
|
195 |
#' ) |
|
196 |
#' ), |
|
197 |
#' size_by = data_extract_spec( |
|
198 |
#' dataname = "ADSL", |
|
199 |
#' select = select_spec( |
|
200 |
#' label = "Select variable:", |
|
201 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1")), |
|
202 |
#' selected = "AGE", |
|
203 |
#' multiple = FALSE, |
|
204 |
#' fixed = FALSE |
|
205 |
#' ) |
|
206 |
#' ), |
|
207 |
#' row_facet = data_extract_spec( |
|
208 |
#' dataname = "ADSL", |
|
209 |
#' select = select_spec( |
|
210 |
#' label = "Select variable:", |
|
211 |
#' choices = variable_choices(data[["ADSL"]], c("BMRKR2", "RACE", "REGION1")), |
|
212 |
#' selected = NULL, |
|
213 |
#' multiple = FALSE, |
|
214 |
#' fixed = FALSE |
|
215 |
#' ) |
|
216 |
#' ), |
|
217 |
#' col_facet = data_extract_spec( |
|
218 |
#' dataname = "ADSL", |
|
219 |
#' select = select_spec( |
|
220 |
#' label = "Select variable:", |
|
221 |
#' choices = variable_choices(data[["ADSL"]], c("BMRKR2", "RACE", "REGION1")), |
|
222 |
#' selected = NULL, |
|
223 |
#' multiple = FALSE, |
|
224 |
#' fixed = FALSE |
|
225 |
#' ) |
|
226 |
#' ) |
|
227 |
#' ) |
|
228 |
#' ) |
|
229 |
#' ) |
|
230 |
#' if (interactive()) { |
|
231 |
#' shinyApp(app$ui, app$server) |
|
232 |
#' } |
|
233 |
#' |
|
234 |
#' @export |
|
235 |
#' |
|
236 |
tm_g_scatterplot <- function(label = "Scatterplot", |
|
237 |
x, |
|
238 |
y, |
|
239 |
color_by = NULL, |
|
240 |
size_by = NULL, |
|
241 |
row_facet = NULL, |
|
242 |
col_facet = NULL, |
|
243 |
plot_height = c(600, 200, 2000), |
|
244 |
plot_width = NULL, |
|
245 |
alpha = c(1, 0, 1), |
|
246 |
shape = shape_names, |
|
247 |
size = c(5, 1, 15), |
|
248 |
max_deg = 5L, |
|
249 |
rotate_xaxis_labels = FALSE, |
|
250 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
251 |
pre_output = NULL, |
|
252 |
post_output = NULL, |
|
253 |
table_dec = 4, |
|
254 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
255 |
transformators = list(), |
|
256 |
decorators = list()) { |
|
257 | ! |
message("Initializing tm_g_scatterplot") |
258 | ||
259 |
# Normalize the parameters |
|
260 | ! |
if (inherits(x, "data_extract_spec")) x <- list(x) |
261 | ! |
if (inherits(y, "data_extract_spec")) y <- list(y) |
262 | ! |
if (inherits(color_by, "data_extract_spec")) color_by <- list(color_by) |
263 | ! |
if (inherits(size_by, "data_extract_spec")) size_by <- list(size_by) |
264 | ! |
if (inherits(row_facet, "data_extract_spec")) row_facet <- list(row_facet) |
265 | ! |
if (inherits(col_facet, "data_extract_spec")) col_facet <- list(col_facet) |
266 | ! |
if (is.double(max_deg)) max_deg <- as.integer(max_deg) |
267 | ||
268 |
# Start of assertions |
|
269 | ! |
checkmate::assert_string(label) |
270 | ! |
checkmate::assert_list(x, types = "data_extract_spec") |
271 | ! |
checkmate::assert_list(y, types = "data_extract_spec") |
272 | ! |
checkmate::assert_list(color_by, types = "data_extract_spec", null.ok = TRUE) |
273 | ! |
checkmate::assert_list(size_by, types = "data_extract_spec", null.ok = TRUE) |
274 | ||
275 | ! |
checkmate::assert_list(row_facet, types = "data_extract_spec", null.ok = TRUE) |
276 | ! |
assert_single_selection(row_facet) |
277 | ||
278 | ! |
checkmate::assert_list(col_facet, types = "data_extract_spec", null.ok = TRUE) |
279 | ! |
assert_single_selection(col_facet) |
280 | ||
281 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
282 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
283 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
284 | ! |
checkmate::assert_numeric( |
285 | ! |
plot_width[1], |
286 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
287 |
) |
|
288 | ||
289 | ! |
if (length(alpha) == 1) { |
290 | ! |
checkmate::assert_numeric(alpha, any.missing = FALSE, finite = TRUE) |
291 |
} else { |
|
292 | ! |
checkmate::assert_numeric(alpha, len = 3, any.missing = FALSE, finite = TRUE) |
293 | ! |
checkmate::assert_numeric(alpha[1], lower = alpha[2], upper = alpha[3], .var.name = "alpha") |
294 |
} |
|
295 | ||
296 | ! |
checkmate::assert_character(shape) |
297 | ||
298 | ! |
if (length(size) == 1) { |
299 | ! |
checkmate::assert_numeric(size, any.missing = FALSE, finite = TRUE) |
300 |
} else { |
|
301 | ! |
checkmate::assert_numeric(size, len = 3, any.missing = FALSE, finite = TRUE) |
302 | ! |
checkmate::assert_numeric(size[1], lower = size[2], upper = size[3], .var.name = "size") |
303 |
} |
|
304 | ||
305 | ! |
checkmate::assert_int(max_deg, lower = 1L) |
306 | ! |
checkmate::assert_flag(rotate_xaxis_labels) |
307 | ! |
ggtheme <- match.arg(ggtheme) |
308 | ||
309 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
310 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
311 | ||
312 | ! |
checkmate::assert_scalar(table_dec) |
313 | ! |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
314 | ||
315 | ! |
assert_decorators(decorators, "plot") |
316 | ||
317 |
# End of assertions |
|
318 | ||
319 |
# Make UI args |
|
320 | ! |
args <- as.list(environment()) |
321 | ||
322 | ! |
data_extract_list <- list( |
323 | ! |
x = x, |
324 | ! |
y = y, |
325 | ! |
color_by = color_by, |
326 | ! |
size_by = size_by, |
327 | ! |
row_facet = row_facet, |
328 | ! |
col_facet = col_facet |
329 |
) |
|
330 | ||
331 | ! |
ans <- module( |
332 | ! |
label = label, |
333 | ! |
server = srv_g_scatterplot, |
334 | ! |
ui = ui_g_scatterplot, |
335 | ! |
ui_args = args, |
336 | ! |
server_args = c( |
337 | ! |
data_extract_list, |
338 | ! |
list( |
339 | ! |
plot_height = plot_height, |
340 | ! |
plot_width = plot_width, |
341 | ! |
table_dec = table_dec, |
342 | ! |
ggplot2_args = ggplot2_args, |
343 | ! |
decorators = decorators |
344 |
) |
|
345 |
), |
|
346 | ! |
transformators = transformators, |
347 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
348 |
) |
|
349 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
350 | ! |
ans |
351 |
} |
|
352 | ||
353 |
# UI function for the scatterplot module |
|
354 |
ui_g_scatterplot <- function(id, ...) { |
|
355 | ! |
args <- list(...) |
356 | ! |
ns <- NS(id) |
357 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset( |
358 | ! |
args$x, args$y, args$color_by, args$size_by, args$row_facet, args$col_facet |
359 |
) |
|
360 | ||
361 | ! |
tagList( |
362 | ! |
include_css_files("custom"), |
363 | ! |
teal.widgets::standard_layout( |
364 | ! |
output = teal.widgets::white_small_well( |
365 | ! |
teal.widgets::plot_with_settings_ui(id = ns("scatter_plot")), |
366 | ! |
tags$h1(tags$strong("Selected points:"), class = "text-center font-150p"), |
367 | ! |
teal.widgets::get_dt_rows(ns("data_table"), ns("data_table_rows")), |
368 | ! |
DT::dataTableOutput(ns("data_table"), width = "100%") |
369 |
), |
|
370 | ! |
encoding = tags$div( |
371 |
### Reporter |
|
372 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
373 |
### |
|
374 | ! |
tags$label("Encodings", class = "text-primary"), |
375 | ! |
teal.transform::datanames_input(args[c("x", "y", "color_by", "size_by", "row_facet", "col_facet")]), |
376 | ! |
teal.transform::data_extract_ui( |
377 | ! |
id = ns("x"), |
378 | ! |
label = "X variable", |
379 | ! |
data_extract_spec = args$x, |
380 | ! |
is_single_dataset = is_single_dataset_value |
381 |
), |
|
382 | ! |
checkboxInput(ns("log_x"), "Use log transformation", value = FALSE), |
383 | ! |
conditionalPanel( |
384 | ! |
condition = paste0("input['", ns("log_x"), "'] == true"), |
385 | ! |
radioButtons( |
386 | ! |
ns("log_x_base"), |
387 | ! |
label = NULL, |
388 | ! |
inline = TRUE, |
389 | ! |
choices = c("Natural" = "log", "Base 10" = "log10", "Base 2" = "log2") |
390 |
) |
|
391 |
), |
|
392 | ! |
teal.transform::data_extract_ui( |
393 | ! |
id = ns("y"), |
394 | ! |
label = "Y variable", |
395 | ! |
data_extract_spec = args$y, |
396 | ! |
is_single_dataset = is_single_dataset_value |
397 |
), |
|
398 | ! |
checkboxInput(ns("log_y"), "Use log transformation", value = FALSE), |
399 | ! |
conditionalPanel( |
400 | ! |
condition = paste0("input['", ns("log_y"), "'] == true"), |
401 | ! |
radioButtons( |
402 | ! |
ns("log_y_base"), |
403 | ! |
label = NULL, |
404 | ! |
inline = TRUE, |
405 | ! |
choices = c("Natural" = "log", "Base 10" = "log10", "Base 2" = "log2") |
406 |
) |
|
407 |
), |
|
408 | ! |
if (!is.null(args$color_by)) { |
409 | ! |
teal.transform::data_extract_ui( |
410 | ! |
id = ns("color_by"), |
411 | ! |
label = "Color by variable", |
412 | ! |
data_extract_spec = args$color_by, |
413 | ! |
is_single_dataset = is_single_dataset_value |
414 |
) |
|
415 |
}, |
|
416 | ! |
if (!is.null(args$size_by)) { |
417 | ! |
teal.transform::data_extract_ui( |
418 | ! |
id = ns("size_by"), |
419 | ! |
label = "Size by variable", |
420 | ! |
data_extract_spec = args$size_by, |
421 | ! |
is_single_dataset = is_single_dataset_value |
422 |
) |
|
423 |
}, |
|
424 | ! |
if (!is.null(args$row_facet)) { |
425 | ! |
teal.transform::data_extract_ui( |
426 | ! |
id = ns("row_facet"), |
427 | ! |
label = "Row facetting", |
428 | ! |
data_extract_spec = args$row_facet, |
429 | ! |
is_single_dataset = is_single_dataset_value |
430 |
) |
|
431 |
}, |
|
432 | ! |
if (!is.null(args$col_facet)) { |
433 | ! |
teal.transform::data_extract_ui( |
434 | ! |
id = ns("col_facet"), |
435 | ! |
label = "Column facetting", |
436 | ! |
data_extract_spec = args$col_facet, |
437 | ! |
is_single_dataset = is_single_dataset_value |
438 |
) |
|
439 |
}, |
|
440 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")), |
441 | ! |
teal.widgets::panel_group( |
442 | ! |
teal.widgets::panel_item( |
443 | ! |
title = "Plot settings", |
444 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("alpha"), "Opacity:", args$alpha, ticks = FALSE), |
445 | ! |
teal.widgets::optionalSelectInput( |
446 | ! |
inputId = ns("shape"), |
447 | ! |
label = "Points shape:", |
448 | ! |
choices = args$shape, |
449 | ! |
selected = args$shape[1], |
450 | ! |
multiple = FALSE |
451 |
), |
|
452 | ! |
colourpicker::colourInput(ns("color"), "Points color:", "black"), |
453 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("size"), "Points size:", args$size, ticks = FALSE, step = .1), |
454 | ! |
checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = args$rotate_xaxis_labels), |
455 | ! |
checkboxInput(ns("add_density"), "Add marginal density", value = FALSE), |
456 | ! |
checkboxInput(ns("rug_plot"), "Include rug plot", value = FALSE), |
457 | ! |
checkboxInput(ns("show_count"), "Show N (number of observations)", value = FALSE), |
458 | ! |
shinyjs::hidden(helpText(id = ns("line_msg"), "Trendline needs numeric X and Y variables")), |
459 | ! |
teal.widgets::optionalSelectInput(ns("smoothing_degree"), "Smoothing degree", seq_len(args$max_deg)), |
460 | ! |
shinyjs::hidden(teal.widgets::optionalSelectInput(ns("color_sub"), label = "", multiple = TRUE)), |
461 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("ci"), "Confidence", c(.95, .8, .99), ticks = FALSE), |
462 | ! |
shinyjs::hidden(checkboxInput(ns("show_form"), "Show formula", value = TRUE)), |
463 | ! |
shinyjs::hidden(checkboxInput(ns("show_r2"), "Show adj-R Squared", value = TRUE)), |
464 | ! |
uiOutput(ns("num_na_removed")), |
465 | ! |
tags$div( |
466 | ! |
id = ns("label_pos"), |
467 | ! |
tags$div(tags$strong("Stats position")), |
468 | ! |
tags$div(class = "inline-block w-10", helpText("Left")), |
469 | ! |
tags$div( |
470 | ! |
class = "inline-block w-70", |
471 | ! |
teal.widgets::optionalSliderInput( |
472 | ! |
ns("pos"), |
473 | ! |
label = NULL, |
474 | ! |
min = 0, max = 1, value = .99, ticks = FALSE, step = .01 |
475 |
) |
|
476 |
), |
|
477 | ! |
tags$div(class = "inline-block w-10", helpText("Right")) |
478 |
), |
|
479 | ! |
teal.widgets::optionalSliderInput( |
480 | ! |
ns("label_size"), "Stats font size", |
481 | ! |
min = 3, max = 10, value = 5, ticks = FALSE, step = .1 |
482 |
), |
|
483 | ! |
if (!is.null(args$row_facet) || !is.null(args$col_facet)) { |
484 | ! |
checkboxInput(ns("free_scales"), "Free scales", value = FALSE) |
485 |
}, |
|
486 | ! |
selectInput( |
487 | ! |
inputId = ns("ggtheme"), |
488 | ! |
label = "Theme (by ggplot):", |
489 | ! |
choices = ggplot_themes, |
490 | ! |
selected = args$ggtheme, |
491 | ! |
multiple = FALSE |
492 |
) |
|
493 |
) |
|
494 |
) |
|
495 |
), |
|
496 | ! |
forms = tagList( |
497 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
498 |
), |
|
499 | ! |
pre_output = args$pre_output, |
500 | ! |
post_output = args$post_output |
501 |
) |
|
502 |
) |
|
503 |
} |
|
504 | ||
505 |
# Server function for the scatterplot module |
|
506 |
srv_g_scatterplot <- function(id, |
|
507 |
data, |
|
508 |
reporter, |
|
509 |
filter_panel_api, |
|
510 |
x, |
|
511 |
y, |
|
512 |
color_by, |
|
513 |
size_by, |
|
514 |
row_facet, |
|
515 |
col_facet, |
|
516 |
plot_height, |
|
517 |
plot_width, |
|
518 |
table_dec, |
|
519 |
ggplot2_args, |
|
520 |
decorators) { |
|
521 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
522 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
523 | ! |
checkmate::assert_class(data, "reactive") |
524 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
525 | ! |
moduleServer(id, function(input, output, session) { |
526 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
527 | ||
528 | ! |
data_extract <- list( |
529 | ! |
x = x, |
530 | ! |
y = y, |
531 | ! |
color_by = color_by, |
532 | ! |
size_by = size_by, |
533 | ! |
row_facet = row_facet, |
534 | ! |
col_facet = col_facet |
535 |
) |
|
536 | ||
537 | ! |
rule_diff <- function(other) { |
538 | ! |
function(value) { |
539 | ! |
othervalue <- selector_list()[[other]]()[["select"]] |
540 | ! |
if (!is.null(othervalue)) { |
541 | ! |
if (identical(value, othervalue)) { |
542 | ! |
"Row and column facetting variables must be different." |
543 |
} |
|
544 |
} |
|
545 |
} |
|
546 |
} |
|
547 | ||
548 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
549 | ! |
data_extract = data_extract, |
550 | ! |
datasets = data, |
551 | ! |
select_validation_rule = list( |
552 | ! |
x = ~ if (length(.) != 1) "Please select exactly one x var.", |
553 | ! |
y = ~ if (length(.) != 1) "Please select exactly one y var.", |
554 | ! |
color_by = ~ if (length(.) > 1) "There cannot be more than 1 color variable.", |
555 | ! |
size_by = ~ if (length(.) > 1) "There cannot be more than 1 size variable.", |
556 | ! |
row_facet = shinyvalidate::compose_rules( |
557 | ! |
shinyvalidate::sv_optional(), |
558 | ! |
rule_diff("col_facet") |
559 |
), |
|
560 | ! |
col_facet = shinyvalidate::compose_rules( |
561 | ! |
shinyvalidate::sv_optional(), |
562 | ! |
rule_diff("row_facet") |
563 |
) |
|
564 |
) |
|
565 |
) |
|
566 | ||
567 | ! |
iv_r <- reactive({ |
568 | ! |
iv_facet <- shinyvalidate::InputValidator$new() |
569 | ! |
iv <- shinyvalidate::InputValidator$new() |
570 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
571 |
}) |
|
572 | ! |
iv_facet <- shinyvalidate::InputValidator$new() |
573 | ! |
iv_facet$add_rule("add_density", ~ if ( |
574 | ! |
isTRUE(.) && |
575 |
( |
|
576 | ! |
length(selector_list()$row_facet()$select) > 0L || |
577 | ! |
length(selector_list()$col_facet()$select) > 0L |
578 |
) |
|
579 |
) { |
|
580 | ! |
"Cannot add marginal density when Row or Column facetting has been selected" |
581 |
}) |
|
582 | ! |
iv_facet$enable() |
583 | ||
584 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
585 | ! |
selector_list = selector_list, |
586 | ! |
datasets = data, |
587 | ! |
merge_function = "dplyr::inner_join" |
588 |
) |
|
589 | ||
590 | ! |
anl_merged_q <- reactive({ |
591 | ! |
req(anl_merged_input()) |
592 | ! |
data() %>% |
593 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) %>% |
594 | ! |
teal.code::eval_code(quote(ANL)) # used to display table when running show-r-code code |
595 |
}) |
|
596 | ||
597 | ! |
merged <- list( |
598 | ! |
anl_input_r = anl_merged_input, |
599 | ! |
anl_q_r = anl_merged_q |
600 |
) |
|
601 | ||
602 | ! |
trend_line_is_applicable <- reactive({ |
603 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
604 | ! |
x_var <- as.vector(merged$anl_input_r()$columns_source$x) |
605 | ! |
y_var <- as.vector(merged$anl_input_r()$columns_source$y) |
606 | ! |
length(x_var) > 0 && length(y_var) > 0 && is.numeric(ANL[[x_var]]) && is.numeric(ANL[[y_var]]) |
607 |
}) |
|
608 | ||
609 | ! |
add_trend_line <- reactive({ |
610 | ! |
smoothing_degree <- as.integer(input$smoothing_degree) |
611 | ! |
trend_line_is_applicable() && length(smoothing_degree) > 0 |
612 |
}) |
|
613 | ||
614 | ! |
if (!is.null(color_by)) { |
615 | ! |
observeEvent( |
616 | ! |
eventExpr = merged$anl_input_r()$columns_source$color_by, |
617 | ! |
handlerExpr = { |
618 | ! |
color_by_var <- as.vector(merged$anl_input_r()$columns_source$color_by) |
619 | ! |
if (length(color_by_var) > 0) { |
620 | ! |
shinyjs::hide("color") |
621 |
} else { |
|
622 | ! |
shinyjs::show("color") |
623 |
} |
|
624 |
} |
|
625 |
) |
|
626 |
} |
|
627 | ||
628 | ! |
output$num_na_removed <- renderUI({ |
629 | ! |
if (add_trend_line()) { |
630 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
631 | ! |
x_var <- as.vector(merged$anl_input_r()$columns_source$x) |
632 | ! |
y_var <- as.vector(merged$anl_input_r()$columns_source$y) |
633 | ! |
if ((num_total_na <- nrow(ANL) - nrow(stats::na.omit(ANL[, c(x_var, y_var)]))) > 0) { |
634 | ! |
tags$div(paste(num_total_na, "row(s) with missing values were removed"), tags$hr()) |
635 |
} |
|
636 |
} |
|
637 |
}) |
|
638 | ||
639 | ! |
observeEvent( |
640 | ! |
eventExpr = merged$anl_input_r()$columns_source[c("col_facet", "row_facet")], |
641 | ! |
handlerExpr = { |
642 | ! |
if ( |
643 | ! |
length(merged$anl_input_r()$columns_source$col_facet) == 0 && |
644 | ! |
length(merged$anl_input_r()$columns_source$row_facet) == 0 |
645 |
) { |
|
646 | ! |
shinyjs::hide("free_scales") |
647 |
} else { |
|
648 | ! |
shinyjs::show("free_scales") |
649 |
} |
|
650 |
} |
|
651 |
) |
|
652 | ||
653 | ! |
output_q <- reactive({ |
654 | ! |
teal::validate_inputs(iv_r(), iv_facet) |
655 | ||
656 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
657 | ||
658 | ! |
x_var <- as.vector(merged$anl_input_r()$columns_source$x) |
659 | ! |
y_var <- as.vector(merged$anl_input_r()$columns_source$y) |
660 | ! |
color_by_var <- as.vector(merged$anl_input_r()$columns_source$color_by) |
661 | ! |
size_by_var <- as.vector(merged$anl_input_r()$columns_source$size_by) |
662 | ! |
row_facet_name <- if (length(merged$anl_input_r()$columns_source$row_facet) == 0) { |
663 | ! |
character(0) |
664 |
} else { |
|
665 | ! |
as.vector(merged$anl_input_r()$columns_source$row_facet) |
666 |
} |
|
667 | ! |
col_facet_name <- if (length(merged$anl_input_r()$columns_source$col_facet) == 0) { |
668 | ! |
character(0) |
669 |
} else { |
|
670 | ! |
as.vector(merged$anl_input_r()$columns_source$col_facet) |
671 |
} |
|
672 | ! |
alpha <- input$alpha |
673 | ! |
size <- input$size |
674 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
675 | ! |
add_density <- input$add_density |
676 | ! |
ggtheme <- input$ggtheme |
677 | ! |
rug_plot <- input$rug_plot |
678 | ! |
color <- input$color |
679 | ! |
shape <- `if`(is.null(input$shape) || identical(input$shape, ""), "circle", input$shape) |
680 | ! |
smoothing_degree <- as.integer(input$smoothing_degree) |
681 | ! |
ci <- input$ci |
682 | ||
683 | ! |
log_x <- input$log_x |
684 | ! |
log_y <- input$log_y |
685 | ||
686 | ! |
validate(need( |
687 | ! |
length(row_facet_name) == 0 || inherits(ANL[[row_facet_name]], c("character", "factor", "Date", "integer")), |
688 | ! |
"`Row facetting` variable must be of class `character`, `factor`, `Date`, or `integer`" |
689 |
)) |
|
690 | ! |
validate(need( |
691 | ! |
length(col_facet_name) == 0 || inherits(ANL[[col_facet_name]], c("character", "factor", "Date", "integer")), |
692 | ! |
"`Column facetting` variable must be of class `character`, `factor`, `Date`, or `integer`" |
693 |
)) |
|
694 | ||
695 | ! |
if (add_density && length(color_by_var) > 0) { |
696 | ! |
validate(need( |
697 | ! |
!is.numeric(ANL[[color_by_var]]), |
698 | ! |
"Marginal plots cannot be produced when the points are colored by numeric variables. |
699 | ! |
\n Uncheck the 'Add marginal density' checkbox to display the plot." |
700 |
)) |
|
701 | ! |
validate(need( |
702 |
!( |
|
703 | ! |
inherits(ANL[[color_by_var]], "Date") || |
704 | ! |
inherits(ANL[[color_by_var]], "POSIXct") || |
705 | ! |
inherits(ANL[[color_by_var]], "POSIXlt") |
706 |
), |
|
707 | ! |
"Marginal plots cannot be produced when the points are colored by Date or POSIX variables. |
708 | ! |
\n Uncheck the 'Add marginal density' checkbox to display the plot." |
709 |
)) |
|
710 |
} |
|
711 | ||
712 | ! |
teal::validate_has_data(ANL[, c(x_var, y_var)], 10, complete = TRUE, allow_inf = FALSE) |
713 | ||
714 | ! |
if (log_x) { |
715 | ! |
validate( |
716 | ! |
need( |
717 | ! |
is.numeric(ANL[[x_var]]) && all( |
718 | ! |
ANL[[x_var]] > 0 | is.na(ANL[[x_var]]) |
719 |
), |
|
720 | ! |
"X variable can only be log transformed if variable is numeric and all values are positive." |
721 |
) |
|
722 |
) |
|
723 |
} |
|
724 | ! |
if (log_y) { |
725 | ! |
validate( |
726 | ! |
need( |
727 | ! |
is.numeric(ANL[[y_var]]) && all( |
728 | ! |
ANL[[y_var]] > 0 | is.na(ANL[[y_var]]) |
729 |
), |
|
730 | ! |
"Y variable can only be log transformed if variable is numeric and all values are positive." |
731 |
) |
|
732 |
) |
|
733 |
} |
|
734 | ||
735 | ! |
facet_cl <- facet_ggplot_call( |
736 | ! |
row_facet_name, |
737 | ! |
col_facet_name, |
738 | ! |
free_x_scales = isTRUE(input$free_scales), |
739 | ! |
free_y_scales = isTRUE(input$free_scales) |
740 |
) |
|
741 | ||
742 | ! |
point_sizes <- if (length(size_by_var) > 0) { |
743 | ! |
validate(need(is.numeric(ANL[[size_by_var]]), "Variable to size by must be numeric")) |
744 | ! |
substitute( |
745 | ! |
expr = size * ANL[[size_by_var]] / max(ANL[[size_by_var]], na.rm = TRUE), |
746 | ! |
env = list(size = size, size_by_var = size_by_var) |
747 |
) |
|
748 |
} else { |
|
749 | ! |
size |
750 |
} |
|
751 | ||
752 | ! |
plot_q <- merged$anl_q_r() |
753 | ||
754 | ! |
if (log_x) { |
755 | ! |
log_x_fn <- input$log_x_base |
756 | ! |
plot_q <- teal.code::eval_code( |
757 | ! |
object = plot_q, |
758 | ! |
code = substitute( |
759 | ! |
expr = ANL[, log_x_var] <- log_x_fn(ANL[, x_var]), |
760 | ! |
env = list( |
761 | ! |
x_var = x_var, |
762 | ! |
log_x_fn = as.name(log_x_fn), |
763 | ! |
log_x_var = paste0(log_x_fn, "_", x_var) |
764 |
) |
|
765 |
) |
|
766 |
) |
|
767 |
} |
|
768 | ||
769 | ! |
if (log_y) { |
770 | ! |
log_y_fn <- input$log_y_base |
771 | ! |
plot_q <- teal.code::eval_code( |
772 | ! |
object = plot_q, |
773 | ! |
code = substitute( |
774 | ! |
expr = ANL[, log_y_var] <- log_y_fn(ANL[, y_var]), |
775 | ! |
env = list( |
776 | ! |
y_var = y_var, |
777 | ! |
log_y_fn = as.name(log_y_fn), |
778 | ! |
log_y_var = paste0(log_y_fn, "_", y_var) |
779 |
) |
|
780 |
) |
|
781 |
) |
|
782 |
} |
|
783 | ||
784 | ! |
pre_pro_anl <- if (input$show_count) { |
785 | ! |
paste0( |
786 | ! |
"ANL %>% dplyr::group_by(", |
787 | ! |
paste( |
788 | ! |
c( |
789 | ! |
if (length(color_by_var) > 0 && inherits(ANL[[color_by_var]], c("factor", "character"))) color_by_var, |
790 | ! |
row_facet_name, |
791 | ! |
col_facet_name |
792 |
), |
|
793 | ! |
collapse = ", " |
794 |
), |
|
795 | ! |
") %>% dplyr::mutate(n = dplyr::n()) %>% dplyr::ungroup()" |
796 |
) |
|
797 |
} else { |
|
798 | ! |
"ANL" |
799 |
} |
|
800 | ||
801 | ! |
plot_call <- substitute(expr = pre_pro_anl %>% ggplot(), env = list(pre_pro_anl = str2lang(pre_pro_anl))) |
802 | ||
803 | ! |
plot_call <- if (length(color_by_var) == 0) { |
804 | ! |
substitute( |
805 | ! |
expr = plot_call + |
806 | ! |
ggplot2::aes(x = x_name, y = y_name) + |
807 | ! |
ggplot2::geom_point(alpha = alpha_value, size = point_sizes, shape = shape_value, color = color_value), |
808 | ! |
env = list( |
809 | ! |
plot_call = plot_call, |
810 | ! |
x_name = if (log_x) as.name(paste0(log_x_fn, "_", x_var)) else as.name(x_var), |
811 | ! |
y_name = if (log_y) as.name(paste0(log_y_fn, "_", y_var)) else as.name(y_var), |
812 | ! |
alpha_value = alpha, |
813 | ! |
point_sizes = point_sizes, |
814 | ! |
shape_value = shape, |
815 | ! |
color_value = color |
816 |
) |
|
817 |
) |
|
818 |
} else { |
|
819 | ! |
substitute( |
820 | ! |
expr = plot_call + |
821 | ! |
ggplot2::aes(x = x_name, y = y_name, color = color_by_var_name) + |
822 | ! |
ggplot2::geom_point(alpha = alpha_value, size = point_sizes, shape = shape_value), |
823 | ! |
env = list( |
824 | ! |
plot_call = plot_call, |
825 | ! |
x_name = if (log_x) as.name(paste0(log_x_fn, "_", x_var)) else as.name(x_var), |
826 | ! |
y_name = if (log_y) as.name(paste0(log_y_fn, "_", y_var)) else as.name(y_var), |
827 | ! |
color_by_var_name = as.name(color_by_var), |
828 | ! |
alpha_value = alpha, |
829 | ! |
point_sizes = point_sizes, |
830 | ! |
shape_value = shape |
831 |
) |
|
832 |
) |
|
833 |
} |
|
834 | ||
835 | ! |
if (rug_plot) plot_call <- substitute(expr = plot_call + geom_rug(), env = list(plot_call = plot_call)) |
836 | ||
837 | ! |
plot_label_generator <- function(rhs_formula = quote(y ~ 1), |
838 | ! |
show_form = input$show_form, |
839 | ! |
show_r2 = input$show_r2, |
840 | ! |
show_count = input$show_count, |
841 | ! |
pos = input$pos, |
842 | ! |
label_size = input$label_size) { |
843 | ! |
stopifnot(sum(show_form, show_r2, show_count) >= 1) |
844 | ! |
aes_label <- paste0( |
845 | ! |
"aes(", |
846 | ! |
if (show_count) "n = n, ", |
847 | ! |
"label = ", |
848 | ! |
if (sum(show_form, show_r2, show_count) > 1) "paste(", |
849 | ! |
paste( |
850 | ! |
c( |
851 | ! |
if (show_form) "stat(eq.label)", |
852 | ! |
if (show_r2) "stat(adj.rr.label)", |
853 | ! |
if (show_count) "paste('N ~`=`~', n)" |
854 |
), |
|
855 | ! |
collapse = ", " |
856 |
), |
|
857 | ! |
if (sum(show_form, show_r2, show_count) > 1) ", sep = '*\", \"*'))" else ")" |
858 |
) |
|
859 | ! |
label_geom <- substitute( |
860 | ! |
expr = ggpmisc::stat_poly_eq( |
861 | ! |
mapping = aes_label, |
862 | ! |
formula = rhs_formula, |
863 | ! |
parse = TRUE, |
864 | ! |
label.x = pos, |
865 | ! |
size = label_size |
866 |
), |
|
867 | ! |
env = list( |
868 | ! |
rhs_formula = rhs_formula, |
869 | ! |
pos = pos, |
870 | ! |
aes_label = str2lang(aes_label), |
871 | ! |
label_size = label_size |
872 |
) |
|
873 |
) |
|
874 | ! |
substitute( |
875 | ! |
expr = plot_call + label_geom, |
876 | ! |
env = list( |
877 | ! |
plot_call = plot_call, |
878 | ! |
label_geom = label_geom |
879 |
) |
|
880 |
) |
|
881 |
} |
|
882 | ||
883 | ! |
if (trend_line_is_applicable()) { |
884 | ! |
shinyjs::hide("line_msg") |
885 | ! |
shinyjs::show("smoothing_degree") |
886 | ! |
if (!add_trend_line()) { |
887 | ! |
shinyjs::hide("ci") |
888 | ! |
shinyjs::hide("color_sub") |
889 | ! |
shinyjs::hide("show_form") |
890 | ! |
shinyjs::hide("show_r2") |
891 | ! |
if (input$show_count) { |
892 | ! |
plot_call <- plot_label_generator(show_form = FALSE, show_r2 = FALSE) |
893 | ! |
shinyjs::show("label_pos") |
894 | ! |
shinyjs::show("label_size") |
895 |
} else { |
|
896 | ! |
shinyjs::hide("label_pos") |
897 | ! |
shinyjs::hide("label_size") |
898 |
} |
|
899 |
} else { |
|
900 | ! |
shinyjs::show("ci") |
901 | ! |
shinyjs::show("show_form") |
902 | ! |
shinyjs::show("show_r2") |
903 | ! |
if (nrow(ANL) - nrow(stats::na.omit(ANL[, c(x_var, y_var)])) > 0) { |
904 | ! |
plot_q <- teal.code::eval_code( |
905 | ! |
plot_q, |
906 | ! |
substitute( |
907 | ! |
expr = ANL <- dplyr::filter(ANL, !is.na(x_var) & !is.na(y_var)), |
908 | ! |
env = list(x_var = as.name(x_var), y_var = as.name(y_var)) |
909 |
) |
|
910 |
) |
|
911 |
} |
|
912 | ! |
rhs_formula <- substitute( |
913 | ! |
expr = y ~ poly(x, smoothing_degree, raw = TRUE), |
914 | ! |
env = list(smoothing_degree = smoothing_degree) |
915 |
) |
|
916 | ! |
if (input$show_form || input$show_r2 || input$show_count) { |
917 | ! |
plot_call <- plot_label_generator(rhs_formula = rhs_formula) |
918 | ! |
shinyjs::show("label_pos") |
919 | ! |
shinyjs::show("label_size") |
920 |
} else { |
|
921 | ! |
shinyjs::hide("label_pos") |
922 | ! |
shinyjs::hide("label_size") |
923 |
} |
|
924 | ! |
plot_call <- substitute( |
925 | ! |
expr = plot_call + ggplot2::geom_smooth(formula = rhs_formula, se = TRUE, level = ci, method = "lm"), |
926 | ! |
env = list(plot_call = plot_call, rhs_formula = rhs_formula, ci = ci) |
927 |
) |
|
928 |
} |
|
929 |
} else { |
|
930 | ! |
shinyjs::hide("smoothing_degree") |
931 | ! |
shinyjs::hide("ci") |
932 | ! |
shinyjs::hide("color_sub") |
933 | ! |
shinyjs::hide("show_form") |
934 | ! |
shinyjs::hide("show_r2") |
935 | ! |
if (input$show_count) { |
936 | ! |
plot_call <- plot_label_generator(show_form = FALSE, show_r2 = FALSE) |
937 | ! |
shinyjs::show("label_pos") |
938 | ! |
shinyjs::show("label_size") |
939 |
} else { |
|
940 | ! |
shinyjs::hide("label_pos") |
941 | ! |
shinyjs::hide("label_size") |
942 |
} |
|
943 | ! |
shinyjs::show("line_msg") |
944 |
} |
|
945 | ||
946 | ! |
if (!is.null(facet_cl)) { |
947 | ! |
plot_call <- substitute(expr = plot_call + facet_cl, env = list(plot_call = plot_call, facet_cl = facet_cl)) |
948 |
} |
|
949 | ||
950 | ! |
y_label <- varname_w_label( |
951 | ! |
y_var, |
952 | ! |
ANL, |
953 | ! |
prefix = if (log_y) paste(log_y_fn, "(") else NULL, |
954 | ! |
suffix = if (log_y) ")" else NULL |
955 |
) |
|
956 | ! |
x_label <- varname_w_label( |
957 | ! |
x_var, |
958 | ! |
ANL, |
959 | ! |
prefix = if (log_x) paste(log_x_fn, "(") else NULL, |
960 | ! |
suffix = if (log_x) ")" else NULL |
961 |
) |
|
962 | ||
963 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
964 | ! |
labs = list(y = y_label, x = x_label), |
965 | ! |
theme = list(legend.position = "bottom") |
966 |
) |
|
967 | ||
968 | ! |
if (rotate_xaxis_labels) { |
969 | ! |
dev_ggplot2_args$theme[["axis.text.x"]] <- quote(element_text(angle = 45, hjust = 1)) |
970 |
} |
|
971 | ||
972 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
973 | ! |
user_plot = ggplot2_args, |
974 | ! |
module_plot = dev_ggplot2_args |
975 |
) |
|
976 | ||
977 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args(all_ggplot2_args, ggtheme = ggtheme) |
978 | ||
979 | ||
980 | ! |
if (add_density) { |
981 | ! |
plot_call <- substitute( |
982 | ! |
expr = ggExtra::ggMarginal( |
983 | ! |
plot_call + labs + ggthemes + themes, |
984 | ! |
type = "density", |
985 | ! |
groupColour = group_colour |
986 |
), |
|
987 | ! |
env = list( |
988 | ! |
plot_call = plot_call, |
989 | ! |
group_colour = if (length(color_by_var) > 0) TRUE else FALSE, |
990 | ! |
labs = parsed_ggplot2_args$labs, |
991 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
992 | ! |
themes = parsed_ggplot2_args$theme |
993 |
) |
|
994 |
) |
|
995 |
} else { |
|
996 | ! |
plot_call <- substitute( |
997 | ! |
expr = plot_call + |
998 | ! |
labs + |
999 | ! |
ggthemes + |
1000 | ! |
themes, |
1001 | ! |
env = list( |
1002 | ! |
plot_call = plot_call, |
1003 | ! |
labs = parsed_ggplot2_args$labs, |
1004 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
1005 | ! |
themes = parsed_ggplot2_args$theme |
1006 |
) |
|
1007 |
) |
|
1008 |
} |
|
1009 | ||
1010 | ! |
plot_call <- substitute(expr = plot <- plot_call, env = list(plot_call = plot_call)) |
1011 | ||
1012 | ! |
teal.code::eval_code(plot_q, plot_call) |
1013 |
}) |
|
1014 | ||
1015 | ! |
decorated_output_plot_q <- srv_decorate_teal_data( |
1016 | ! |
id = "decorator", |
1017 | ! |
data = output_q, |
1018 | ! |
decorators = select_decorators(decorators, "plot"), |
1019 | ! |
expr = print(plot) |
1020 |
) |
|
1021 | ||
1022 | ! |
plot_r <- reactive(req(decorated_output_plot_q())[["plot"]]) |
1023 | ||
1024 |
# Insert the plot into a plot_with_settings module from teal.widgets |
|
1025 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
1026 | ! |
id = "scatter_plot", |
1027 | ! |
plot_r = plot_r, |
1028 | ! |
height = plot_height, |
1029 | ! |
width = plot_width, |
1030 | ! |
brushing = TRUE |
1031 |
) |
|
1032 | ||
1033 | ! |
output$data_table <- DT::renderDataTable({ |
1034 | ! |
plot_brush <- pws$brush() |
1035 | ||
1036 | ! |
if (!is.null(plot_brush)) { |
1037 | ! |
validate(need(!input$add_density, "Brushing feature is currently not supported when plot has marginal density")) |
1038 |
} |
|
1039 | ||
1040 | ! |
merged_data <- isolate(teal.code::dev_suppress(output_q()[["ANL"]])) |
1041 | ||
1042 | ! |
brushed_df <- teal.widgets::clean_brushedPoints(merged_data, plot_brush) |
1043 | ! |
numeric_cols <- names(brushed_df)[ |
1044 | ! |
vapply(brushed_df, function(x) is.numeric(x) && !is.integer(x), FUN.VALUE = logical(1)) |
1045 |
] |
|
1046 | ||
1047 | ! |
if (length(numeric_cols) > 0) { |
1048 | ! |
DT::formatRound( |
1049 | ! |
DT::datatable(brushed_df, |
1050 | ! |
rownames = FALSE, |
1051 | ! |
options = list(scrollX = TRUE, pageLength = input$data_table_rows) |
1052 |
), |
|
1053 | ! |
numeric_cols, |
1054 | ! |
table_dec |
1055 |
) |
|
1056 |
} else { |
|
1057 | ! |
DT::datatable(brushed_df, rownames = FALSE, options = list(scrollX = TRUE, pageLength = input$data_table_rows)) |
1058 |
} |
|
1059 |
}) |
|
1060 | ||
1061 |
# Render R code. |
|
1062 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_output_plot_q()))) |
1063 | ||
1064 | ! |
teal.widgets::verbatim_popup_srv( |
1065 | ! |
id = "rcode", |
1066 | ! |
verbatim_content = source_code_r, |
1067 | ! |
title = "R Code for scatterplot" |
1068 |
) |
|
1069 | ||
1070 |
### REPORTER |
|
1071 | ! |
if (with_reporter) { |
1072 | ! |
card_fun <- function(comment, label) { |
1073 | ! |
card <- teal::report_card_template( |
1074 | ! |
title = "Scatter Plot", |
1075 | ! |
label = label, |
1076 | ! |
with_filter = with_filter, |
1077 | ! |
filter_panel_api = filter_panel_api |
1078 |
) |
|
1079 | ! |
card$append_text("Plot", "header3") |
1080 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
1081 | ! |
if (!comment == "") { |
1082 | ! |
card$append_text("Comment", "header3") |
1083 | ! |
card$append_text(comment) |
1084 |
} |
|
1085 | ! |
card$append_src(source_code_r()) |
1086 | ! |
card |
1087 |
} |
|
1088 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
1089 |
} |
|
1090 |
### |
|
1091 |
}) |
|
1092 |
} |
1 |
#' `teal` module: Missing data analysis |
|
2 |
#' |
|
3 |
#' This module analyzes missing data in `data.frame`s to help users explore missing observations and |
|
4 |
#' gain insights into the completeness of their data. |
|
5 |
#' It is useful for clinical data analysis within the context of `CDISC` standards and |
|
6 |
#' adaptable for general data analysis purposes. |
|
7 |
#' |
|
8 |
#' @inheritParams teal::module |
|
9 |
#' @inheritParams shared_params |
|
10 |
#' @param parent_dataname (`character(1)`) Specifies the parent dataset name. Default is `ADSL` for `CDISC` data. |
|
11 |
#' If provided and exists, enables additional analysis "by subject". For non-`CDISC` data, this parameter can be |
|
12 |
#' ignored. |
|
13 |
# nolint start: line_length. |
|
14 |
#' @param ggtheme (`character`) optional, specifies the default `ggplot2` theme for plots. Defaults to `classic`. |
|
15 |
#' @param ggplot2_args `r roxygen_ggplot2_args_param("Summary Obs", "Summary Patients", "Combinations Main", "Combinations Hist", "By Subject")` |
|
16 |
# nolint end: line_length. |
|
17 |
#' |
|
18 |
#' @inherit shared_params return |
|
19 |
#' |
|
20 |
#' @section Decorating Module: |
|
21 |
#' |
|
22 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
23 |
#' - `summary_plot` (`grob` created with [ggplot2::ggplotGrob()]) |
|
24 |
#' - `combination_plot` (`grob` created with [ggplot2::ggplotGrob()]) |
|
25 |
#' - `by_subject_plot` (`ggplot2`) |
|
26 |
#' - `table` (`listing_df` created with [rlistings::as_listing()]) |
|
27 |
#' |
|
28 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
29 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
30 |
#' See code snippet below: |
|
31 |
#' |
|
32 |
#' ``` |
|
33 |
#' tm_missing_data( |
|
34 |
#' ..., # arguments for module |
|
35 |
#' decorators = list( |
|
36 |
#' summary_plot = teal_transform_module(...), # applied only to `summary_plot` output |
|
37 |
#' combination_plot = teal_transform_module(...), # applied only to `combination_plot` output |
|
38 |
#' by_subject_plot = teal_transform_module(...), # applied only to `by_subject_plot` output |
|
39 |
#' table = teal_transform_module(...) # applied only to `table` output |
|
40 |
#' ) |
|
41 |
#' ) |
|
42 |
#' ``` |
|
43 |
#' |
|
44 |
#' For additional details and examples of decorators, refer to the vignette |
|
45 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
46 |
#' |
|
47 |
#' @examplesShinylive |
|
48 |
#' library(teal.modules.general) |
|
49 |
#' interactive <- function() TRUE |
|
50 |
#' {{ next_example }} |
|
51 |
#' @examples |
|
52 |
#' # general example data |
|
53 |
#' data <- teal_data() |
|
54 |
#' data <- within(data, { |
|
55 |
#' require(nestcolor) |
|
56 |
#' |
|
57 |
#' add_nas <- function(x) { |
|
58 |
#' x[sample(seq_along(x), floor(length(x) * runif(1, .05, .17)))] <- NA |
|
59 |
#' x |
|
60 |
#' } |
|
61 |
#' |
|
62 |
#' iris <- iris |
|
63 |
#' mtcars <- mtcars |
|
64 |
#' |
|
65 |
#' iris[] <- lapply(iris, add_nas) |
|
66 |
#' mtcars[] <- lapply(mtcars, add_nas) |
|
67 |
#' mtcars[["cyl"]] <- as.factor(mtcars[["cyl"]]) |
|
68 |
#' mtcars[["gear"]] <- as.factor(mtcars[["gear"]]) |
|
69 |
#' }) |
|
70 |
#' |
|
71 |
#' app <- init( |
|
72 |
#' data = data, |
|
73 |
#' modules = modules( |
|
74 |
#' tm_missing_data(parent_dataname = "mtcars") |
|
75 |
#' ) |
|
76 |
#' ) |
|
77 |
#' if (interactive()) { |
|
78 |
#' shinyApp(app$ui, app$server) |
|
79 |
#' } |
|
80 |
#' |
|
81 |
#' @examplesShinylive |
|
82 |
#' library(teal.modules.general) |
|
83 |
#' interactive <- function() TRUE |
|
84 |
#' {{ next_example }} |
|
85 |
#' @examples |
|
86 |
#' # CDISC example data |
|
87 |
#' data <- teal_data() |
|
88 |
#' data <- within(data, { |
|
89 |
#' require(nestcolor) |
|
90 |
#' ADSL <- teal.data::rADSL |
|
91 |
#' ADRS <- rADRS |
|
92 |
#' }) |
|
93 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
94 |
#' |
|
95 |
#' app <- init( |
|
96 |
#' data = data, |
|
97 |
#' modules = modules( |
|
98 |
#' tm_missing_data() |
|
99 |
#' ) |
|
100 |
#' ) |
|
101 |
#' if (interactive()) { |
|
102 |
#' shinyApp(app$ui, app$server) |
|
103 |
#' } |
|
104 |
#' |
|
105 |
#' @export |
|
106 |
#' |
|
107 |
tm_missing_data <- function(label = "Missing data", |
|
108 |
plot_height = c(600, 400, 5000), |
|
109 |
plot_width = NULL, |
|
110 |
datanames = "all", |
|
111 |
parent_dataname = "ADSL", |
|
112 |
ggtheme = c("classic", "gray", "bw", "linedraw", "light", "dark", "minimal", "void"), |
|
113 |
ggplot2_args = list( |
|
114 |
"Combinations Hist" = teal.widgets::ggplot2_args(labs = list(caption = NULL)), |
|
115 |
"Combinations Main" = teal.widgets::ggplot2_args(labs = list(title = NULL)) |
|
116 |
), |
|
117 |
pre_output = NULL, |
|
118 |
post_output = NULL, |
|
119 |
transformators = list(), |
|
120 |
decorators = list()) { |
|
121 | ! |
message("Initializing tm_missing_data") |
122 | ||
123 |
# Normalize the parameters |
|
124 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
125 | ||
126 |
# Start of assertions |
|
127 | ! |
checkmate::assert_string(label) |
128 | ||
129 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
130 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
131 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
132 | ! |
checkmate::assert_numeric( |
133 | ! |
plot_width[1], |
134 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
135 |
) |
|
136 | ||
137 | ! |
checkmate::assert_character(datanames, min.len = 0, min.chars = 1, null.ok = TRUE) |
138 | ! |
checkmate::assert_character(parent_dataname, min.len = 0, max.len = 1) |
139 | ! |
ggtheme <- match.arg(ggtheme) |
140 | ||
141 | ! |
plot_choices <- c("Summary Obs", "Summary Patients", "Combinations Main", "Combinations Hist", "By Subject") |
142 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
143 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
144 | ||
145 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
146 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
147 | ||
148 | ! |
available_decorators <- c("summary_plot", "combination_plot", "by_subject_plot", "table") |
149 | ! |
assert_decorators(decorators, names = available_decorators) |
150 |
# End of assertions |
|
151 | ||
152 | ! |
datanames_module <- if (identical(datanames, "all") || is.null(datanames)) { |
153 | ! |
datanames |
154 |
} else { |
|
155 | ! |
union(datanames, parent_dataname) |
156 |
} |
|
157 | ||
158 | ! |
ans <- module( |
159 | ! |
label, |
160 | ! |
server = srv_page_missing_data, |
161 | ! |
datanames = datanames_module, |
162 | ! |
server_args = list( |
163 | ! |
datanames = if (is.null(datanames)) "all" else datanames, |
164 | ! |
parent_dataname = parent_dataname, |
165 | ! |
plot_height = plot_height, |
166 | ! |
plot_width = plot_width, |
167 | ! |
ggplot2_args = ggplot2_args, |
168 | ! |
ggtheme = ggtheme, |
169 | ! |
decorators = decorators |
170 |
), |
|
171 | ! |
ui = ui_page_missing_data, |
172 | ! |
transformators = transformators, |
173 | ! |
ui_args = list(pre_output = pre_output, post_output = post_output) |
174 |
) |
|
175 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
176 | ! |
ans |
177 |
} |
|
178 | ||
179 |
# UI function for the missing data module (all datasets) |
|
180 |
ui_page_missing_data <- function(id, pre_output = NULL, post_output = NULL) { |
|
181 | ! |
ns <- NS(id) |
182 | ! |
tagList( |
183 | ! |
include_css_files("custom"), |
184 | ! |
teal.widgets::standard_layout( |
185 | ! |
output = teal.widgets::white_small_well( |
186 | ! |
tags$div( |
187 | ! |
class = "flex", |
188 | ! |
column( |
189 | ! |
width = 12, |
190 | ! |
uiOutput(ns("dataset_tabs")) |
191 |
) |
|
192 |
) |
|
193 |
), |
|
194 | ! |
encoding = tags$div( |
195 | ! |
uiOutput(ns("dataset_encodings")) |
196 |
), |
|
197 | ! |
uiOutput(ns("dataset_reporter")), |
198 | ! |
pre_output = pre_output, |
199 | ! |
post_output = post_output |
200 |
) |
|
201 |
) |
|
202 |
} |
|
203 | ||
204 |
# Server function for the missing data module (all datasets) |
|
205 |
srv_page_missing_data <- function(id, data, reporter, filter_panel_api, datanames, parent_dataname, |
|
206 |
plot_height, plot_width, ggplot2_args, ggtheme, decorators) { |
|
207 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
208 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
209 | ! |
moduleServer(id, function(input, output, session) { |
210 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
211 | ||
212 | ! |
datanames <- Filter(function(name) { |
213 | ! |
is.data.frame(isolate(data())[[name]]) |
214 | ! |
}, if (identical(datanames, "all")) names(isolate(data())) else datanames) |
215 | ||
216 | ! |
if_subject_plot <- length(parent_dataname) > 0 && parent_dataname %in% datanames |
217 | ||
218 | ! |
ns <- session$ns |
219 | ||
220 | ! |
output$dataset_tabs <- renderUI({ |
221 | ! |
do.call( |
222 | ! |
tabsetPanel, |
223 | ! |
c( |
224 | ! |
id = ns("dataname_tab"), |
225 | ! |
lapply( |
226 | ! |
datanames, |
227 | ! |
function(x) { |
228 | ! |
tabPanel( |
229 | ! |
title = x, |
230 | ! |
column( |
231 | ! |
width = 12, |
232 | ! |
tags$div( |
233 | ! |
class = "mt-4", |
234 | ! |
ui_missing_data(id = ns(x), by_subject_plot = if_subject_plot) |
235 |
) |
|
236 |
) |
|
237 |
) |
|
238 |
} |
|
239 |
) |
|
240 |
) |
|
241 |
) |
|
242 |
}) |
|
243 | ||
244 | ! |
output$dataset_encodings <- renderUI({ |
245 | ! |
tagList( |
246 | ! |
lapply( |
247 | ! |
datanames, |
248 | ! |
function(x) { |
249 | ! |
conditionalPanel( |
250 | ! |
is_tab_active_js(ns("dataname_tab"), x), |
251 | ! |
encoding_missing_data( |
252 | ! |
id = ns(x), |
253 | ! |
summary_per_patient = if_subject_plot, |
254 | ! |
ggtheme = ggtheme, |
255 | ! |
datanames = datanames, |
256 | ! |
decorators = decorators |
257 |
) |
|
258 |
) |
|
259 |
} |
|
260 |
) |
|
261 |
) |
|
262 |
}) |
|
263 | ||
264 | ! |
output$dataset_reporter <- renderUI({ |
265 | ! |
lapply(datanames, function(x) { |
266 | ! |
dataname_ns <- NS(ns(x)) |
267 | ||
268 | ! |
conditionalPanel( |
269 | ! |
is_tab_active_js(ns("dataname_tab"), x), |
270 | ! |
tagList( |
271 | ! |
teal.widgets::verbatim_popup_ui(dataname_ns("rcode"), "Show R code") |
272 |
) |
|
273 |
) |
|
274 |
}) |
|
275 |
}) |
|
276 | ||
277 | ! |
lapply( |
278 | ! |
datanames, |
279 | ! |
function(x) { |
280 | ! |
srv_missing_data( |
281 | ! |
id = x, |
282 | ! |
data = data, |
283 | ! |
reporter = if (with_reporter) reporter, |
284 | ! |
filter_panel_api = if (with_filter) filter_panel_api, |
285 | ! |
dataname = x, |
286 | ! |
parent_dataname = parent_dataname, |
287 | ! |
plot_height = plot_height, |
288 | ! |
plot_width = plot_width, |
289 | ! |
ggplot2_args = ggplot2_args, |
290 | ! |
decorators = decorators |
291 |
) |
|
292 |
} |
|
293 |
) |
|
294 |
}) |
|
295 |
} |
|
296 | ||
297 |
# UI function for the missing data module (single dataset) |
|
298 |
ui_missing_data <- function(id, by_subject_plot = FALSE) { |
|
299 | ! |
ns <- NS(id) |
300 | ||
301 | ! |
tab_list <- list( |
302 | ! |
tabPanel( |
303 | ! |
"Summary", |
304 | ! |
teal.widgets::plot_with_settings_ui(id = ns("summary_plot")), |
305 | ! |
helpText( |
306 | ! |
tags$p(paste( |
307 | ! |
'The "Summary" graph shows the number of missing values per variable (both absolute and percentage),', |
308 | ! |
"sorted by magnitude." |
309 |
)), |
|
310 | ! |
tags$p( |
311 | ! |
'The "summary per patients" graph is showing how many subjects have at least one missing observation', |
312 | ! |
"for each variable. It will be most useful for panel datasets." |
313 |
) |
|
314 |
) |
|
315 |
), |
|
316 | ! |
tabPanel( |
317 | ! |
"Combinations", |
318 | ! |
teal.widgets::plot_with_settings_ui(id = ns("combination_plot")), |
319 | ! |
helpText( |
320 | ! |
tags$p(paste( |
321 | ! |
'The "Combinations" graph is used to explore the relationship between the missing data within', |
322 | ! |
"different columns of the dataset.", |
323 | ! |
"It shows the different patterns of missingness in the rows of the data.", |
324 | ! |
'For example, suppose that 70 rows of the data have exactly columns "A" and "B" missing.', |
325 | ! |
"In this case there would be a bar of height 70 in the top graph and", |
326 | ! |
'the column below this in the second graph would have rows "A" and "B" cells shaded red.' |
327 |
)), |
|
328 | ! |
tags$p(paste( |
329 | ! |
"Due to the large number of missing data patterns possible, only those with a large set of observations", |
330 | ! |
'are shown in the graph and the "Combination cut-off" slider can be used to adjust the number shown.' |
331 |
)) |
|
332 |
) |
|
333 |
), |
|
334 | ! |
tabPanel( |
335 | ! |
"By Variable Levels", |
336 | ! |
teal.widgets::get_dt_rows(ns("levels_table"), ns("levels_table_rows")), |
337 | ! |
DT::dataTableOutput(ns("levels_table")) |
338 |
) |
|
339 |
) |
|
340 | ! |
if (isTRUE(by_subject_plot)) { |
341 | ! |
tab_list <- append( |
342 | ! |
tab_list, |
343 | ! |
list(tabPanel( |
344 | ! |
"Grouped by Subject", |
345 | ! |
teal.widgets::plot_with_settings_ui(id = ns("by_subject_plot")), |
346 | ! |
helpText( |
347 | ! |
tags$p(paste( |
348 | ! |
"This graph shows the missingness with respect to subjects rather than individual rows of the", |
349 | ! |
"dataset. Each row represents one dataset variable and each column a single subject. Only subjects", |
350 | ! |
"with at least one record in this dataset are shown. For a given subject, if they have any missing", |
351 | ! |
"values of a specific variable then the appropriate cell in the graph is marked as missing." |
352 |
)) |
|
353 |
) |
|
354 |
)) |
|
355 |
) |
|
356 |
} |
|
357 | ||
358 | ! |
do.call( |
359 | ! |
tabsetPanel, |
360 | ! |
c( |
361 | ! |
id = ns("summary_type"), |
362 | ! |
tab_list |
363 |
) |
|
364 |
) |
|
365 |
} |
|
366 | ||
367 |
# UI encoding for the missing data module (all datasets) |
|
368 |
encoding_missing_data <- function(id, summary_per_patient = FALSE, ggtheme, datanames, decorators) { |
|
369 | ! |
ns <- NS(id) |
370 | ||
371 | ! |
tagList( |
372 |
### Reporter |
|
373 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
374 |
### |
|
375 | ! |
tags$label("Encodings", class = "text-primary"), |
376 | ! |
helpText( |
377 | ! |
paste0("Dataset", `if`(length(datanames) > 1, "s", ""), ":"), |
378 | ! |
tags$code(paste(datanames, collapse = ", ")) |
379 |
), |
|
380 | ! |
uiOutput(ns("variables")), |
381 | ! |
actionButton( |
382 | ! |
ns("filter_na"), |
383 | ! |
tags$span("Select only vars with missings", class = "whitespace-normal"), |
384 | ! |
width = "100%", |
385 | ! |
class = "mb-4" |
386 |
), |
|
387 | ! |
conditionalPanel( |
388 | ! |
is_tab_active_js(ns("summary_type"), "Summary"), |
389 | ! |
checkboxInput( |
390 | ! |
ns("any_na"), |
391 | ! |
tags$div( |
392 | ! |
class = "teal-tooltip", |
393 | ! |
tagList( |
394 | ! |
"Add **anyna** variable", |
395 | ! |
icon("circle-info"), |
396 | ! |
tags$span( |
397 | ! |
class = "tooltiptext", |
398 | ! |
"Describes the number of observations with at least one missing value in any variable." |
399 |
) |
|
400 |
) |
|
401 |
), |
|
402 | ! |
value = FALSE |
403 |
), |
|
404 | ! |
if (summary_per_patient) { |
405 | ! |
checkboxInput( |
406 | ! |
ns("if_patients_plot"), |
407 | ! |
tags$div( |
408 | ! |
class = "teal-tooltip", |
409 | ! |
tagList( |
410 | ! |
"Add summary per patients", |
411 | ! |
icon("circle-info"), |
412 | ! |
tags$span( |
413 | ! |
class = "tooltiptext", |
414 | ! |
paste( |
415 | ! |
"Displays the number of missing values per observation,", |
416 | ! |
"where the x-axis is sorted by observation appearance in the table." |
417 |
) |
|
418 |
) |
|
419 |
) |
|
420 |
), |
|
421 | ! |
value = FALSE |
422 |
) |
|
423 |
}, |
|
424 | ! |
ui_decorate_teal_data(ns("dec_summary_plot"), decorators = select_decorators(decorators, "summary_plot")) |
425 |
), |
|
426 | ! |
conditionalPanel( |
427 | ! |
is_tab_active_js(ns("summary_type"), "Combinations"), |
428 | ! |
uiOutput(ns("cutoff")), |
429 | ! |
ui_decorate_teal_data(ns("dec_combination_plot"), decorators = select_decorators(decorators, "combination_plot")) |
430 |
), |
|
431 | ! |
conditionalPanel( |
432 | ! |
is_tab_active_js(ns("summary_type"), "Grouped by Subject"), |
433 | ! |
ui_decorate_teal_data(ns("dec_by_subject_plot"), decorators = select_decorators(decorators, "by_subject_plot")) |
434 |
), |
|
435 | ! |
conditionalPanel( |
436 | ! |
is_tab_active_js(ns("summary_type"), "By Variable Levels"), |
437 | ! |
uiOutput(ns("group_by_var_ui")), |
438 | ! |
uiOutput(ns("group_by_vals_ui")), |
439 | ! |
radioButtons( |
440 | ! |
ns("count_type"), |
441 | ! |
label = "Display missing as", |
442 | ! |
choices = c("counts", "proportions"), |
443 | ! |
selected = "counts", |
444 | ! |
inline = TRUE |
445 |
), |
|
446 | ! |
ui_decorate_teal_data(ns("dec_summary_table"), decorators = select_decorators(decorators, "table")) |
447 |
), |
|
448 | ! |
teal.widgets::panel_item( |
449 | ! |
title = "Plot settings", |
450 | ! |
selectInput( |
451 | ! |
inputId = ns("ggtheme"), |
452 | ! |
label = "Theme (by ggplot):", |
453 | ! |
choices = ggplot_themes, |
454 | ! |
selected = ggtheme, |
455 | ! |
multiple = FALSE |
456 |
) |
|
457 |
) |
|
458 |
) |
|
459 |
} |
|
460 | ||
461 |
# Server function for the missing data (single dataset) |
|
462 |
srv_missing_data <- function(id, |
|
463 |
data, |
|
464 |
reporter, |
|
465 |
filter_panel_api, |
|
466 |
dataname, |
|
467 |
parent_dataname, |
|
468 |
plot_height, |
|
469 |
plot_width, |
|
470 |
ggplot2_args, |
|
471 |
decorators) { |
|
472 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
473 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
474 | ! |
checkmate::assert_class(data, "reactive") |
475 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
476 | ! |
moduleServer(id, function(input, output, session) { |
477 | ! |
ns <- session$ns |
478 | ||
479 | ! |
prev_group_by_var <- reactiveVal("") |
480 | ! |
data_r <- reactive(data()[[dataname]]) |
481 | ! |
data_keys <- reactive(unlist(teal.data::join_keys(data())[[dataname]])) |
482 | ||
483 | ! |
iv_r <- reactive({ |
484 | ! |
iv <- shinyvalidate::InputValidator$new() |
485 | ! |
iv$add_rule( |
486 | ! |
"variables_select", |
487 | ! |
shinyvalidate::sv_required("At least one reference variable needs to be selected.") |
488 |
) |
|
489 | ! |
iv$add_rule( |
490 | ! |
"variables_select", |
491 | ! |
~ if (length(setdiff((.), data_keys())) < 1) "Please also select non-key columns." |
492 |
) |
|
493 | ! |
iv_summary_table <- shinyvalidate::InputValidator$new() |
494 | ! |
iv_summary_table$condition(~ isTRUE(input$summary_type == "By Variable Levels")) |
495 | ! |
iv_summary_table$add_rule("count_type", shinyvalidate::sv_required("Please select type of counts")) |
496 | ! |
iv_summary_table$add_rule( |
497 | ! |
"group_by_vals", |
498 | ! |
shinyvalidate::sv_required("Please select both group-by variable and values") |
499 |
) |
|
500 | ! |
iv_summary_table$add_rule( |
501 | ! |
"group_by_var", |
502 | ! |
~ if (length(.) > 0 && length(input$variables_select) == 1 && (.) == input$variables_select) { |
503 | ! |
"If only one reference variable is selected it must not be the grouping variable." |
504 |
} |
|
505 |
) |
|
506 | ! |
iv_summary_table$add_rule( |
507 | ! |
"variables_select", |
508 | ! |
~ if (length(input$group_by_var) > 0 && length(.) == 1 && (.) == input$group_by_var) { |
509 | ! |
"If only one reference variable is selected it must not be the grouping variable." |
510 |
} |
|
511 |
) |
|
512 | ! |
iv$add_validator(iv_summary_table) |
513 | ! |
iv$enable() |
514 | ! |
iv |
515 |
}) |
|
516 | ||
517 | ! |
data_parent_keys <- reactive({ |
518 | ! |
if (length(parent_dataname) > 0 && parent_dataname %in% names(data())) { |
519 | ! |
keys <- teal.data::join_keys(data())[[dataname]] |
520 | ! |
if (parent_dataname %in% names(keys)) { |
521 | ! |
keys[[parent_dataname]] |
522 |
} else { |
|
523 | ! |
keys[[dataname]] |
524 |
} |
|
525 |
} else { |
|
526 | ! |
NULL |
527 |
} |
|
528 |
}) |
|
529 | ||
530 | ! |
common_code_q <- reactive({ |
531 | ! |
teal::validate_inputs(iv_r()) |
532 | ||
533 | ! |
group_var <- input$group_by_var |
534 | ! |
anl <- data_r() |
535 | ||
536 | ! |
qenv <- if (!is.null(selected_vars()) && length(selected_vars()) != ncol(anl)) { |
537 | ! |
teal.code::eval_code( |
538 | ! |
data(), |
539 | ! |
substitute( |
540 | ! |
expr = ANL <- anl_name[, selected_vars, drop = FALSE], |
541 | ! |
env = list(anl_name = as.name(dataname), selected_vars = selected_vars()) |
542 |
) |
|
543 |
) |
|
544 |
} else { |
|
545 | ! |
teal.code::eval_code( |
546 | ! |
data(), |
547 | ! |
substitute(expr = ANL <- anl_name, env = list(anl_name = as.name(dataname))) |
548 |
) |
|
549 |
} |
|
550 | ||
551 | ! |
if (input$summary_type == "By Variable Levels" && !is.null(group_var) && !(group_var %in% selected_vars())) { |
552 | ! |
qenv <- teal.code::eval_code( |
553 | ! |
qenv, |
554 | ! |
substitute( |
555 | ! |
expr = ANL[[group_var]] <- anl_name[[group_var]], |
556 | ! |
env = list(group_var = group_var, anl_name = as.name(dataname)) |
557 |
) |
|
558 |
) |
|
559 |
} |
|
560 | ||
561 | ! |
new_col_name <- "**anyna**" |
562 | ||
563 | ! |
qenv <- teal.code::eval_code( |
564 | ! |
qenv, |
565 | ! |
substitute( |
566 | ! |
expr = |
567 | ! |
create_cols_labels <- function(cols, just_label = FALSE) { |
568 | ! |
column_labels <- column_labels_value |
569 | ! |
column_labels[is.na(column_labels) | length(column_labels) == 0] <- "" |
570 | ! |
if (just_label) { |
571 | ! |
labels <- column_labels[cols] |
572 |
} else { |
|
573 | ! |
labels <- ifelse(cols == new_col_name | cols == "", cols, paste0(column_labels[cols], " [", cols, "]")) |
574 |
} |
|
575 | ! |
labels |
576 |
}, |
|
577 | ! |
env = list( |
578 | ! |
new_col_name = new_col_name, |
579 | ! |
column_labels_value = c(teal.data::col_labels(data_r())[selected_vars()], |
580 | ! |
new_col_name = new_col_name |
581 |
) |
|
582 |
) |
|
583 |
) |
|
584 |
) |
|
585 | ! |
qenv |
586 |
}) |
|
587 | ||
588 | ! |
selected_vars <- reactive({ |
589 | ! |
req(input$variables_select) |
590 | ! |
keys <- data_keys() |
591 | ! |
vars <- unique(c(keys, input$variables_select)) |
592 | ! |
vars |
593 |
}) |
|
594 | ||
595 | ! |
vars_summary <- reactive({ |
596 | ! |
na_count <- data_r() %>% |
597 | ! |
sapply(function(x) mean(is.na(x)), USE.NAMES = TRUE) %>% |
598 | ! |
sort(decreasing = TRUE) |
599 | ||
600 | ! |
tibble::tibble( |
601 | ! |
key = names(na_count), |
602 | ! |
value = unname(na_count), |
603 | ! |
label = cut(na_count, breaks = seq(from = 0, to = 1, by = 0.1), include.lowest = TRUE) |
604 |
) |
|
605 |
}) |
|
606 | ||
607 |
# Keep encoding panel up-to-date |
|
608 | ! |
output$variables <- renderUI({ |
609 | ! |
choices <- split(x = vars_summary()$key, f = vars_summary()$label, drop = TRUE) %>% rev() |
610 | ! |
selected <- choices <- unname(unlist(choices)) |
611 | ||
612 | ! |
teal.widgets::optionalSelectInput( |
613 | ! |
ns("variables_select"), |
614 | ! |
label = "Select variables", |
615 | ! |
label_help = HTML(paste0("Dataset: ", tags$code(dataname))), |
616 | ! |
choices = teal.transform::variable_choices(data_r(), choices), |
617 | ! |
selected = selected, |
618 | ! |
multiple = TRUE |
619 |
) |
|
620 |
}) |
|
621 | ||
622 | ! |
observeEvent(input$filter_na, { |
623 | ! |
choices <- vars_summary() %>% |
624 | ! |
dplyr::select(!!as.name("key")) %>% |
625 | ! |
getElement(name = 1) |
626 | ||
627 | ! |
selected <- vars_summary() %>% |
628 | ! |
dplyr::filter(!!as.name("value") > 0) %>% |
629 | ! |
dplyr::select(!!as.name("key")) %>% |
630 | ! |
getElement(name = 1) |
631 | ||
632 | ! |
teal.widgets::updateOptionalSelectInput( |
633 | ! |
session = session, |
634 | ! |
inputId = "variables_select", |
635 | ! |
choices = teal.transform::variable_choices(data_r()), |
636 | ! |
selected = restoreInput(ns("variables_select"), selected) |
637 |
) |
|
638 |
}) |
|
639 | ||
640 | ! |
output$group_by_var_ui <- renderUI({ |
641 | ! |
all_choices <- teal.transform::variable_choices(data_r()) |
642 | ! |
cat_choices <- all_choices[!sapply(data_r(), function(x) is.numeric(x) || inherits(x, "POSIXct"))] |
643 | ! |
validate( |
644 | ! |
need(cat_choices, "Dataset does not have any non-numeric or non-datetime variables to use to group data with") |
645 |
) |
|
646 | ! |
teal.widgets::optionalSelectInput( |
647 | ! |
ns("group_by_var"), |
648 | ! |
label = "Group by variable", |
649 | ! |
choices = cat_choices, |
650 | ! |
selected = `if`( |
651 | ! |
is.null(isolate(input$group_by_var)), |
652 | ! |
cat_choices[1], |
653 | ! |
isolate(input$group_by_var) |
654 |
), |
|
655 | ! |
multiple = FALSE, |
656 | ! |
label_help = paste0("Dataset: ", dataname) |
657 |
) |
|
658 |
}) |
|
659 | ||
660 | ! |
output$group_by_vals_ui <- renderUI({ |
661 | ! |
req(input$group_by_var) |
662 | ||
663 | ! |
choices <- teal.transform::value_choices(data_r(), input$group_by_var, input$group_by_var) |
664 | ! |
prev_choices <- isolate(input$group_by_vals) |
665 | ||
666 |
# determine selected value based on filtered data |
|
667 |
# display those previously selected values that are still available |
|
668 | ! |
selected <- if (!is.null(prev_choices) && any(prev_choices %in% choices)) { |
669 | ! |
prev_choices[match(choices[choices %in% prev_choices], prev_choices)] |
670 | ! |
} else if ( |
671 | ! |
!is.null(prev_choices) && |
672 | ! |
!any(prev_choices %in% choices) && |
673 | ! |
isolate(prev_group_by_var()) == input$group_by_var |
674 |
) { |
|
675 |
# if not any previously selected value is available and the grouping variable is the same, |
|
676 |
# then display NULL |
|
677 | ! |
NULL |
678 |
} else { |
|
679 |
# if new grouping variable (i.e. not any previously selected value is available), |
|
680 |
# then display all choices |
|
681 | ! |
choices |
682 |
} |
|
683 | ||
684 | ! |
prev_group_by_var(input$group_by_var) # set current group_by_var |
685 | ! |
validate(need(length(choices) < 100, "Please select group-by variable with fewer than 100 unique values")) |
686 | ! |
teal.widgets::optionalSelectInput( |
687 | ! |
ns("group_by_vals"), |
688 | ! |
label = "Filter levels", |
689 | ! |
choices = choices, |
690 | ! |
selected = selected, |
691 | ! |
multiple = TRUE, |
692 | ! |
label_help = paste0("Dataset: ", dataname) |
693 |
) |
|
694 |
}) |
|
695 | ||
696 | ! |
combination_cutoff_q <- reactive({ |
697 | ! |
req(common_code_q()) |
698 | ! |
teal.code::eval_code( |
699 | ! |
common_code_q(), |
700 | ! |
quote( |
701 | ! |
combination_cutoff <- ANL %>% |
702 | ! |
dplyr::mutate_all(is.na) %>% |
703 | ! |
dplyr::group_by_all() %>% |
704 | ! |
dplyr::tally() %>% |
705 | ! |
dplyr::ungroup() |
706 |
) |
|
707 |
) |
|
708 |
}) |
|
709 | ||
710 | ! |
output$cutoff <- renderUI({ |
711 | ! |
x <- combination_cutoff_q()[["combination_cutoff"]]$n |
712 | ||
713 |
# select 10-th from the top |
|
714 | ! |
n <- length(x) |
715 | ! |
idx <- max(1, n - 10) |
716 | ! |
prev_value <- isolate(input$combination_cutoff) |
717 | ! |
value <- if (is.null(prev_value) || prev_value > max(x) || prev_value < min(x)) { |
718 | ! |
sort(x, partial = idx)[idx] |
719 |
} else { |
|
720 | ! |
prev_value |
721 |
} |
|
722 | ||
723 | ! |
teal.widgets::optionalSliderInputValMinMax( |
724 | ! |
ns("combination_cutoff"), |
725 | ! |
"Combination cut-off", |
726 | ! |
c(value, range(x)) |
727 |
) |
|
728 |
}) |
|
729 | ||
730 |
# Prepare qenvs for output objects |
|
731 | ||
732 | ! |
summary_plot_q <- reactive({ |
733 | ! |
req(input$summary_type == "Summary") # needed to trigger show r code update on tab change |
734 | ! |
teal::validate_has_data(data_r(), 1) |
735 | ||
736 | ! |
qenv <- common_code_q() |
737 | ! |
if (input$any_na) { |
738 | ! |
new_col_name <- "**anyna**" |
739 | ! |
qenv <- teal.code::eval_code( |
740 | ! |
qenv, |
741 | ! |
substitute( |
742 | ! |
expr = ANL[[new_col_name]] <- ifelse(rowSums(is.na(ANL)) > 0, NA, FALSE), |
743 | ! |
env = list(new_col_name = new_col_name) |
744 |
) |
|
745 |
) |
|
746 |
} |
|
747 | ||
748 | ! |
qenv <- teal.code::eval_code( |
749 | ! |
qenv, |
750 | ! |
substitute( |
751 | ! |
expr = analysis_vars <- setdiff(colnames(ANL), data_keys), |
752 | ! |
env = list(data_keys = data_keys()) |
753 |
) |
|
754 |
) %>% |
|
755 | ! |
teal.code::eval_code( |
756 | ! |
substitute( |
757 | ! |
expr = summary_plot_obs <- data_frame_call[, analysis_vars] %>% |
758 | ! |
dplyr::summarise_all(list(function(x) sum(is.na(x)))) %>% |
759 | ! |
tidyr::pivot_longer(dplyr::everything(), names_to = "col", values_to = "n_na") %>% |
760 | ! |
dplyr::mutate(n_not_na = nrow(ANL) - n_na) %>% |
761 | ! |
tidyr::pivot_longer(-col, names_to = "isna", values_to = "n") %>% |
762 | ! |
dplyr::mutate(isna = isna == "n_na", n_pct = n / nrow(ANL) * 100), |
763 | ! |
env = list(data_frame_call = if (!inherits(data_r(), "tbl_df")) { |
764 | ! |
quote(tibble::as_tibble(ANL)) |
765 |
} else { |
|
766 | ! |
quote(ANL) |
767 |
}) |
|
768 |
) |
|
769 |
) %>% |
|
770 |
# x axis ordering according to number of missing values and alphabet |
|
771 | ! |
teal.code::eval_code( |
772 | ! |
quote( |
773 | ! |
expr = x_levels <- dplyr::filter(summary_plot_obs, isna) %>% |
774 | ! |
dplyr::arrange(n_pct, dplyr::desc(col)) %>% |
775 | ! |
dplyr::pull(col) %>% |
776 | ! |
create_cols_labels() |
777 |
) |
|
778 |
) |
|
779 | ||
780 |
# always set "**anyna**" level as the last one |
|
781 | ! |
if (isolate(input$any_na)) { |
782 | ! |
qenv <- teal.code::eval_code( |
783 | ! |
qenv, |
784 | ! |
quote(x_levels <- c(setdiff(x_levels, "**anyna**"), "**anyna**")) |
785 |
) |
|
786 |
} |
|
787 | ||
788 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
789 | ! |
labs = list(x = "Variable", y = "Missing observations"), |
790 | ! |
theme = list(legend.position = "bottom", axis.text.x = quote(element_text(angle = 45, hjust = 1))) |
791 |
) |
|
792 | ||
793 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
794 | ! |
user_plot = ggplot2_args[["Summary Obs"]], |
795 | ! |
user_default = ggplot2_args$default, |
796 | ! |
module_plot = dev_ggplot2_args |
797 |
) |
|
798 | ||
799 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
800 | ! |
all_ggplot2_args, |
801 | ! |
ggtheme = input$ggtheme |
802 |
) |
|
803 | ||
804 | ! |
qenv <- teal.code::eval_code( |
805 | ! |
qenv, |
806 | ! |
substitute( |
807 | ! |
summary_plot_top <- summary_plot_obs %>% |
808 | ! |
ggplot() + |
809 | ! |
aes( |
810 | ! |
x = factor(create_cols_labels(col), levels = x_levels), |
811 | ! |
y = n_pct, |
812 | ! |
fill = isna |
813 |
) + |
|
814 | ! |
geom_bar(position = "fill", stat = "identity") + |
815 | ! |
scale_fill_manual( |
816 | ! |
name = "", |
817 | ! |
values = c("grey90", c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]), |
818 | ! |
labels = c("Present", "Missing") |
819 |
) + |
|
820 | ! |
scale_y_continuous( |
821 | ! |
labels = scales::percent_format(), |
822 | ! |
breaks = seq(0, 1, by = 0.1), |
823 | ! |
expand = c(0, 0) |
824 |
) + |
|
825 | ! |
geom_text( |
826 | ! |
aes(label = ifelse(isna == TRUE, sprintf("%d [%.02f%%]", n, n_pct), ""), y = 1), |
827 | ! |
hjust = 1, |
828 | ! |
color = "black" |
829 |
) + |
|
830 | ! |
labs + |
831 | ! |
ggthemes + |
832 | ! |
themes + |
833 | ! |
coord_flip(), |
834 | ! |
env = list( |
835 | ! |
labs = parsed_ggplot2_args$labs, |
836 | ! |
themes = parsed_ggplot2_args$theme, |
837 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
838 |
) |
|
839 |
) |
|
840 |
) |
|
841 | ||
842 | ! |
if (isTRUE(input$if_patients_plot)) { |
843 | ! |
qenv <- teal.code::eval_code( |
844 | ! |
qenv, |
845 | ! |
substitute( |
846 | ! |
expr = parent_keys <- keys, |
847 | ! |
env = list(keys = data_parent_keys()) |
848 |
) |
|
849 |
) %>% |
|
850 | ! |
teal.code::eval_code(quote(ndistinct_subjects <- dplyr::n_distinct(ANL[, parent_keys]))) %>% |
851 | ! |
teal.code::eval_code( |
852 | ! |
quote( |
853 | ! |
summary_plot_patients <- ANL[, c(parent_keys, analysis_vars)] %>% |
854 | ! |
dplyr::group_by_at(parent_keys) %>% |
855 | ! |
dplyr::summarise_all(anyNA) %>% |
856 | ! |
tidyr::pivot_longer(cols = !dplyr::all_of(parent_keys), names_to = "col", values_to = "anyna") %>% |
857 | ! |
dplyr::group_by_at(c("col")) %>% |
858 | ! |
dplyr::summarise(count_na = sum(anyna)) %>% |
859 | ! |
dplyr::mutate(count_not_na = ndistinct_subjects - count_na) %>% |
860 | ! |
tidyr::pivot_longer(-c(col), names_to = "isna", values_to = "n") %>% |
861 | ! |
dplyr::mutate(isna = isna == "count_na", n_pct = n / ndistinct_subjects * 100) %>% |
862 | ! |
dplyr::arrange_at(c("isna", "n"), .funs = dplyr::desc) |
863 |
) |
|
864 |
) |
|
865 | ||
866 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
867 | ! |
labs = list(x = "", y = "Missing patients"), |
868 | ! |
theme = list( |
869 | ! |
legend.position = "bottom", |
870 | ! |
axis.text.x = quote(element_text(angle = 45, hjust = 1)), |
871 | ! |
axis.text.y = quote(element_blank()) |
872 |
) |
|
873 |
) |
|
874 | ||
875 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
876 | ! |
user_plot = ggplot2_args[["Summary Patients"]], |
877 | ! |
user_default = ggplot2_args$default, |
878 | ! |
module_plot = dev_ggplot2_args |
879 |
) |
|
880 | ||
881 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
882 | ! |
all_ggplot2_args, |
883 | ! |
ggtheme = input$ggtheme |
884 |
) |
|
885 | ||
886 | ! |
qenv <- teal.code::eval_code( |
887 | ! |
qenv, |
888 | ! |
substitute( |
889 | ! |
summary_plot_bottom <- summary_plot_patients %>% |
890 | ! |
ggplot() + |
891 | ! |
aes_( |
892 | ! |
x = ~ factor(create_cols_labels(col), levels = x_levels), |
893 | ! |
y = ~n_pct, |
894 | ! |
fill = ~isna |
895 |
) + |
|
896 | ! |
geom_bar(alpha = 1, stat = "identity", position = "fill") + |
897 | ! |
scale_y_continuous( |
898 | ! |
labels = scales::percent_format(), |
899 | ! |
breaks = seq(0, 1, by = 0.1), |
900 | ! |
expand = c(0, 0) |
901 |
) + |
|
902 | ! |
scale_fill_manual( |
903 | ! |
name = "", |
904 | ! |
values = c("grey90", c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]), |
905 | ! |
labels = c("Present", "Missing") |
906 |
) + |
|
907 | ! |
geom_text( |
908 | ! |
aes(label = ifelse(isna == TRUE, sprintf("%d [%.02f%%]", n, n_pct), ""), y = 1), |
909 | ! |
hjust = 1, |
910 | ! |
color = "black" |
911 |
) + |
|
912 | ! |
labs + |
913 | ! |
ggthemes + |
914 | ! |
themes + |
915 | ! |
coord_flip(), |
916 | ! |
env = list( |
917 | ! |
labs = parsed_ggplot2_args$labs, |
918 | ! |
themes = parsed_ggplot2_args$theme, |
919 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
920 |
) |
|
921 |
) |
|
922 |
) |
|
923 |
} |
|
924 | ||
925 | ! |
if (isTRUE(input$if_patients_plot)) { |
926 | ! |
within(qenv, { |
927 | ! |
g1 <- ggplotGrob(summary_plot_top) |
928 | ! |
g2 <- ggplotGrob(summary_plot_bottom) |
929 | ! |
summary_plot <- gridExtra::gtable_cbind(g1, g2, size = "first") |
930 | ! |
summary_plot$heights <- grid::unit.pmax(g1$heights, g2$heights) |
931 |
}) |
|
932 |
} else { |
|
933 | ! |
within(qenv, { |
934 | ! |
g1 <- ggplotGrob(summary_plot_top) |
935 | ! |
summary_plot <- g1 |
936 |
}) |
|
937 |
} |
|
938 |
}) |
|
939 | ||
940 | ! |
combination_plot_q <- reactive({ |
941 | ! |
req(input$summary_type == "Combinations", input$combination_cutoff, combination_cutoff_q()) |
942 | ! |
teal::validate_has_data(data_r(), 1) |
943 | ||
944 | ! |
qenv <- teal.code::eval_code( |
945 | ! |
combination_cutoff_q(), |
946 | ! |
substitute( |
947 | ! |
expr = data_combination_plot_cutoff <- combination_cutoff %>% |
948 | ! |
dplyr::filter(n >= combination_cutoff_value) %>% |
949 | ! |
dplyr::mutate(id = rank(-n, ties.method = "first")) %>% |
950 | ! |
tidyr::pivot_longer(-c(n, id), names_to = "key", values_to = "value") %>% |
951 | ! |
dplyr::arrange(n), |
952 | ! |
env = list(combination_cutoff_value = input$combination_cutoff) |
953 |
) |
|
954 |
) |
|
955 | ||
956 |
# find keys in dataset not selected in the UI and remove them from dataset |
|
957 | ! |
keys_not_selected <- setdiff(data_keys(), input$variables_select) |
958 | ! |
if (length(keys_not_selected) > 0) { |
959 | ! |
qenv <- teal.code::eval_code( |
960 | ! |
qenv, |
961 | ! |
substitute( |
962 | ! |
expr = data_combination_plot_cutoff <- data_combination_plot_cutoff %>% |
963 | ! |
dplyr::filter(!key %in% keys_not_selected), |
964 | ! |
env = list(keys_not_selected = keys_not_selected) |
965 |
) |
|
966 |
) |
|
967 |
} |
|
968 | ||
969 | ! |
qenv <- teal.code::eval_code( |
970 | ! |
qenv, |
971 | ! |
quote( |
972 | ! |
labels <- data_combination_plot_cutoff %>% |
973 | ! |
dplyr::filter(key == key[[1]]) %>% |
974 | ! |
getElement(name = 1) |
975 |
) |
|
976 |
) |
|
977 | ||
978 | ! |
dev_ggplot2_args1 <- teal.widgets::ggplot2_args( |
979 | ! |
labs = list(x = "", y = ""), |
980 | ! |
theme = list( |
981 | ! |
legend.position = "bottom", |
982 | ! |
axis.text.x = quote(element_blank()) |
983 |
) |
|
984 |
) |
|
985 | ||
986 | ! |
all_ggplot2_args1 <- teal.widgets::resolve_ggplot2_args( |
987 | ! |
user_plot = ggplot2_args[["Combinations Hist"]], |
988 | ! |
user_default = ggplot2_args$default, |
989 | ! |
module_plot = dev_ggplot2_args1 |
990 |
) |
|
991 | ||
992 | ! |
parsed_ggplot2_args1 <- teal.widgets::parse_ggplot2_args( |
993 | ! |
all_ggplot2_args1, |
994 | ! |
ggtheme = "void" |
995 |
) |
|
996 | ||
997 | ! |
dev_ggplot2_args2 <- teal.widgets::ggplot2_args( |
998 | ! |
labs = list(x = "", y = ""), |
999 | ! |
theme = list( |
1000 | ! |
legend.position = "bottom", |
1001 | ! |
axis.text.x = quote(element_blank()), |
1002 | ! |
axis.ticks = quote(element_blank()), |
1003 | ! |
panel.grid.major = quote(element_blank()) |
1004 |
) |
|
1005 |
) |
|
1006 | ||
1007 | ! |
all_ggplot2_args2 <- teal.widgets::resolve_ggplot2_args( |
1008 | ! |
user_plot = ggplot2_args[["Combinations Main"]], |
1009 | ! |
user_default = ggplot2_args$default, |
1010 | ! |
module_plot = dev_ggplot2_args2 |
1011 |
) |
|
1012 | ||
1013 | ! |
parsed_ggplot2_args2 <- teal.widgets::parse_ggplot2_args( |
1014 | ! |
all_ggplot2_args2, |
1015 | ! |
ggtheme = input$ggtheme |
1016 |
) |
|
1017 | ||
1018 | ! |
qenv <- teal.code::eval_code( |
1019 | ! |
qenv, |
1020 | ! |
substitute( |
1021 | ! |
expr = { |
1022 | ! |
combination_plot_top <- data_combination_plot_cutoff %>% |
1023 | ! |
dplyr::select(id, n) %>% |
1024 | ! |
dplyr::distinct() %>% |
1025 | ! |
ggplot(aes(x = id, y = n)) + |
1026 | ! |
geom_bar(stat = "identity", fill = c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]) + |
1027 | ! |
geom_text( |
1028 | ! |
aes(label = n), |
1029 | ! |
position = position_dodge(width = 0.9), |
1030 | ! |
vjust = -0.25 |
1031 |
) + |
|
1032 | ! |
ylim(c(0, max(data_combination_plot_cutoff$n) * 1.5)) + |
1033 | ! |
labs1 + |
1034 | ! |
ggthemes1 + |
1035 | ! |
themes1 |
1036 | ||
1037 | ! |
graph_number_rows <- length(unique(data_combination_plot_cutoff$id)) |
1038 | ! |
graph_number_cols <- nrow(data_combination_plot_cutoff) / graph_number_rows |
1039 | ||
1040 | ! |
combination_plot_bottom <- data_combination_plot_cutoff %>% ggplot() + |
1041 | ! |
aes(x = create_cols_labels(key), y = id - 0.5, fill = value) + |
1042 | ! |
geom_tile(alpha = 0.85, height = 0.95) + |
1043 | ! |
scale_fill_manual( |
1044 | ! |
name = "", |
1045 | ! |
values = c("grey90", c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]), |
1046 | ! |
labels = c("Present", "Missing") |
1047 |
) + |
|
1048 | ! |
geom_hline(yintercept = seq_len(1 + graph_number_rows) - 1) + |
1049 | ! |
geom_vline(xintercept = seq_len(1 + graph_number_cols) - 0.5, linetype = "dotted") + |
1050 | ! |
coord_flip() + |
1051 | ! |
labs2 + |
1052 | ! |
ggthemes2 + |
1053 | ! |
themes2 |
1054 |
}, |
|
1055 | ! |
env = list( |
1056 | ! |
labs1 = parsed_ggplot2_args1$labs, |
1057 | ! |
themes1 = parsed_ggplot2_args1$theme, |
1058 | ! |
ggthemes1 = parsed_ggplot2_args1$ggtheme, |
1059 | ! |
labs2 = parsed_ggplot2_args2$labs, |
1060 | ! |
themes2 = parsed_ggplot2_args2$theme, |
1061 | ! |
ggthemes2 = parsed_ggplot2_args2$ggtheme |
1062 |
) |
|
1063 |
) |
|
1064 |
) |
|
1065 | ||
1066 | ! |
within(qenv, { |
1067 | ! |
g1 <- ggplotGrob(combination_plot_top) |
1068 | ! |
g2 <- ggplotGrob(combination_plot_bottom) |
1069 | ||
1070 | ! |
combination_plot <- gridExtra::gtable_rbind(g1, g2, size = "last") |
1071 | ! |
combination_plot$heights[7] <- grid::unit(0.2, "null") # rescale to get the bar chart smaller |
1072 |
}) |
|
1073 |
}) |
|
1074 | ||
1075 | ! |
summary_table_q <- reactive({ |
1076 | ! |
req( |
1077 | ! |
input$summary_type == "By Variable Levels", # needed to trigger show r code update on tab change |
1078 | ! |
common_code_q() |
1079 |
) |
|
1080 | ! |
teal::validate_has_data(data_r(), 1) |
1081 | ||
1082 |
# extract the ANL dataset for use in further validation |
|
1083 | ! |
anl <- common_code_q()[["ANL"]] |
1084 | ||
1085 | ! |
group_var <- input$group_by_var |
1086 | ! |
validate( |
1087 | ! |
need( |
1088 | ! |
is.null(group_var) || |
1089 | ! |
length(unique(anl[[group_var]])) < 100, |
1090 | ! |
"Please select group-by variable with fewer than 100 unique values" |
1091 |
) |
|
1092 |
) |
|
1093 | ||
1094 | ! |
group_vals <- input$group_by_vals |
1095 | ! |
variables_select <- input$variables_select |
1096 | ! |
vars <- unique(variables_select, group_var) |
1097 | ! |
count_type <- input$count_type |
1098 | ||
1099 | ! |
if (!is.null(selected_vars()) && length(selected_vars()) != ncol(anl)) { |
1100 | ! |
variables <- selected_vars() |
1101 |
} else { |
|
1102 | ! |
variables <- colnames(anl) |
1103 |
} |
|
1104 | ||
1105 | ! |
summ_fn <- if (input$count_type == "counts") { |
1106 | ! |
function(x) sum(is.na(x)) |
1107 |
} else { |
|
1108 | ! |
function(x) round(sum(is.na(x)) / length(x), 4) |
1109 |
} |
|
1110 | ||
1111 | ! |
qenv <- if (!is.null(group_var)) { |
1112 | ! |
teal.code::eval_code( |
1113 | ! |
common_code_q(), |
1114 | ! |
substitute( |
1115 | ! |
expr = { |
1116 | ! |
summary_data <- ANL %>% |
1117 | ! |
dplyr::mutate(group_var_name := forcats::fct_na_value_to_level(as.factor(group_var_name), "NA")) %>% |
1118 | ! |
dplyr::group_by_at(group_var) %>% |
1119 | ! |
dplyr::filter(group_var_name %in% group_vals) |
1120 | ||
1121 | ! |
count_data <- dplyr::summarise(summary_data, n = dplyr::n()) |
1122 | ||
1123 | ! |
summary_data <- dplyr::summarise_all(summary_data, summ_fn) %>% |
1124 | ! |
dplyr::mutate(group_var_name := paste0(group_var, ":", group_var_name, "(N=", count_data$n, ")")) %>% |
1125 | ! |
tidyr::pivot_longer(!dplyr::all_of(group_var), names_to = "Variable", values_to = "out") %>% |
1126 | ! |
tidyr::pivot_wider(names_from = group_var, values_from = "out") %>% |
1127 | ! |
dplyr::mutate(`Variable label` = create_cols_labels(Variable, just_label = TRUE), .after = Variable) |
1128 |
}, |
|
1129 | ! |
env = list( |
1130 | ! |
group_var = group_var, group_var_name = as.name(group_var), group_vals = group_vals, summ_fn = summ_fn |
1131 |
) |
|
1132 |
) |
|
1133 |
) |
|
1134 |
} else { |
|
1135 | ! |
teal.code::eval_code( |
1136 | ! |
common_code_q(), |
1137 | ! |
substitute( |
1138 | ! |
expr = summary_data <- ANL %>% |
1139 | ! |
dplyr::summarise_all(summ_fn) %>% |
1140 | ! |
tidyr::pivot_longer(dplyr::everything(), |
1141 | ! |
names_to = "Variable", |
1142 | ! |
values_to = paste0("Missing (N=", nrow(ANL), ")") |
1143 |
) %>% |
|
1144 | ! |
dplyr::mutate(`Variable label` = create_cols_labels(Variable), .after = Variable), |
1145 | ! |
env = list(summ_fn = summ_fn) |
1146 |
) |
|
1147 |
) |
|
1148 |
} |
|
1149 | ||
1150 | ! |
within(qenv, table <- rlistings::as_listing(summary_data)) |
1151 |
}) |
|
1152 | ||
1153 | ! |
by_subject_plot_q <- reactive({ |
1154 |
# needed to trigger show r code update on tab change |
|
1155 | ! |
req(input$summary_type == "Grouped by Subject", common_code_q()) |
1156 | ||
1157 | ! |
teal::validate_has_data(data_r(), 1) |
1158 | ||
1159 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
1160 | ! |
labs = list(x = "", y = ""), |
1161 | ! |
theme = list(legend.position = "bottom", axis.text.x = quote(element_blank())) |
1162 |
) |
|
1163 | ||
1164 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
1165 | ! |
user_plot = ggplot2_args[["By Subject"]], |
1166 | ! |
user_default = ggplot2_args$default, |
1167 | ! |
module_plot = dev_ggplot2_args |
1168 |
) |
|
1169 | ||
1170 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
1171 | ! |
all_ggplot2_args, |
1172 | ! |
ggtheme = input$ggtheme |
1173 |
) |
|
1174 | ||
1175 |
# Unlikely that `rlang` is not available, new hashing may be expensive |
|
1176 | ! |
hashing_function <- if (requireNamespace("rlang", quietly = TRUE)) { |
1177 | ! |
quote(rlang::hash) |
1178 |
} else { |
|
1179 | ! |
function(x) paste(as.integer(x), collapse = "") |
1180 |
} |
|
1181 | ||
1182 | ! |
teal.code::eval_code( |
1183 | ! |
common_code_q(), |
1184 | ! |
substitute( |
1185 | ! |
expr = parent_keys <- keys, |
1186 | ! |
env = list(keys = data_parent_keys()) |
1187 |
) |
|
1188 |
) %>% |
|
1189 | ! |
teal.code::eval_code( |
1190 | ! |
substitute( |
1191 | ! |
expr = analysis_vars <- setdiff(colnames(ANL), data_keys), |
1192 | ! |
env = list(data_keys = data_keys()) |
1193 |
) |
|
1194 |
) %>% |
|
1195 | ! |
teal.code::eval_code( |
1196 | ! |
substitute( |
1197 | ! |
expr = { |
1198 | ! |
summary_plot_patients <- ANL[, c(parent_keys, analysis_vars)] %>% |
1199 | ! |
dplyr::group_by_at(parent_keys) %>% |
1200 | ! |
dplyr::mutate(id = dplyr::cur_group_id()) %>% |
1201 | ! |
dplyr::ungroup() %>% |
1202 | ! |
dplyr::group_by_at(c(parent_keys, "id")) %>% |
1203 | ! |
dplyr::summarise_all(anyNA) %>% |
1204 | ! |
dplyr::ungroup() |
1205 | ||
1206 |
# order subjects by decreasing number of missing and then by |
|
1207 |
# missingness pattern (defined using sha1) |
|
1208 | ! |
order_subjects <- summary_plot_patients %>% |
1209 | ! |
dplyr::select(-"id", -dplyr::all_of(parent_keys)) %>% |
1210 | ! |
dplyr::transmute( |
1211 | ! |
id = dplyr::row_number(), |
1212 | ! |
number_NA = apply(., 1, sum), |
1213 | ! |
sha = apply(., 1, hashing_function) |
1214 |
) %>% |
|
1215 | ! |
dplyr::arrange(dplyr::desc(number_NA), sha) %>% |
1216 | ! |
getElement(name = "id") |
1217 | ||
1218 |
# order columns by decreasing percent of missing values |
|
1219 | ! |
ordered_columns <- summary_plot_patients %>% |
1220 | ! |
dplyr::select(-"id", -dplyr::all_of(parent_keys)) %>% |
1221 | ! |
dplyr::summarise( |
1222 | ! |
column = create_cols_labels(colnames(.)), |
1223 | ! |
na_count = apply(., MARGIN = 2, FUN = sum), |
1224 | ! |
na_percent = na_count / nrow(.) * 100 |
1225 |
) %>% |
|
1226 | ! |
dplyr::arrange(na_percent, dplyr::desc(column)) |
1227 | ||
1228 | ! |
summary_plot_patients <- summary_plot_patients %>% |
1229 | ! |
tidyr::gather("col", "isna", -"id", -dplyr::all_of(parent_keys)) %>% |
1230 | ! |
dplyr::mutate(col = create_cols_labels(col)) |
1231 |
}, |
|
1232 | ! |
env = list(hashing_function = hashing_function) |
1233 |
) |
|
1234 |
) %>% |
|
1235 | ! |
teal.code::eval_code( |
1236 | ! |
substitute( |
1237 | ! |
expr = { |
1238 | ! |
by_subject_plot <- ggplot(summary_plot_patients, aes( |
1239 | ! |
x = factor(id, levels = order_subjects), |
1240 | ! |
y = factor(col, levels = ordered_columns[["column"]]), |
1241 | ! |
fill = isna |
1242 |
)) + |
|
1243 | ! |
geom_raster() + |
1244 | ! |
annotate( |
1245 | ! |
"text", |
1246 | ! |
x = length(order_subjects), |
1247 | ! |
y = seq_len(nrow(ordered_columns)), |
1248 | ! |
hjust = 1, |
1249 | ! |
label = sprintf("%d [%.02f%%]", ordered_columns[["na_count"]], ordered_columns[["na_percent"]]) |
1250 |
) + |
|
1251 | ! |
scale_fill_manual( |
1252 | ! |
name = "", |
1253 | ! |
values = c("grey90", c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]), |
1254 | ! |
labels = c("Present", "Missing (at least one)") |
1255 |
) + |
|
1256 | ! |
labs + |
1257 | ! |
ggthemes + |
1258 | ! |
themes |
1259 |
}, |
|
1260 | ! |
env = list( |
1261 | ! |
labs = parsed_ggplot2_args$labs, |
1262 | ! |
themes = parsed_ggplot2_args$theme, |
1263 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
1264 |
) |
|
1265 |
) |
|
1266 |
) |
|
1267 |
}) |
|
1268 | ||
1269 |
# Decorated outputs |
|
1270 | ||
1271 |
# Summary_plot_q |
|
1272 | ! |
decorated_summary_plot_q <- srv_decorate_teal_data( |
1273 | ! |
id = "dec_summary_plot", |
1274 | ! |
data = summary_plot_q, |
1275 | ! |
decorators = select_decorators(decorators, "summary_plot"), |
1276 | ! |
expr = { |
1277 | ! |
grid::grid.newpage() |
1278 | ! |
grid::grid.draw(summary_plot) |
1279 |
} |
|
1280 |
) |
|
1281 | ||
1282 | ! |
decorated_combination_plot_q <- srv_decorate_teal_data( |
1283 | ! |
id = "dec_combination_plot", |
1284 | ! |
data = combination_plot_q, |
1285 | ! |
decorators = select_decorators(decorators, "combination_plot"), |
1286 | ! |
expr = { |
1287 | ! |
grid::grid.newpage() |
1288 | ! |
grid::grid.draw(combination_plot) |
1289 |
} |
|
1290 |
) |
|
1291 | ||
1292 | ! |
decorated_summary_table_q <- srv_decorate_teal_data( |
1293 | ! |
id = "dec_summary_table", |
1294 | ! |
data = summary_table_q, |
1295 | ! |
decorators = select_decorators(decorators, "table"), |
1296 | ! |
expr = table |
1297 |
) |
|
1298 | ||
1299 | ! |
decorated_by_subject_plot_q <- srv_decorate_teal_data( |
1300 | ! |
id = "dec_by_subject_plot", |
1301 | ! |
data = by_subject_plot_q, |
1302 | ! |
decorators = select_decorators(decorators, "by_subject_plot"), |
1303 | ! |
expr = print(by_subject_plot) |
1304 |
) |
|
1305 | ||
1306 |
# Plots & tables reactives |
|
1307 | ||
1308 | ! |
summary_plot_r <- reactive({ |
1309 | ! |
req(decorated_summary_plot_q())[["summary_plot"]] |
1310 |
}) |
|
1311 | ||
1312 | ! |
combination_plot_r <- reactive({ |
1313 | ! |
req(decorated_combination_plot_q())[["combination_plot"]] |
1314 |
}) |
|
1315 | ||
1316 | ! |
summary_table_r <- reactive({ |
1317 | ! |
req(decorated_summary_table_q()) |
1318 | ||
1319 | ! |
if (length(input$variables_select) == 0) { |
1320 |
# so that zeroRecords message gets printed |
|
1321 |
# using tibble as it supports weird column names, such as " " |
|
1322 | ! |
DT::datatable( |
1323 | ! |
tibble::tibble(` ` = logical(0)), |
1324 | ! |
options = list(language = list(zeroRecords = "No variable selected."), pageLength = input$levels_table_rows) |
1325 |
) |
|
1326 |
} else { |
|
1327 | ! |
DT::datatable(decorated_summary_table_q()[["summary_data"]]) |
1328 |
} |
|
1329 |
}) |
|
1330 | ||
1331 | ! |
by_subject_plot_r <- reactive({ |
1332 | ! |
req(decorated_by_subject_plot_q()[["by_subject_plot"]]) |
1333 |
}) |
|
1334 | ||
1335 |
# Generate output |
|
1336 | ! |
pws1 <- teal.widgets::plot_with_settings_srv( |
1337 | ! |
id = "summary_plot", |
1338 | ! |
plot_r = summary_plot_r, |
1339 | ! |
height = plot_height, |
1340 | ! |
width = plot_width |
1341 |
) |
|
1342 | ||
1343 | ! |
pws2 <- teal.widgets::plot_with_settings_srv( |
1344 | ! |
id = "combination_plot", |
1345 | ! |
plot_r = combination_plot_r, |
1346 | ! |
height = plot_height, |
1347 | ! |
width = plot_width |
1348 |
) |
|
1349 | ||
1350 | ! |
output$levels_table <- DT::renderDataTable(summary_table_r()) |
1351 | ||
1352 | ! |
pws3 <- teal.widgets::plot_with_settings_srv( |
1353 | ! |
id = "by_subject_plot", |
1354 | ! |
plot_r = by_subject_plot_r, |
1355 | ! |
height = plot_height, |
1356 | ! |
width = plot_width |
1357 |
) |
|
1358 | ||
1359 | ! |
decorated_final_q <- reactive({ |
1360 | ! |
sum_type <- req(input$summary_type) |
1361 | ! |
if (sum_type == "Summary") { |
1362 | ! |
decorated_summary_plot_q() |
1363 | ! |
} else if (sum_type == "Combinations") { |
1364 | ! |
decorated_combination_plot_q() |
1365 | ! |
} else if (sum_type == "By Variable Levels") { |
1366 | ! |
decorated_summary_table_q() |
1367 | ! |
} else if (sum_type == "Grouped by Subject") { |
1368 | ! |
decorated_by_subject_plot_q() |
1369 |
} |
|
1370 |
}) |
|
1371 | ||
1372 |
# Render R code. |
|
1373 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_final_q()))) |
1374 | ||
1375 | ! |
teal.widgets::verbatim_popup_srv( |
1376 | ! |
id = "rcode", |
1377 | ! |
verbatim_content = source_code_r, |
1378 | ! |
title = "Show R Code for Missing Data" |
1379 |
) |
|
1380 | ||
1381 |
### REPORTER |
|
1382 | ! |
if (with_reporter) { |
1383 | ! |
card_fun <- function(comment, label) { |
1384 | ! |
card <- teal::TealReportCard$new() |
1385 | ! |
sum_type <- input$summary_type |
1386 | ! |
title <- if (sum_type == "By Variable Levels") paste0(sum_type, " Table") else paste0(sum_type, " Plot") |
1387 | ! |
title_dataname <- paste(title, dataname, sep = " - ") |
1388 | ! |
label <- if (label == "") { |
1389 | ! |
paste("Missing Data", sum_type, dataname, sep = " - ") |
1390 |
} else { |
|
1391 | ! |
label |
1392 |
} |
|
1393 | ! |
card$set_name(label) |
1394 | ! |
card$append_text(title_dataname, "header2") |
1395 | ! |
if (with_filter) card$append_fs(filter_panel_api$get_filter_state()) |
1396 | ! |
if (sum_type == "Summary") { |
1397 | ! |
card$append_text("Plot", "header3") |
1398 | ! |
card$append_plot(summary_plot_r(), dim = pws1$dim()) |
1399 | ! |
} else if (sum_type == "Combinations") { |
1400 | ! |
card$append_text("Plot", "header3") |
1401 | ! |
card$append_plot(combination_plot_r(), dim = pws2$dim()) |
1402 | ! |
} else if (sum_type == "By Variable Levels") { |
1403 | ! |
card$append_text("Table", "header3") |
1404 | ! |
table <- decorated_summary_table_q()[["table"]] |
1405 | ! |
if (nrow(table) == 0L) { |
1406 | ! |
card$append_text("No data available for table.") |
1407 |
} else { |
|
1408 | ! |
card$append_table(table) |
1409 |
} |
|
1410 | ! |
} else if (sum_type == "Grouped by Subject") { |
1411 | ! |
card$append_text("Plot", "header3") |
1412 | ! |
card$append_plot(by_subject_plot_r(), dim = pws3$dim()) |
1413 |
} |
|
1414 | ! |
if (!comment == "") { |
1415 | ! |
card$append_text("Comment", "header3") |
1416 | ! |
card$append_text(comment) |
1417 |
} |
|
1418 | ! |
card$append_src(source_code_r()) |
1419 | ! |
card |
1420 |
} |
|
1421 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
1422 |
} |
|
1423 |
### |
|
1424 |
}) |
|
1425 |
} |
1 |
#' `teal` module: Front page |
|
2 |
#' |
|
3 |
#' Creates a simple front page for `teal` applications, displaying |
|
4 |
#' introductory text, tables, additional `html` or `shiny` tags, and footnotes. |
|
5 |
#' |
|
6 |
#' @inheritParams teal::module |
|
7 |
#' @param header_text (`character` vector) text to be shown at the top of the module, for each |
|
8 |
#' element, if named the name is shown first in bold as a header followed by the value. The first |
|
9 |
#' element's header is displayed larger than the others. |
|
10 |
#' @param tables (`named list` of `data.frame`s) tables to be shown in the module. |
|
11 |
#' @param additional_tags (`shiny.tag.list` or `html`) additional `shiny` tags or `html` to be included after the table, |
|
12 |
#' for example to include an image, `tagList(tags$img(src = "image.png"))` or to include further `html`, |
|
13 |
#' `HTML("html text here")`. |
|
14 |
#' @param footnotes (`character` vector) of text to be shown at the bottom of the module, for each |
|
15 |
#' element, if named the name is shown first in bold, followed by the value. |
|
16 |
#' @param show_metadata (`logical`) `r lifecycle::badge("deprecated")` indicating |
|
17 |
#' whether the metadata of the datasets be available on the module. |
|
18 |
#' Metadata shown automatically when `datanames` set. |
|
19 |
#' @inheritParams tm_variable_browser |
|
20 |
#' |
|
21 |
#' @inherit shared_params return |
|
22 |
#' |
|
23 |
#' @examplesShinylive |
|
24 |
#' library(teal.modules.general) |
|
25 |
#' interactive <- function() TRUE |
|
26 |
#' {{ next_example }} |
|
27 |
#' @examples |
|
28 |
#' data <- teal_data() |
|
29 |
#' data <- within(data, { |
|
30 |
#' require(nestcolor) |
|
31 |
#' ADSL <- teal.data::rADSL |
|
32 |
#' attr(ADSL, "metadata") <- list("Author" = "NEST team", "data_source" = "synthetic data") |
|
33 |
#' }) |
|
34 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
35 |
#' |
|
36 |
#' table_1 <- data.frame(Info = c("A", "B"), Text = c("A", "B")) |
|
37 |
#' table_2 <- data.frame(`Column 1` = c("C", "D"), `Column 2` = c(5.5, 6.6), `Column 3` = c("A", "B")) |
|
38 |
#' table_3 <- data.frame(Info = c("E", "F"), Text = c("G", "H")) |
|
39 |
#' |
|
40 |
#' table_input <- list( |
|
41 |
#' "Table 1" = table_1, |
|
42 |
#' "Table 2" = table_2, |
|
43 |
#' "Table 3" = table_3 |
|
44 |
#' ) |
|
45 |
#' |
|
46 |
#' app <- init( |
|
47 |
#' data = data, |
|
48 |
#' modules = modules( |
|
49 |
#' tm_front_page( |
|
50 |
#' header_text = c( |
|
51 |
#' "Important information" = "It can go here.", |
|
52 |
#' "Other information" = "Can go here." |
|
53 |
#' ), |
|
54 |
#' tables = table_input, |
|
55 |
#' additional_tags = HTML("Additional HTML or shiny tags go here <br>"), |
|
56 |
#' footnotes = c("X" = "is the first footnote", "Y is the second footnote") |
|
57 |
#' ) |
|
58 |
#' ) |
|
59 |
#' ) |> |
|
60 |
#' modify_header(tags$h1("Sample Application")) |> |
|
61 |
#' modify_footer(tags$p("Application footer")) |
|
62 |
#' |
|
63 |
#' if (interactive()) { |
|
64 |
#' shinyApp(app$ui, app$server) |
|
65 |
#' } |
|
66 |
#' |
|
67 |
#' @export |
|
68 |
#' |
|
69 |
tm_front_page <- function(label = "Front page", |
|
70 |
header_text = character(0), |
|
71 |
tables = list(), |
|
72 |
additional_tags = tagList(), |
|
73 |
footnotes = character(0), |
|
74 |
show_metadata = deprecated(), |
|
75 |
datanames = if (missing(show_metadata)) NULL else "all", |
|
76 |
transformators = list()) { |
|
77 | ! |
message("Initializing tm_front_page") |
78 | ||
79 |
# Start of assertions |
|
80 | ! |
checkmate::assert_string(label) |
81 | ! |
checkmate::assert_character(header_text, min.len = 0, any.missing = FALSE) |
82 | ! |
checkmate::assert_list(tables, types = "data.frame", names = "named", any.missing = FALSE) |
83 | ! |
checkmate::assert_multi_class(additional_tags, classes = c("shiny.tag.list", "html")) |
84 | ! |
checkmate::assert_character(footnotes, min.len = 0, any.missing = FALSE) |
85 | ! |
if (!missing(show_metadata)) { |
86 | ! |
lifecycle::deprecate_soft( |
87 | ! |
when = "0.4.0", |
88 | ! |
what = "tm_front_page(show_metadata)", |
89 | ! |
with = "tm_front_page(datanames)", |
90 | ! |
details = c( |
91 | ! |
"With `datanames` you can select which datasets are displayed.", |
92 | ! |
i = "Use `tm_front_page(datanames = 'all')` to keep the previous behavior and avoid this warning." |
93 |
) |
|
94 |
) |
|
95 |
} |
|
96 | ! |
checkmate::assert_character(datanames, min.len = 0, min.chars = 1, null.ok = TRUE) |
97 | ||
98 |
# End of assertions |
|
99 | ||
100 |
# Make UI args |
|
101 | ! |
args <- as.list(environment()) |
102 | ||
103 | ! |
ans <- module( |
104 | ! |
label = label, |
105 | ! |
server = srv_front_page, |
106 | ! |
ui = ui_front_page, |
107 | ! |
ui_args = args, |
108 | ! |
server_args = list(tables = tables), |
109 | ! |
datanames = datanames, , |
110 | ! |
transformators = transformators |
111 |
) |
|
112 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
113 | ! |
ans |
114 |
} |
|
115 | ||
116 |
# UI function for the front page module |
|
117 |
ui_front_page <- function(id, ...) { |
|
118 | ! |
args <- list(...) |
119 | ! |
ns <- NS(id) |
120 | ||
121 | ! |
tagList( |
122 | ! |
include_css_files("custom"), |
123 | ! |
tags$div( |
124 | ! |
id = "front_page_content", |
125 | ! |
class = "ml-8", |
126 | ! |
tags$div( |
127 | ! |
id = "front_page_headers", |
128 | ! |
get_header_tags(args$header_text) |
129 |
), |
|
130 | ! |
tags$div( |
131 | ! |
id = "front_page_tables", |
132 | ! |
class = "ml-4", |
133 | ! |
get_table_tags(args$tables, ns) |
134 |
), |
|
135 | ! |
tags$div( |
136 | ! |
id = "front_page_custom_html", |
137 | ! |
class = "my-4", |
138 | ! |
args$additional_tags |
139 |
), |
|
140 | ! |
if (length(args$datanames) > 0L) { |
141 | ! |
tags$div( |
142 | ! |
id = "front_page_metabutton", |
143 | ! |
class = "m-4", |
144 | ! |
actionButton(ns("metadata_button"), "Show metadata") |
145 |
) |
|
146 |
}, |
|
147 | ! |
tags$footer( |
148 | ! |
class = ".small", |
149 | ! |
get_footer_tags(args$footnotes) |
150 |
) |
|
151 |
) |
|
152 |
) |
|
153 |
} |
|
154 | ||
155 |
# Server function for the front page module |
|
156 |
srv_front_page <- function(id, data, tables) { |
|
157 | ! |
checkmate::assert_class(data, "reactive") |
158 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
159 | ! |
moduleServer(id, function(input, output, session) { |
160 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
161 | ||
162 | ! |
ns <- session$ns |
163 | ||
164 | ! |
setBookmarkExclude("metadata_button") |
165 | ||
166 | ! |
lapply(seq_along(tables), function(idx) { |
167 | ! |
output[[paste0("table_", idx)]] <- renderTable( |
168 | ! |
tables[[idx]], |
169 | ! |
bordered = TRUE, |
170 | ! |
caption = names(tables)[idx], |
171 | ! |
caption.placement = "top" |
172 |
) |
|
173 |
}) |
|
174 | ! |
if (length(isolate(names(data()))) > 0L) { |
175 | ! |
observeEvent( |
176 | ! |
input$metadata_button, showModal( |
177 | ! |
modalDialog( |
178 | ! |
title = "Metadata", |
179 | ! |
dataTableOutput(ns("metadata_table")), |
180 | ! |
size = "l", |
181 | ! |
easyClose = TRUE |
182 |
) |
|
183 |
) |
|
184 |
) |
|
185 | ||
186 | ! |
metadata_data_frame <- reactive({ |
187 | ! |
datanames <- names(data()) |
188 | ! |
convert_metadata_to_dataframe( |
189 | ! |
lapply(datanames, function(dataname) attr(data()[[dataname]], "metadata")), |
190 | ! |
datanames |
191 |
) |
|
192 |
}) |
|
193 | ||
194 | ! |
output$metadata_table <- renderDataTable({ |
195 | ! |
validate(need(nrow(metadata_data_frame()) > 0, "The data has no associated metadata")) |
196 | ! |
metadata_data_frame() |
197 |
}) |
|
198 |
} |
|
199 |
}) |
|
200 |
} |
|
201 | ||
202 |
## utils functions |
|
203 | ||
204 |
get_header_tags <- function(header_text) { |
|
205 | ! |
if (length(header_text) == 0) { |
206 | ! |
return(list()) |
207 |
} |
|
208 | ||
209 | ! |
get_single_header_tags <- function(header_text, p_text, header_tag = tags$h4) { |
210 | ! |
tagList( |
211 | ! |
tags$div( |
212 | ! |
if (!is.null(header_text) && nchar(header_text) > 0) header_tag(header_text), |
213 | ! |
tags$p(p_text) |
214 |
) |
|
215 |
) |
|
216 |
} |
|
217 | ||
218 | ! |
header_tags <- get_single_header_tags(names(header_text[1]), header_text[1], header_tag = tags$h3) |
219 | ! |
c(header_tags, mapply(get_single_header_tags, utils::tail(names(header_text), -1), utils::tail(header_text, -1))) |
220 |
} |
|
221 | ||
222 |
get_table_tags <- function(tables, ns) { |
|
223 | ! |
if (length(tables) == 0) { |
224 | ! |
return(list()) |
225 |
} |
|
226 | ! |
table_tags <- c(lapply(seq_along(tables), function(idx) { |
227 | ! |
list( |
228 | ! |
tableOutput(ns(paste0("table_", idx))) |
229 |
) |
|
230 |
})) |
|
231 | ! |
return(table_tags) |
232 |
} |
|
233 | ||
234 |
get_footer_tags <- function(footnotes) { |
|
235 | ! |
if (length(footnotes) == 0) { |
236 | ! |
return(list()) |
237 |
} |
|
238 | ! |
bold_texts <- if (is.null(names(footnotes))) rep("", length(footnotes)) else names(footnotes) |
239 | ! |
footnote_tags <- mapply(function(bold_text, value) { |
240 | ! |
list( |
241 | ! |
tags$div( |
242 | ! |
tags$b(bold_text), |
243 | ! |
value, |
244 | ! |
tags$br() |
245 |
) |
|
246 |
) |
|
247 | ! |
}, bold_text = bold_texts, value = footnotes) |
248 |
} |
|
249 | ||
250 |
# take a list of metadata, one item per dataset (raw_metadata each element from datasets$get_metadata()) |
|
251 |
# and the corresponding datanames and output a data.frame with columns {Dataset, Name, Value}. |
|
252 |
# which are, the Dataset the metadata came from, the metadata's name and value |
|
253 |
convert_metadata_to_dataframe <- function(raw_metadata, datanames) { |
|
254 | 4x |
output <- mapply(function(metadata, dataname) { |
255 | 6x |
if (is.null(metadata)) { |
256 | 2x |
return(data.frame(Dataset = character(0), Name = character(0), Value = character(0))) |
257 |
} |
|
258 | 4x |
return(data.frame( |
259 | 4x |
Dataset = dataname, |
260 | 4x |
Name = names(metadata), |
261 | 4x |
Value = unname(unlist(lapply(metadata, as.character))) |
262 |
)) |
|
263 | 4x |
}, raw_metadata, datanames, SIMPLIFY = FALSE) |
264 | 4x |
do.call(rbind, output) |
265 |
} |
1 |
#' `teal` module: Stack plots of variables and show association with reference variable |
|
2 |
#' |
|
3 |
#' Module provides functionality for visualizing the distribution of variables and |
|
4 |
#' their association with a reference variable. |
|
5 |
#' It supports configuring the appearance of the plots, including themes and whether to show associations. |
|
6 |
#' |
|
7 |
#' |
|
8 |
#' @note For more examples, please see the vignette "Using association plot" via |
|
9 |
#' `vignette("using-association-plot", package = "teal.modules.general")`. |
|
10 |
#' |
|
11 |
#' @inheritParams teal::module |
|
12 |
#' @inheritParams shared_params |
|
13 |
#' @param ref (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
14 |
#' Reference variable, must accepts a `data_extract_spec` with `select_spec(multiple = FALSE)` |
|
15 |
#' to ensure single selection option. |
|
16 |
#' @param vars (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
17 |
#' Variables to be associated with the reference variable. |
|
18 |
#' @param show_association (`logical`) optional, whether show association of `vars` |
|
19 |
#' with reference variable. Defaults to `TRUE`. |
|
20 |
#' @param distribution_theme,association_theme (`character`) optional, `ggplot2` themes to be used by default. |
|
21 |
#' Default to `"gray"`. |
|
22 |
#' |
|
23 |
#' @param ggplot2_args `r roxygen_ggplot2_args_param("Bivariate1", "Bivariate2")` |
|
24 |
#' |
|
25 |
#' @inherit shared_params return |
|
26 |
#' |
|
27 |
#' @section Decorating Module: |
|
28 |
#' |
|
29 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
30 |
#' - `plot` (`grob` created with [ggplot2::ggplotGrob()]) |
|
31 |
#' |
|
32 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
33 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
34 |
#' See code snippet below: |
|
35 |
#' |
|
36 |
#' ``` |
|
37 |
#' tm_g_association( |
|
38 |
#' ..., # arguments for module |
|
39 |
#' decorators = list( |
|
40 |
#' plot = teal_transform_module(...) # applied to the `plot` output |
|
41 |
#' ) |
|
42 |
#' ) |
|
43 |
#' ``` |
|
44 |
#' |
|
45 |
#' For additional details and examples of decorators, refer to the vignette |
|
46 |
#' `vignette("decorate-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 |
#' # general data example |
|
54 |
#' data <- teal_data() |
|
55 |
#' data <- within(data, { |
|
56 |
#' require(nestcolor) |
|
57 |
#' CO2 <- CO2 |
|
58 |
#' factors <- names(Filter(isTRUE, vapply(CO2, is.factor, logical(1L)))) |
|
59 |
#' CO2[factors] <- lapply(CO2[factors], as.character) |
|
60 |
#' }) |
|
61 |
#' |
|
62 |
#' app <- init( |
|
63 |
#' data = data, |
|
64 |
#' modules = modules( |
|
65 |
#' tm_g_association( |
|
66 |
#' ref = data_extract_spec( |
|
67 |
#' dataname = "CO2", |
|
68 |
#' select = select_spec( |
|
69 |
#' label = "Select variable:", |
|
70 |
#' choices = variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment")), |
|
71 |
#' selected = "Plant", |
|
72 |
#' fixed = FALSE |
|
73 |
#' ) |
|
74 |
#' ), |
|
75 |
#' vars = data_extract_spec( |
|
76 |
#' dataname = "CO2", |
|
77 |
#' select = select_spec( |
|
78 |
#' label = "Select variables:", |
|
79 |
#' choices = variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment")), |
|
80 |
#' selected = "Treatment", |
|
81 |
#' multiple = TRUE, |
|
82 |
#' fixed = FALSE |
|
83 |
#' ) |
|
84 |
#' ) |
|
85 |
#' ) |
|
86 |
#' ) |
|
87 |
#' ) |
|
88 |
#' if (interactive()) { |
|
89 |
#' shinyApp(app$ui, app$server) |
|
90 |
#' } |
|
91 |
#' |
|
92 |
#' @examplesShinylive |
|
93 |
#' library(teal.modules.general) |
|
94 |
#' interactive <- function() TRUE |
|
95 |
#' {{ next_example }} |
|
96 |
#' @examples |
|
97 |
#' # CDISC data example |
|
98 |
#' data <- teal_data() |
|
99 |
#' data <- within(data, { |
|
100 |
#' require(nestcolor) |
|
101 |
#' ADSL <- teal.data::rADSL |
|
102 |
#' }) |
|
103 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
104 |
#' |
|
105 |
#' app <- init( |
|
106 |
#' data = data, |
|
107 |
#' modules = modules( |
|
108 |
#' tm_g_association( |
|
109 |
#' ref = data_extract_spec( |
|
110 |
#' dataname = "ADSL", |
|
111 |
#' select = select_spec( |
|
112 |
#' label = "Select variable:", |
|
113 |
#' choices = variable_choices( |
|
114 |
#' data[["ADSL"]], |
|
115 |
#' c("SEX", "RACE", "COUNTRY", "ARM", "STRATA1", "STRATA2", "ITTFL", "BMRKR2") |
|
116 |
#' ), |
|
117 |
#' selected = "RACE", |
|
118 |
#' fixed = FALSE |
|
119 |
#' ) |
|
120 |
#' ), |
|
121 |
#' vars = data_extract_spec( |
|
122 |
#' dataname = "ADSL", |
|
123 |
#' select = select_spec( |
|
124 |
#' label = "Select variables:", |
|
125 |
#' choices = variable_choices( |
|
126 |
#' data[["ADSL"]], |
|
127 |
#' c("SEX", "RACE", "COUNTRY", "ARM", "STRATA1", "STRATA2", "ITTFL", "BMRKR2") |
|
128 |
#' ), |
|
129 |
#' selected = "BMRKR2", |
|
130 |
#' multiple = TRUE, |
|
131 |
#' fixed = FALSE |
|
132 |
#' ) |
|
133 |
#' ) |
|
134 |
#' ) |
|
135 |
#' ) |
|
136 |
#' ) |
|
137 |
#' if (interactive()) { |
|
138 |
#' shinyApp(app$ui, app$server) |
|
139 |
#' } |
|
140 |
#' |
|
141 |
#' @export |
|
142 |
#' |
|
143 |
tm_g_association <- function(label = "Association", |
|
144 |
ref, |
|
145 |
vars, |
|
146 |
show_association = TRUE, |
|
147 |
plot_height = c(600, 400, 5000), |
|
148 |
plot_width = NULL, |
|
149 |
distribution_theme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), # nolint: line_length. |
|
150 |
association_theme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), # nolint: line_length. |
|
151 |
pre_output = NULL, |
|
152 |
post_output = NULL, |
|
153 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
154 |
transformators = list(), |
|
155 |
decorators = list()) { |
|
156 | ! |
message("Initializing tm_g_association") |
157 | ||
158 |
# Normalize the parameters |
|
159 | ! |
if (inherits(ref, "data_extract_spec")) ref <- list(ref) |
160 | ! |
if (inherits(vars, "data_extract_spec")) vars <- list(vars) |
161 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
162 | ||
163 |
# Start of assertions |
|
164 | ! |
checkmate::assert_string(label) |
165 | ||
166 | ! |
checkmate::assert_list(ref, types = "data_extract_spec") |
167 | ! |
if (!all(vapply(ref, function(x) !x$select$multiple, logical(1)))) { |
168 | ! |
stop("'ref' should not allow multiple selection") |
169 |
} |
|
170 | ||
171 | ! |
checkmate::assert_list(vars, types = "data_extract_spec") |
172 | ! |
checkmate::assert_flag(show_association) |
173 | ||
174 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
175 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
176 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
177 | ! |
checkmate::assert_numeric( |
178 | ! |
plot_width[1], |
179 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
180 |
) |
|
181 | ||
182 | ! |
distribution_theme <- match.arg(distribution_theme) |
183 | ! |
association_theme <- match.arg(association_theme) |
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 | ! |
plot_choices <- c("Bivariate1", "Bivariate2") |
189 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
190 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
191 | ||
192 | ! |
assert_decorators(decorators, "plot") |
193 |
# End of assertions |
|
194 | ||
195 |
# Make UI args |
|
196 | ! |
args <- as.list(environment()) |
197 | ||
198 | ! |
data_extract_list <- list( |
199 | ! |
ref = ref, |
200 | ! |
vars = vars |
201 |
) |
|
202 | ||
203 | ! |
ans <- module( |
204 | ! |
label = label, |
205 | ! |
server = srv_tm_g_association, |
206 | ! |
ui = ui_tm_g_association, |
207 | ! |
ui_args = args, |
208 | ! |
server_args = c( |
209 | ! |
data_extract_list, |
210 | ! |
list(plot_height = plot_height, plot_width = plot_width, ggplot2_args = ggplot2_args, decorators = decorators) |
211 |
), |
|
212 | ! |
transformators = transformators, |
213 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
214 |
) |
|
215 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
216 | ! |
ans |
217 |
} |
|
218 | ||
219 |
# UI function for the association module |
|
220 |
ui_tm_g_association <- function(id, ...) { |
|
221 | ! |
ns <- NS(id) |
222 | ! |
args <- list(...) |
223 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$ref, args$vars) |
224 | ||
225 | ! |
teal.widgets::standard_layout( |
226 | ! |
output = teal.widgets::white_small_well( |
227 | ! |
textOutput(ns("title")), |
228 | ! |
tags$br(), |
229 | ! |
teal.widgets::plot_with_settings_ui(id = ns("myplot")) |
230 |
), |
|
231 | ! |
encoding = tags$div( |
232 |
### Reporter |
|
233 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
234 |
### |
|
235 | ! |
tags$label("Encodings", class = "text-primary"), |
236 | ! |
teal.transform::datanames_input(args[c("ref", "vars")]), |
237 | ! |
teal.transform::data_extract_ui( |
238 | ! |
id = ns("ref"), |
239 | ! |
label = "Reference variable", |
240 | ! |
data_extract_spec = args$ref, |
241 | ! |
is_single_dataset = is_single_dataset_value |
242 |
), |
|
243 | ! |
teal.transform::data_extract_ui( |
244 | ! |
id = ns("vars"), |
245 | ! |
label = "Associated variables", |
246 | ! |
data_extract_spec = args$vars, |
247 | ! |
is_single_dataset = is_single_dataset_value |
248 |
), |
|
249 | ! |
checkboxInput( |
250 | ! |
ns("association"), |
251 | ! |
"Association with reference variable", |
252 | ! |
value = args$show_association |
253 |
), |
|
254 | ! |
checkboxInput( |
255 | ! |
ns("show_dist"), |
256 | ! |
"Scaled frequencies", |
257 | ! |
value = FALSE |
258 |
), |
|
259 | ! |
checkboxInput( |
260 | ! |
ns("log_transformation"), |
261 | ! |
"Log transformed", |
262 | ! |
value = FALSE |
263 |
), |
|
264 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")), |
265 | ! |
teal.widgets::panel_group( |
266 | ! |
teal.widgets::panel_item( |
267 | ! |
title = "Plot settings", |
268 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("alpha"), "Scatterplot opacity:", c(0.5, 0, 1), ticks = FALSE), |
269 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("size"), "Scatterplot points size:", c(2, 1, 8), ticks = FALSE), |
270 | ! |
checkboxInput(ns("swap_axes"), "Swap axes", value = FALSE), |
271 | ! |
checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = FALSE), |
272 | ! |
selectInput( |
273 | ! |
inputId = ns("distribution_theme"), |
274 | ! |
label = "Distribution theme (by ggplot):", |
275 | ! |
choices = ggplot_themes, |
276 | ! |
selected = args$distribution_theme, |
277 | ! |
multiple = FALSE |
278 |
), |
|
279 | ! |
selectInput( |
280 | ! |
inputId = ns("association_theme"), |
281 | ! |
label = "Association theme (by ggplot):", |
282 | ! |
choices = ggplot_themes, |
283 | ! |
selected = args$association_theme, |
284 | ! |
multiple = FALSE |
285 |
) |
|
286 |
) |
|
287 |
) |
|
288 |
), |
|
289 | ! |
forms = tagList( |
290 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
291 |
), |
|
292 | ! |
pre_output = args$pre_output, |
293 | ! |
post_output = args$post_output |
294 |
) |
|
295 |
} |
|
296 | ||
297 |
# Server function for the association module |
|
298 |
srv_tm_g_association <- function(id, |
|
299 |
data, |
|
300 |
reporter, |
|
301 |
filter_panel_api, |
|
302 |
ref, |
|
303 |
vars, |
|
304 |
plot_height, |
|
305 |
plot_width, |
|
306 |
ggplot2_args, |
|
307 |
decorators) { |
|
308 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
309 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
310 | ! |
checkmate::assert_class(data, "reactive") |
311 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
312 | ||
313 | ! |
moduleServer(id, function(input, output, session) { |
314 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
315 | ||
316 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
317 | ! |
data_extract = list(ref = ref, vars = vars), |
318 | ! |
datasets = data, |
319 | ! |
select_validation_rule = list( |
320 | ! |
ref = shinyvalidate::compose_rules( |
321 | ! |
shinyvalidate::sv_required("A reference variable needs to be selected."), |
322 | ! |
~ if ((.) %in% selector_list()$vars()$select) { |
323 | ! |
"Associated variables and reference variable cannot overlap" |
324 |
} |
|
325 |
), |
|
326 | ! |
vars = shinyvalidate::compose_rules( |
327 | ! |
shinyvalidate::sv_required("An associated variable needs to be selected."), |
328 | ! |
~ if (length(selector_list()$ref()$select) != 0 && selector_list()$ref()$select %in% (.)) { |
329 | ! |
"Associated variables and reference variable cannot overlap" |
330 |
} |
|
331 |
) |
|
332 |
) |
|
333 |
) |
|
334 | ||
335 | ! |
iv_r <- reactive({ |
336 | ! |
iv <- shinyvalidate::InputValidator$new() |
337 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
338 |
}) |
|
339 | ||
340 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
341 | ! |
datasets = data, |
342 | ! |
selector_list = selector_list |
343 |
) |
|
344 | ||
345 | ! |
anl_merged_q <- reactive({ |
346 | ! |
req(anl_merged_input()) |
347 | ! |
data() %>% teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
348 |
}) |
|
349 | ||
350 | ! |
merged <- list( |
351 | ! |
anl_input_r = anl_merged_input, |
352 | ! |
anl_q_r = anl_merged_q |
353 |
) |
|
354 | ||
355 | ! |
output_q <- reactive({ |
356 | ! |
teal::validate_inputs(iv_r()) |
357 | ||
358 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
359 | ! |
teal::validate_has_data(ANL, 3) |
360 | ||
361 | ! |
vars_names <- merged$anl_input_r()$columns_source$vars |
362 | ||
363 | ! |
ref_name <- as.vector(merged$anl_input_r()$columns_source$ref) |
364 | ! |
association <- input$association |
365 | ! |
show_dist <- input$show_dist |
366 | ! |
log_transformation <- input$log_transformation |
367 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
368 | ! |
swap_axes <- input$swap_axes |
369 | ! |
distribution_theme <- input$distribution_theme |
370 | ! |
association_theme <- input$association_theme |
371 | ||
372 | ! |
is_scatterplot <- is.numeric(ANL[[ref_name]]) && any(vapply(ANL[vars_names], is.numeric, logical(1))) |
373 | ! |
if (is_scatterplot) { |
374 | ! |
shinyjs::show("alpha") |
375 | ! |
shinyjs::show("size") |
376 | ! |
alpha <- input$alpha |
377 | ! |
size <- input$size |
378 |
} else { |
|
379 | ! |
shinyjs::hide("alpha") |
380 | ! |
shinyjs::hide("size") |
381 | ! |
alpha <- 0.5 |
382 | ! |
size <- 2 |
383 |
} |
|
384 | ||
385 | ! |
teal::validate_has_data(ANL[, c(ref_name, vars_names)], 3, complete = TRUE, allow_inf = FALSE) |
386 | ||
387 |
# reference |
|
388 | ! |
ref_class <- class(ANL[[ref_name]])[1] |
389 | ! |
if (is.numeric(ANL[[ref_name]]) && log_transformation) { |
390 |
# works for both integers and doubles |
|
391 | ! |
ref_cl_name <- call("log", as.name(ref_name)) |
392 | ! |
ref_cl_lbl <- varname_w_label(ref_name, ANL, prefix = "Log of ") |
393 |
} else { |
|
394 |
# silently ignore when non-numeric even if `log` is selected because some |
|
395 |
# variables may be numeric and others not |
|
396 | ! |
ref_cl_name <- as.name(ref_name) |
397 | ! |
ref_cl_lbl <- varname_w_label(ref_name, ANL) |
398 |
} |
|
399 | ||
400 | ! |
user_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
401 | ! |
user_plot = ggplot2_args[["Bivariate1"]], |
402 | ! |
user_default = ggplot2_args$default |
403 |
) |
|
404 | ||
405 | ! |
ref_call <- bivariate_plot_call( |
406 | ! |
data_name = "ANL", |
407 | ! |
x = ref_cl_name, |
408 | ! |
x_class = ref_class, |
409 | ! |
x_label = ref_cl_lbl, |
410 | ! |
freq = !show_dist, |
411 | ! |
theme = distribution_theme, |
412 | ! |
rotate_xaxis_labels = rotate_xaxis_labels, |
413 | ! |
swap_axes = FALSE, |
414 | ! |
size = size, |
415 | ! |
alpha = alpha, |
416 | ! |
ggplot2_args = user_ggplot2_args |
417 |
) |
|
418 | ||
419 |
# association |
|
420 | ! |
ref_class_cov <- ifelse(association, ref_class, "NULL") |
421 | ||
422 | ! |
var_calls <- lapply(vars_names, function(var_i) { |
423 | ! |
var_class <- class(ANL[[var_i]])[1] |
424 | ! |
if (is.numeric(ANL[[var_i]]) && log_transformation) { |
425 |
# works for both integers and doubles |
|
426 | ! |
var_cl_name <- call("log", as.name(var_i)) |
427 | ! |
var_cl_lbl <- varname_w_label(var_i, ANL, prefix = "Log of ") |
428 |
} else { |
|
429 |
# silently ignore when non-numeric even if `log` is selected because some |
|
430 |
# variables may be numeric and others not |
|
431 | ! |
var_cl_name <- as.name(var_i) |
432 | ! |
var_cl_lbl <- varname_w_label(var_i, ANL) |
433 |
} |
|
434 | ||
435 | ! |
user_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
436 | ! |
user_plot = ggplot2_args[["Bivariate2"]], |
437 | ! |
user_default = ggplot2_args$default |
438 |
) |
|
439 | ||
440 | ! |
bivariate_plot_call( |
441 | ! |
data_name = "ANL", |
442 | ! |
x = ref_cl_name, |
443 | ! |
y = var_cl_name, |
444 | ! |
x_class = ref_class_cov, |
445 | ! |
y_class = var_class, |
446 | ! |
x_label = ref_cl_lbl, |
447 | ! |
y_label = var_cl_lbl, |
448 | ! |
theme = association_theme, |
449 | ! |
freq = !show_dist, |
450 | ! |
rotate_xaxis_labels = rotate_xaxis_labels, |
451 | ! |
swap_axes = swap_axes, |
452 | ! |
alpha = alpha, |
453 | ! |
size = size, |
454 | ! |
ggplot2_args = user_ggplot2_args |
455 |
) |
|
456 |
}) |
|
457 | ||
458 |
# helper function to format variable name |
|
459 | ! |
format_varnames <- function(x) { |
460 | ! |
if (is.numeric(ANL[[x]]) && log_transformation) { |
461 | ! |
varname_w_label(x, ANL, prefix = "Log of ") |
462 |
} else { |
|
463 | ! |
varname_w_label(x, ANL) |
464 |
} |
|
465 |
} |
|
466 | ! |
new_title <- |
467 | ! |
if (association) { |
468 | ! |
switch(as.character(length(vars_names)), |
469 | ! |
"0" = sprintf("Value distribution for %s", ref_cl_lbl), |
470 | ! |
"1" = sprintf( |
471 | ! |
"Association between %s and %s", |
472 | ! |
ref_cl_lbl, |
473 | ! |
format_varnames(vars_names) |
474 |
), |
|
475 | ! |
sprintf( |
476 | ! |
"Associations between %s and: %s", |
477 | ! |
ref_cl_lbl, |
478 | ! |
paste(lapply(vars_names, format_varnames), collapse = ", ") |
479 |
) |
|
480 |
) |
|
481 |
} else { |
|
482 | ! |
switch(as.character(length(vars_names)), |
483 | ! |
"0" = sprintf("Value distribution for %s", ref_cl_lbl), |
484 | ! |
sprintf( |
485 | ! |
"Value distributions for %s and %s", |
486 | ! |
ref_cl_lbl, |
487 | ! |
paste(lapply(vars_names, format_varnames), collapse = ", ") |
488 |
) |
|
489 |
) |
|
490 |
} |
|
491 | ! |
teal.code::eval_code( |
492 | ! |
merged$anl_q_r(), |
493 | ! |
substitute( |
494 | ! |
expr = title <- new_title, |
495 | ! |
env = list(new_title = new_title) |
496 |
) |
|
497 |
) %>% |
|
498 | ! |
teal.code::eval_code( |
499 | ! |
substitute( |
500 | ! |
expr = { |
501 | ! |
plot_top <- plot_calls[[1]] |
502 | ! |
plot_bottom <- plot_calls[[1]] |
503 | ! |
plot <- tern::stack_grobs(grobs = lapply(list(plot_top, plot_bottom), ggplotGrob)) |
504 |
}, |
|
505 | ! |
env = list( |
506 | ! |
plot_calls = do.call( |
507 | ! |
"call", |
508 | ! |
c(list("list", ref_call), var_calls), |
509 | ! |
quote = TRUE |
510 |
) |
|
511 |
) |
|
512 |
) |
|
513 |
) |
|
514 |
}) |
|
515 | ||
516 | ! |
decorated_output_grob_q <- srv_decorate_teal_data( |
517 | ! |
id = "decorator", |
518 | ! |
data = output_q, |
519 | ! |
decorators = select_decorators(decorators, "plot"), |
520 | ! |
expr = { |
521 | ! |
grid::grid.newpage() |
522 | ! |
grid::grid.draw(plot) |
523 |
} |
|
524 |
) |
|
525 | ||
526 | ! |
plot_r <- reactive({ |
527 | ! |
req(iv_r()$is_valid()) |
528 | ! |
req(decorated_output_grob_q())[["plot"]] |
529 |
}) |
|
530 | ||
531 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
532 | ! |
id = "myplot", |
533 | ! |
plot_r = plot_r, |
534 | ! |
height = plot_height, |
535 | ! |
width = plot_width |
536 |
) |
|
537 | ||
538 | ! |
output$title <- renderText({ |
539 | ! |
teal.code::dev_suppress(output_q()[["title"]]) |
540 |
}) |
|
541 | ||
542 |
# Render R code. |
|
543 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_output_grob_q()))) |
544 | ||
545 | ! |
teal.widgets::verbatim_popup_srv( |
546 | ! |
id = "rcode", |
547 | ! |
verbatim_content = source_code_r, |
548 | ! |
title = "Association Plot" |
549 |
) |
|
550 | ||
551 |
### REPORTER |
|
552 | ! |
if (with_reporter) { |
553 | ! |
card_fun <- function(comment, label) { |
554 | ! |
card <- teal::report_card_template( |
555 | ! |
title = "Association Plot", |
556 | ! |
label = label, |
557 | ! |
with_filter = with_filter, |
558 | ! |
filter_panel_api = filter_panel_api |
559 |
) |
|
560 | ! |
card$append_text("Plot", "header3") |
561 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
562 | ! |
if (!comment == "") { |
563 | ! |
card$append_text("Comment", "header3") |
564 | ! |
card$append_text(comment) |
565 |
} |
|
566 | ! |
card$append_src(source_code_r()) |
567 | ! |
card |
568 |
} |
|
569 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
570 |
} |
|
571 |
### |
|
572 |
}) |
|
573 |
} |
1 |
#' `teal` module: Response plot |
|
2 |
#' |
|
3 |
#' Generates a response plot for a given `response` and `x` variables. |
|
4 |
#' This module allows users customize and add annotations to the plot depending |
|
5 |
#' on the module's arguments. |
|
6 |
#' It supports showing the counts grouped by other variable facets (by row / column), |
|
7 |
#' swapping the coordinates, show count annotations and displaying the response plot |
|
8 |
#' as frequency or density. |
|
9 |
#' |
|
10 |
#' @inheritParams teal::module |
|
11 |
#' @inheritParams shared_params |
|
12 |
#' @param response (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
13 |
#' Which variable to use as the response. |
|
14 |
#' You can define one fixed column by setting `fixed = TRUE` inside the `select_spec`. |
|
15 |
#' |
|
16 |
#' The `data_extract_spec` must not allow multiple selection in this case. |
|
17 |
#' @param x (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
18 |
#' Specifies which variable to use on the X-axis of the response plot. |
|
19 |
#' Allow the user to select multiple columns from the `data` allowed in teal. |
|
20 |
#' |
|
21 |
#' The `data_extract_spec` must not allow multiple selection in this case. |
|
22 |
#' @param row_facet (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
23 |
#' optional specification of the data variable(s) to use for faceting rows. |
|
24 |
#' @param col_facet (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
25 |
#' optional specification of the data variable(s) to use for faceting columns. |
|
26 |
#' @param coord_flip (`logical(1)`) |
|
27 |
#' Indicates whether to flip coordinates between `x` and `response`. |
|
28 |
#' The default value is `FALSE` and it will show the `x` variable on the x-axis |
|
29 |
#' and the `response` variable on the y-axis. |
|
30 |
#' @param count_labels (`logical(1)`) |
|
31 |
#' Indicates whether to show count labels. |
|
32 |
#' Defaults to `TRUE`. |
|
33 |
#' @param freq (`logical(1)`) |
|
34 |
#' Indicates whether to display frequency (`TRUE`) or density (`FALSE`). |
|
35 |
#' Defaults to density (`FALSE`). |
|
36 |
#' |
|
37 |
#' @inherit shared_params return |
|
38 |
#' |
|
39 |
#' @note For more examples, please see the vignette "Using response plot" via |
|
40 |
#' `vignette("using-response-plot", package = "teal.modules.general")`. |
|
41 |
#' |
|
42 |
#' @section Decorating Module: |
|
43 |
#' |
|
44 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
45 |
#' - `plot` (`ggplot2`) |
|
46 |
#' |
|
47 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
48 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
49 |
#' See code snippet below: |
|
50 |
#' |
|
51 |
#' ``` |
|
52 |
#' tm_g_response( |
|
53 |
#' ..., # arguments for module |
|
54 |
#' decorators = list( |
|
55 |
#' plot = teal_transform_module(...) # applied to the `plot` output |
|
56 |
#' ) |
|
57 |
#' ) |
|
58 |
#' ``` |
|
59 |
#' |
|
60 |
#' For additional details and examples of decorators, refer to the vignette |
|
61 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
62 |
#' |
|
63 |
#' @examplesShinylive |
|
64 |
#' library(teal.modules.general) |
|
65 |
#' interactive <- function() TRUE |
|
66 |
#' {{ next_example }} |
|
67 |
#' @examples |
|
68 |
#' # general data example |
|
69 |
#' data <- teal_data() |
|
70 |
#' data <- within(data, { |
|
71 |
#' require(nestcolor) |
|
72 |
#' mtcars <- mtcars |
|
73 |
#' for (v in c("cyl", "vs", "am", "gear")) { |
|
74 |
#' mtcars[[v]] <- as.factor(mtcars[[v]]) |
|
75 |
#' } |
|
76 |
#' }) |
|
77 |
#' |
|
78 |
#' app <- init( |
|
79 |
#' data = data, |
|
80 |
#' modules = modules( |
|
81 |
#' tm_g_response( |
|
82 |
#' label = "Response Plots", |
|
83 |
#' response = data_extract_spec( |
|
84 |
#' dataname = "mtcars", |
|
85 |
#' select = select_spec( |
|
86 |
#' label = "Select variable:", |
|
87 |
#' choices = variable_choices(data[["mtcars"]], c("cyl", "gear")), |
|
88 |
#' selected = "cyl", |
|
89 |
#' multiple = FALSE, |
|
90 |
#' fixed = FALSE |
|
91 |
#' ) |
|
92 |
#' ), |
|
93 |
#' x = data_extract_spec( |
|
94 |
#' dataname = "mtcars", |
|
95 |
#' select = select_spec( |
|
96 |
#' label = "Select variable:", |
|
97 |
#' choices = variable_choices(data[["mtcars"]], c("vs", "am")), |
|
98 |
#' selected = "vs", |
|
99 |
#' multiple = FALSE, |
|
100 |
#' fixed = FALSE |
|
101 |
#' ) |
|
102 |
#' ) |
|
103 |
#' ) |
|
104 |
#' ) |
|
105 |
#' ) |
|
106 |
#' if (interactive()) { |
|
107 |
#' shinyApp(app$ui, app$server) |
|
108 |
#' } |
|
109 |
#' |
|
110 |
#' @examplesShinylive |
|
111 |
#' library(teal.modules.general) |
|
112 |
#' interactive <- function() TRUE |
|
113 |
#' {{ next_example }} |
|
114 |
#' @examples |
|
115 |
#' # CDISC data example |
|
116 |
#' data <- teal_data() |
|
117 |
#' data <- within(data, { |
|
118 |
#' require(nestcolor) |
|
119 |
#' ADSL <- teal.data::rADSL |
|
120 |
#' }) |
|
121 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
122 |
#' |
|
123 |
#' app <- init( |
|
124 |
#' data = data, |
|
125 |
#' modules = modules( |
|
126 |
#' tm_g_response( |
|
127 |
#' label = "Response Plots", |
|
128 |
#' response = data_extract_spec( |
|
129 |
#' dataname = "ADSL", |
|
130 |
#' select = select_spec( |
|
131 |
#' label = "Select variable:", |
|
132 |
#' choices = variable_choices(data[["ADSL"]], c("BMRKR2", "COUNTRY")), |
|
133 |
#' selected = "BMRKR2", |
|
134 |
#' multiple = FALSE, |
|
135 |
#' fixed = FALSE |
|
136 |
#' ) |
|
137 |
#' ), |
|
138 |
#' x = data_extract_spec( |
|
139 |
#' dataname = "ADSL", |
|
140 |
#' select = select_spec( |
|
141 |
#' label = "Select variable:", |
|
142 |
#' choices = variable_choices(data[["ADSL"]], c("SEX", "RACE")), |
|
143 |
#' selected = "RACE", |
|
144 |
#' multiple = FALSE, |
|
145 |
#' fixed = FALSE |
|
146 |
#' ) |
|
147 |
#' ) |
|
148 |
#' ) |
|
149 |
#' ) |
|
150 |
#' ) |
|
151 |
#' if (interactive()) { |
|
152 |
#' shinyApp(app$ui, app$server) |
|
153 |
#' } |
|
154 |
#' |
|
155 |
#' @export |
|
156 |
#' |
|
157 |
tm_g_response <- function(label = "Response Plot", |
|
158 |
response, |
|
159 |
x, |
|
160 |
row_facet = NULL, |
|
161 |
col_facet = NULL, |
|
162 |
coord_flip = FALSE, |
|
163 |
count_labels = TRUE, |
|
164 |
rotate_xaxis_labels = FALSE, |
|
165 |
freq = FALSE, |
|
166 |
plot_height = c(600, 400, 5000), |
|
167 |
plot_width = NULL, |
|
168 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
169 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
170 |
pre_output = NULL, |
|
171 |
post_output = NULL, |
|
172 |
transformators = list(), |
|
173 |
decorators = list()) { |
|
174 | ! |
message("Initializing tm_g_response") |
175 | ||
176 |
# Normalize the parameters |
|
177 | ! |
if (inherits(response, "data_extract_spec")) response <- list(response) |
178 | ! |
if (inherits(x, "data_extract_spec")) x <- list(x) |
179 | ! |
if (inherits(row_facet, "data_extract_spec")) row_facet <- list(row_facet) |
180 | ! |
if (inherits(col_facet, "data_extract_spec")) col_facet <- list(col_facet) |
181 | ||
182 |
# Start of assertions |
|
183 | ! |
checkmate::assert_string(label) |
184 | ||
185 | ! |
checkmate::assert_list(response, types = "data_extract_spec") |
186 | ! |
if (!all(vapply(response, function(x) !("" %in% x$select$choices), logical(1)))) { |
187 | ! |
stop("'response' should not allow empty values") |
188 |
} |
|
189 | ! |
assert_single_selection(response) |
190 | ||
191 | ! |
checkmate::assert_list(x, types = "data_extract_spec") |
192 | ! |
if (!all(vapply(x, function(x) !("" %in% x$select$choices), logical(1)))) { |
193 | ! |
stop("'x' should not allow empty values") |
194 |
} |
|
195 | ! |
assert_single_selection(x) |
196 | ||
197 | ! |
checkmate::assert_list(row_facet, types = "data_extract_spec", null.ok = TRUE) |
198 | ! |
checkmate::assert_list(col_facet, types = "data_extract_spec", null.ok = TRUE) |
199 | ! |
checkmate::assert_flag(coord_flip) |
200 | ! |
checkmate::assert_flag(count_labels) |
201 | ! |
checkmate::assert_flag(rotate_xaxis_labels) |
202 | ! |
checkmate::assert_flag(freq) |
203 | ||
204 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
205 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
206 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
207 | ! |
checkmate::assert_numeric( |
208 | ! |
plot_width[1], |
209 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
210 |
) |
|
211 | ||
212 | ! |
ggtheme <- match.arg(ggtheme) |
213 | ! |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
214 | ||
215 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
216 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
217 | ||
218 | ! |
assert_decorators(decorators, "plot") |
219 |
# End of assertions |
|
220 | ||
221 |
# Make UI args |
|
222 | ! |
args <- as.list(environment()) |
223 | ||
224 | ! |
data_extract_list <- list( |
225 | ! |
response = response, |
226 | ! |
x = x, |
227 | ! |
row_facet = row_facet, |
228 | ! |
col_facet = col_facet |
229 |
) |
|
230 | ||
231 | ! |
ans <- module( |
232 | ! |
label = label, |
233 | ! |
server = srv_g_response, |
234 | ! |
ui = ui_g_response, |
235 | ! |
ui_args = args, |
236 | ! |
server_args = c( |
237 | ! |
data_extract_list, |
238 | ! |
list( |
239 | ! |
plot_height = plot_height, |
240 | ! |
plot_width = plot_width, |
241 | ! |
ggplot2_args = ggplot2_args, |
242 | ! |
decorators = decorators |
243 |
) |
|
244 |
), |
|
245 | ! |
transformators = transformators, |
246 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
247 |
) |
|
248 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
249 | ! |
ans |
250 |
} |
|
251 | ||
252 |
# UI function for the response module |
|
253 |
ui_g_response <- function(id, ...) { |
|
254 | ! |
ns <- NS(id) |
255 | ! |
args <- list(...) |
256 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$response, args$x, args$row_facet, args$col_facet) |
257 | ||
258 | ! |
teal.widgets::standard_layout( |
259 | ! |
output = teal.widgets::white_small_well( |
260 | ! |
teal.widgets::plot_with_settings_ui(id = ns("myplot")) |
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("response", "x", "row_facet", "col_facet")]), |
268 | ! |
teal.transform::data_extract_ui( |
269 | ! |
id = ns("response"), |
270 | ! |
label = "Response variable", |
271 | ! |
data_extract_spec = args$response, |
272 | ! |
is_single_dataset = is_single_dataset_value |
273 |
), |
|
274 | ! |
teal.transform::data_extract_ui( |
275 | ! |
id = ns("x"), |
276 | ! |
label = "X variable", |
277 | ! |
data_extract_spec = args$x, |
278 | ! |
is_single_dataset = is_single_dataset_value |
279 |
), |
|
280 | ! |
if (!is.null(args$row_facet)) { |
281 | ! |
teal.transform::data_extract_ui( |
282 | ! |
id = ns("row_facet"), |
283 | ! |
label = "Row facetting", |
284 | ! |
data_extract_spec = args$row_facet, |
285 | ! |
is_single_dataset = is_single_dataset_value |
286 |
) |
|
287 |
}, |
|
288 | ! |
if (!is.null(args$col_facet)) { |
289 | ! |
teal.transform::data_extract_ui( |
290 | ! |
id = ns("col_facet"), |
291 | ! |
label = "Column facetting", |
292 | ! |
data_extract_spec = args$col_facet, |
293 | ! |
is_single_dataset = is_single_dataset_value |
294 |
) |
|
295 |
}, |
|
296 | ! |
shinyWidgets::radioGroupButtons( |
297 | ! |
inputId = ns("freq"), |
298 | ! |
label = NULL, |
299 | ! |
choices = c("frequency", "density"), |
300 | ! |
selected = ifelse(args$freq, "frequency", "density"), |
301 | ! |
justified = TRUE |
302 |
), |
|
303 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")), |
304 | ! |
teal.widgets::panel_group( |
305 | ! |
teal.widgets::panel_item( |
306 | ! |
title = "Plot settings", |
307 | ! |
checkboxInput(ns("count_labels"), "Add count labels", value = args$count_labels), |
308 | ! |
checkboxInput(ns("coord_flip"), "Swap axes", value = args$coord_flip), |
309 | ! |
checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = args$rotate_xaxis_labels), |
310 | ! |
selectInput( |
311 | ! |
inputId = ns("ggtheme"), |
312 | ! |
label = "Theme (by ggplot):", |
313 | ! |
choices = ggplot_themes, |
314 | ! |
selected = args$ggtheme, |
315 | ! |
multiple = FALSE |
316 |
) |
|
317 |
) |
|
318 |
) |
|
319 |
), |
|
320 | ! |
forms = tagList( |
321 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
322 |
), |
|
323 | ! |
pre_output = args$pre_output, |
324 | ! |
post_output = args$post_output |
325 |
) |
|
326 |
} |
|
327 | ||
328 |
# Server function for the response module |
|
329 |
srv_g_response <- function(id, |
|
330 |
data, |
|
331 |
reporter, |
|
332 |
filter_panel_api, |
|
333 |
response, |
|
334 |
x, |
|
335 |
row_facet, |
|
336 |
col_facet, |
|
337 |
plot_height, |
|
338 |
plot_width, |
|
339 |
ggplot2_args, |
|
340 |
decorators) { |
|
341 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
342 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
343 | ! |
checkmate::assert_class(data, "reactive") |
344 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
345 | ! |
moduleServer(id, function(input, output, session) { |
346 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
347 | ||
348 | ! |
data_extract <- list(response = response, x = x, row_facet = row_facet, col_facet = col_facet) |
349 | ||
350 | ! |
rule_diff <- function(other) { |
351 | ! |
function(value) { |
352 | ! |
if (other %in% names(selector_list())) { |
353 | ! |
othervalue <- selector_list()[[other]]()[["select"]] |
354 | ! |
if (!is.null(othervalue)) { |
355 | ! |
if (identical(value, othervalue)) { |
356 | ! |
"Row and column facetting variables must be different." |
357 |
} |
|
358 |
} |
|
359 |
} |
|
360 |
} |
|
361 |
} |
|
362 | ||
363 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
364 | ! |
data_extract = data_extract, |
365 | ! |
datasets = data, |
366 | ! |
select_validation_rule = list( |
367 | ! |
response = shinyvalidate::sv_required("Please define a column for the response variable"), |
368 | ! |
x = shinyvalidate::sv_required("Please define a column for X variable"), |
369 | ! |
row_facet = shinyvalidate::compose_rules( |
370 | ! |
shinyvalidate::sv_optional(), |
371 | ! |
~ if (length(.) > 1) "There must be 1 or no row facetting variable.", |
372 | ! |
rule_diff("col_facet") |
373 |
), |
|
374 | ! |
col_facet = shinyvalidate::compose_rules( |
375 | ! |
shinyvalidate::sv_optional(), |
376 | ! |
~ if (length(.) > 1) "There must be 1 or no column facetting variable.", |
377 | ! |
rule_diff("row_facet") |
378 |
) |
|
379 |
) |
|
380 |
) |
|
381 | ||
382 | ! |
iv_r <- reactive({ |
383 | ! |
iv <- shinyvalidate::InputValidator$new() |
384 | ! |
iv$add_rule("ggtheme", shinyvalidate::sv_required("Please select a theme")) |
385 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
386 |
}) |
|
387 | ||
388 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
389 | ! |
selector_list = selector_list, |
390 | ! |
datasets = data |
391 |
) |
|
392 | ||
393 | ! |
anl_merged_q <- reactive({ |
394 | ! |
req(anl_merged_input()) |
395 | ! |
data() %>% |
396 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
397 |
}) |
|
398 | ||
399 | ! |
merged <- list( |
400 | ! |
anl_input_r = anl_merged_input, |
401 | ! |
anl_q_r = anl_merged_q |
402 |
) |
|
403 | ||
404 | ! |
output_q <- reactive({ |
405 | ! |
teal::validate_inputs(iv_r()) |
406 | ||
407 | ! |
qenv <- merged$anl_q_r() |
408 | ! |
ANL <- qenv[["ANL"]] |
409 | ! |
resp_var <- as.vector(merged$anl_input_r()$columns_source$response) |
410 | ! |
x <- as.vector(merged$anl_input_r()$columns_source$x) |
411 | ||
412 | ! |
validate(need(is.factor(ANL[[resp_var]]), "Please select a factor variable as the response.")) |
413 | ! |
validate(need(is.factor(ANL[[x]]), "Please select a factor variable as the X-Variable.")) |
414 | ! |
teal::validate_has_data(ANL, 10) |
415 | ! |
teal::validate_has_data(ANL[, c(resp_var, x)], 10, complete = TRUE, allow_inf = FALSE) |
416 | ||
417 | ! |
row_facet_name <- if (length(merged$anl_input_r()$columns_source$row_facet) == 0) { |
418 | ! |
character(0) |
419 |
} else { |
|
420 | ! |
as.vector(merged$anl_input_r()$columns_source$row_facet) |
421 |
} |
|
422 | ! |
col_facet_name <- if (length(merged$anl_input_r()$columns_source$col_facet) == 0) { |
423 | ! |
character(0) |
424 |
} else { |
|
425 | ! |
as.vector(merged$anl_input_r()$columns_source$col_facet) |
426 |
} |
|
427 | ||
428 | ! |
freq <- input$freq == "frequency" |
429 | ! |
swap_axes <- input$coord_flip |
430 | ! |
counts <- input$count_labels |
431 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
432 | ! |
ggtheme <- input$ggtheme |
433 | ||
434 | ! |
arg_position <- if (freq) "stack" else "fill" |
435 | ||
436 | ! |
rowf <- if (length(row_facet_name) != 0) as.name(row_facet_name) |
437 | ! |
colf <- if (length(col_facet_name) != 0) as.name(col_facet_name) |
438 | ! |
resp_cl <- as.name(resp_var) |
439 | ! |
x_cl <- as.name(x) |
440 | ||
441 | ! |
if (swap_axes) { |
442 | ! |
qenv <- teal.code::eval_code( |
443 | ! |
qenv, |
444 | ! |
substitute( |
445 | ! |
expr = ANL[[x]] <- with(ANL, forcats::fct_rev(x_cl)), |
446 | ! |
env = list(x = x, x_cl = x_cl) |
447 |
) |
|
448 |
) |
|
449 |
} |
|
450 | ||
451 | ! |
qenv <- teal.code::eval_code( |
452 | ! |
qenv, |
453 | ! |
substitute( |
454 | ! |
expr = ANL[[resp_var]] <- factor(ANL[[resp_var]]), |
455 | ! |
env = list(resp_var = resp_var) |
456 |
) |
|
457 |
) %>% |
|
458 |
# rowf and colf will be a NULL if not set by a user |
|
459 | ! |
teal.code::eval_code( |
460 | ! |
substitute( |
461 | ! |
expr = ANL2 <- ANL %>% |
462 | ! |
dplyr::group_by_at(dplyr::vars(x_cl, resp_cl, rowf, colf)) %>% |
463 | ! |
dplyr::summarise(ns = dplyr::n()) %>% |
464 | ! |
dplyr::group_by_at(dplyr::vars(x_cl, rowf, colf)) %>% |
465 | ! |
dplyr::mutate(sums = sum(ns), percent = round(ns / sums * 100, 1)), |
466 | ! |
env = list(x_cl = x_cl, resp_cl = resp_cl, rowf = rowf, colf = colf) |
467 |
) |
|
468 |
) %>% |
|
469 | ! |
teal.code::eval_code( |
470 | ! |
substitute( |
471 | ! |
expr = ANL3 <- ANL %>% |
472 | ! |
dplyr::group_by_at(dplyr::vars(x_cl, rowf, colf)) %>% |
473 | ! |
dplyr::summarise(ns = dplyr::n()), |
474 | ! |
env = list(x_cl = x_cl, rowf = rowf, colf = colf) |
475 |
) |
|
476 |
) |
|
477 | ||
478 | ! |
plot_call <- substitute( |
479 | ! |
expr = ggplot(ANL2, aes(x = x_cl, y = ns)) + |
480 | ! |
geom_bar(aes(fill = resp_cl), stat = "identity", position = arg_position), |
481 | ! |
env = list( |
482 | ! |
x_cl = x_cl, |
483 | ! |
resp_cl = resp_cl, |
484 | ! |
arg_position = arg_position |
485 |
) |
|
486 |
) |
|
487 | ||
488 | ! |
if (!freq) { |
489 | ! |
plot_call <- substitute( |
490 | ! |
plot_call + expand_limits(y = c(0, 1.1)), |
491 | ! |
env = list(plot_call = plot_call) |
492 |
) |
|
493 |
} |
|
494 | ||
495 | ! |
if (counts) { |
496 | ! |
plot_call <- substitute( |
497 | ! |
expr = plot_call + |
498 | ! |
geom_text( |
499 | ! |
data = ANL2, |
500 | ! |
aes(label = ns, x = x_cl, y = ns, group = resp_cl), |
501 | ! |
col = "white", |
502 | ! |
vjust = "middle", |
503 | ! |
hjust = "middle", |
504 | ! |
position = position_anl2_value |
505 |
) + |
|
506 | ! |
geom_text( |
507 | ! |
data = ANL3, aes(label = ns, x = x_cl, y = anl3_y), |
508 | ! |
hjust = hjust_value, |
509 | ! |
vjust = vjust_value, |
510 | ! |
position = position_anl3_value |
511 |
), |
|
512 | ! |
env = list( |
513 | ! |
plot_call = plot_call, |
514 | ! |
x_cl = x_cl, |
515 | ! |
resp_cl = resp_cl, |
516 | ! |
hjust_value = if (swap_axes) "left" else "middle", |
517 | ! |
vjust_value = if (swap_axes) "middle" else -1, |
518 | ! |
position_anl2_value = if (!freq) quote(position_fill(0.5)) else quote(position_stack(0.5)), # nolint: line_length. |
519 | ! |
anl3_y = if (!freq) 1.1 else as.name("ns"), |
520 | ! |
position_anl3_value = if (!freq) "fill" else "stack" |
521 |
) |
|
522 |
) |
|
523 |
} |
|
524 | ||
525 | ! |
if (swap_axes) { |
526 | ! |
plot_call <- substitute(plot_call + coord_flip(), env = list(plot_call = plot_call)) |
527 |
} |
|
528 | ||
529 | ! |
facet_cl <- facet_ggplot_call(row_facet_name, col_facet_name) |
530 | ||
531 | ! |
if (!is.null(facet_cl)) { |
532 | ! |
plot_call <- substitute(expr = plot_call + facet_cl, env = list(plot_call = plot_call, facet_cl = facet_cl)) |
533 |
} |
|
534 | ||
535 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
536 | ! |
labs = list( |
537 | ! |
x = varname_w_label(x, ANL), |
538 | ! |
y = varname_w_label(resp_var, ANL, prefix = "Proportion of "), |
539 | ! |
fill = varname_w_label(resp_var, ANL) |
540 |
), |
|
541 | ! |
theme = list(legend.position = "bottom") |
542 |
) |
|
543 | ||
544 | ! |
if (rotate_xaxis_labels) { |
545 | ! |
dev_ggplot2_args$theme[["axis.text.x"]] <- quote(element_text(angle = 45, hjust = 1)) |
546 |
} |
|
547 | ||
548 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
549 | ! |
user_plot = ggplot2_args, |
550 | ! |
module_plot = dev_ggplot2_args |
551 |
) |
|
552 | ||
553 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
554 | ! |
all_ggplot2_args, |
555 | ! |
ggtheme = ggtheme |
556 |
) |
|
557 | ||
558 | ! |
plot_call <- substitute(expr = { |
559 | ! |
plot <- plot_call + labs + ggthemes + themes |
560 | ! |
}, env = list( |
561 | ! |
plot_call = plot_call, |
562 | ! |
labs = parsed_ggplot2_args$labs, |
563 | ! |
themes = parsed_ggplot2_args$theme, |
564 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
565 |
)) |
|
566 | ||
567 | ! |
teal.code::eval_code(qenv, plot_call) |
568 |
}) |
|
569 | ||
570 | ! |
decorated_output_plot_q <- srv_decorate_teal_data( |
571 | ! |
id = "decorator", |
572 | ! |
data = output_q, |
573 | ! |
decorators = select_decorators(decorators, "plot"), |
574 | ! |
expr = print(plot) |
575 |
) |
|
576 | ||
577 | ! |
plot_r <- reactive(req(decorated_output_plot_q())[["plot"]]) |
578 | ||
579 |
# Insert the plot into a plot_with_settings module from teal.widgets |
|
580 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
581 | ! |
id = "myplot", |
582 | ! |
plot_r = plot_r, |
583 | ! |
height = plot_height, |
584 | ! |
width = plot_width |
585 |
) |
|
586 | ||
587 |
# Render R code. |
|
588 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_output_plot_q()))) |
589 | ||
590 | ! |
teal.widgets::verbatim_popup_srv( |
591 | ! |
id = "rcode", |
592 | ! |
verbatim_content = source_code_r, |
593 | ! |
title = "Show R Code for Response" |
594 |
) |
|
595 | ||
596 |
### REPORTER |
|
597 | ! |
if (with_reporter) { |
598 | ! |
card_fun <- function(comment, label) { |
599 | ! |
card <- teal::report_card_template( |
600 | ! |
title = "Response Plot", |
601 | ! |
label = label, |
602 | ! |
with_filter = with_filter, |
603 | ! |
filter_panel_api = filter_panel_api |
604 |
) |
|
605 | ! |
card$append_text("Plot", "header3") |
606 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
607 | ! |
if (!comment == "") { |
608 | ! |
card$append_text("Comment", "header3") |
609 | ! |
card$append_text(comment) |
610 |
} |
|
611 | ! |
card$append_src(source_code_r()) |
612 | ! |
card |
613 |
} |
|
614 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
615 |
} |
|
616 |
### |
|
617 |
}) |
|
618 |
} |
1 |
#' `teal` module: Univariate and bivariate visualizations |
|
2 |
#' |
|
3 |
#' Module enables the creation of univariate and bivariate plots, |
|
4 |
#' facilitating the exploration of data distributions and relationships between two variables. |
|
5 |
#' |
|
6 |
#' This is a general module to visualize 1 & 2 dimensional data. |
|
7 |
#' |
|
8 |
#' @note |
|
9 |
#' For more examples, please see the vignette "Using bivariate plot" via |
|
10 |
#' `vignette("using-bivariate-plot", package = "teal.modules.general")`. |
|
11 |
#' |
|
12 |
#' @inheritParams teal::module |
|
13 |
#' @inheritParams shared_params |
|
14 |
#' @param x (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
15 |
#' Variable names selected to plot along the x-axis by default. |
|
16 |
#' Can be numeric, factor or character. |
|
17 |
#' No empty selections are allowed. |
|
18 |
#' @param y (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
19 |
#' Variable names selected to plot along the y-axis by default. |
|
20 |
#' Can be numeric, factor or character. |
|
21 |
#' @param use_density (`logical`) optional, indicates whether to plot density (`TRUE`) or frequency (`FALSE`). |
|
22 |
#' Defaults to frequency (`FALSE`). |
|
23 |
#' @param row_facet (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
24 |
#' specification of the data variable(s) to use for faceting rows. |
|
25 |
#' @param col_facet (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
26 |
#' specification of the data variable(s) to use for faceting columns. |
|
27 |
#' @param facet (`logical`) optional, specifies whether the facet encodings `ui` elements are toggled |
|
28 |
#' on and shown to the user by default. Defaults to `TRUE` if either `row_facet` or `column_facet` |
|
29 |
#' are supplied. |
|
30 |
#' @param color_settings (`logical`) Whether coloring, filling and size should be applied |
|
31 |
#' and `UI` tool offered to the user. |
|
32 |
#' @param color (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
33 |
#' specification of the data variable(s) selected for the outline color inside the coloring settings. |
|
34 |
#' It will be applied when `color_settings` is set to `TRUE`. |
|
35 |
#' @param fill (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
36 |
#' specification of the data variable(s) selected for the fill color inside the coloring settings. |
|
37 |
#' It will be applied when `color_settings` is set to `TRUE`. |
|
38 |
#' @param size (`data_extract_spec` or `list` of multiple `data_extract_spec`) optional, |
|
39 |
#' specification of the data variable(s) selected for the size of `geom_point` plots inside the coloring settings. |
|
40 |
#' It will be applied when `color_settings` is set to `TRUE`. |
|
41 |
#' @param free_x_scales (`logical`) optional, whether X scaling shall be changeable. |
|
42 |
#' Does not allow scaling to be changed by default (`FALSE`). |
|
43 |
#' @param free_y_scales (`logical`) optional, whether Y scaling shall be changeable. |
|
44 |
#' Does not allow scaling to be changed by default (`FALSE`). |
|
45 |
#' @param swap_axes (`logical`) optional, whether to swap X and Y axes. Defaults to `FALSE`. |
|
46 |
#' |
|
47 |
#' @inherit shared_params return |
|
48 |
#' |
|
49 |
#' @section Decorating Module: |
|
50 |
#' |
|
51 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
52 |
#' - `plot` (`ggplot2`) |
|
53 |
#' |
|
54 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
55 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
56 |
#' See code snippet below: |
|
57 |
#' |
|
58 |
#' ``` |
|
59 |
#' tm_g_bivariate( |
|
60 |
#' ..., # arguments for module |
|
61 |
#' decorators = list( |
|
62 |
#' plot = teal_transform_module(...) # applied to the `plot` output |
|
63 |
#' ) |
|
64 |
#' ) |
|
65 |
#' ``` |
|
66 |
#' |
|
67 |
#' For additional details and examples of decorators, refer to the vignette |
|
68 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
69 |
#' |
|
70 |
#' |
|
71 |
#' @examplesShinylive |
|
72 |
#' library(teal.modules.general) |
|
73 |
#' interactive <- function() TRUE |
|
74 |
#' {{ next_example }} |
|
75 |
#' @examples |
|
76 |
#' # general data example |
|
77 |
#' data <- teal_data() |
|
78 |
#' data <- within(data, { |
|
79 |
#' require(nestcolor) |
|
80 |
#' CO2 <- data.frame(CO2) |
|
81 |
#' }) |
|
82 |
#' |
|
83 |
#' app <- init( |
|
84 |
#' data = data, |
|
85 |
#' modules = tm_g_bivariate( |
|
86 |
#' x = data_extract_spec( |
|
87 |
#' dataname = "CO2", |
|
88 |
#' select = select_spec( |
|
89 |
#' label = "Select variable:", |
|
90 |
#' choices = variable_choices(data[["CO2"]]), |
|
91 |
#' selected = "conc", |
|
92 |
#' fixed = FALSE |
|
93 |
#' ) |
|
94 |
#' ), |
|
95 |
#' y = data_extract_spec( |
|
96 |
#' dataname = "CO2", |
|
97 |
#' select = select_spec( |
|
98 |
#' label = "Select variable:", |
|
99 |
#' choices = variable_choices(data[["CO2"]]), |
|
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"]]), |
|
110 |
#' selected = "Type", |
|
111 |
#' fixed = FALSE |
|
112 |
#' ) |
|
113 |
#' ), |
|
114 |
#' col_facet = data_extract_spec( |
|
115 |
#' dataname = "CO2", |
|
116 |
#' select = select_spec( |
|
117 |
#' label = "Select variable:", |
|
118 |
#' choices = variable_choices(data[["CO2"]]), |
|
119 |
#' selected = "Treatment", |
|
120 |
#' fixed = FALSE |
|
121 |
#' ) |
|
122 |
#' ) |
|
123 |
#' ) |
|
124 |
#' ) |
|
125 |
#' if (interactive()) { |
|
126 |
#' shinyApp(app$ui, app$server) |
|
127 |
#' } |
|
128 |
#' |
|
129 |
#' @examplesShinylive |
|
130 |
#' library(teal.modules.general) |
|
131 |
#' interactive <- function() TRUE |
|
132 |
#' {{ next_example }} |
|
133 |
#' @examples |
|
134 |
#' # CDISC data example |
|
135 |
#' data <- teal_data() |
|
136 |
#' data <- within(data, { |
|
137 |
#' require(nestcolor) |
|
138 |
#' ADSL <- teal.data::rADSL |
|
139 |
#' }) |
|
140 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
141 |
#' |
|
142 |
#' app <- init( |
|
143 |
#' data = data, |
|
144 |
#' modules = tm_g_bivariate( |
|
145 |
#' x = data_extract_spec( |
|
146 |
#' dataname = "ADSL", |
|
147 |
#' select = select_spec( |
|
148 |
#' label = "Select variable:", |
|
149 |
#' choices = variable_choices(data[["ADSL"]]), |
|
150 |
#' selected = "AGE", |
|
151 |
#' fixed = FALSE |
|
152 |
#' ) |
|
153 |
#' ), |
|
154 |
#' y = data_extract_spec( |
|
155 |
#' dataname = "ADSL", |
|
156 |
#' select = select_spec( |
|
157 |
#' label = "Select variable:", |
|
158 |
#' choices = variable_choices(data[["ADSL"]]), |
|
159 |
#' selected = "SEX", |
|
160 |
#' multiple = FALSE, |
|
161 |
#' fixed = FALSE |
|
162 |
#' ) |
|
163 |
#' ), |
|
164 |
#' row_facet = data_extract_spec( |
|
165 |
#' dataname = "ADSL", |
|
166 |
#' select = select_spec( |
|
167 |
#' label = "Select variable:", |
|
168 |
#' choices = variable_choices(data[["ADSL"]]), |
|
169 |
#' selected = "ARM", |
|
170 |
#' fixed = FALSE |
|
171 |
#' ) |
|
172 |
#' ), |
|
173 |
#' col_facet = data_extract_spec( |
|
174 |
#' dataname = "ADSL", |
|
175 |
#' select = select_spec( |
|
176 |
#' label = "Select variable:", |
|
177 |
#' choices = variable_choices(data[["ADSL"]]), |
|
178 |
#' selected = "COUNTRY", |
|
179 |
#' fixed = FALSE |
|
180 |
#' ) |
|
181 |
#' ) |
|
182 |
#' ) |
|
183 |
#' ) |
|
184 |
#' if (interactive()) { |
|
185 |
#' shinyApp(app$ui, app$server) |
|
186 |
#' } |
|
187 |
#' |
|
188 |
#' @export |
|
189 |
#' |
|
190 |
tm_g_bivariate <- function(label = "Bivariate Plots", |
|
191 |
x, |
|
192 |
y, |
|
193 |
row_facet = NULL, |
|
194 |
col_facet = NULL, |
|
195 |
facet = !is.null(row_facet) || !is.null(col_facet), |
|
196 |
color = NULL, |
|
197 |
fill = NULL, |
|
198 |
size = NULL, |
|
199 |
use_density = FALSE, |
|
200 |
color_settings = FALSE, |
|
201 |
free_x_scales = FALSE, |
|
202 |
free_y_scales = FALSE, |
|
203 |
plot_height = c(600, 200, 2000), |
|
204 |
plot_width = NULL, |
|
205 |
rotate_xaxis_labels = FALSE, |
|
206 |
swap_axes = FALSE, |
|
207 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
208 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
209 |
pre_output = NULL, |
|
210 |
post_output = NULL, |
|
211 |
transformators = list(), |
|
212 |
decorators = list()) { |
|
213 | 18x |
message("Initializing tm_g_bivariate") |
214 | ||
215 |
# Normalize the parameters |
|
216 | 14x |
if (inherits(x, "data_extract_spec")) x <- list(x) |
217 | 13x |
if (inherits(y, "data_extract_spec")) y <- list(y) |
218 | 1x |
if (inherits(row_facet, "data_extract_spec")) row_facet <- list(row_facet) |
219 | 1x |
if (inherits(col_facet, "data_extract_spec")) col_facet <- list(col_facet) |
220 | 1x |
if (inherits(color, "data_extract_spec")) color <- list(color) |
221 | 1x |
if (inherits(fill, "data_extract_spec")) fill <- list(fill) |
222 | 1x |
if (inherits(size, "data_extract_spec")) size <- list(size) |
223 | ||
224 |
# Start of assertions |
|
225 | 18x |
checkmate::assert_string(label) |
226 | ||
227 | 18x |
checkmate::assert_list(x, types = "data_extract_spec") |
228 | 18x |
assert_single_selection(x) |
229 | ||
230 | 16x |
checkmate::assert_list(y, types = "data_extract_spec") |
231 | 16x |
assert_single_selection(y) |
232 | ||
233 | 14x |
checkmate::assert_list(row_facet, types = "data_extract_spec", null.ok = TRUE) |
234 | 14x |
assert_single_selection(row_facet) |
235 | ||
236 | 14x |
checkmate::assert_list(col_facet, types = "data_extract_spec", null.ok = TRUE) |
237 | 14x |
assert_single_selection(col_facet) |
238 | ||
239 | 14x |
checkmate::assert_flag(facet) |
240 | ||
241 | 14x |
checkmate::assert_list(color, types = "data_extract_spec", null.ok = TRUE) |
242 | 14x |
assert_single_selection(color) |
243 | ||
244 | 14x |
checkmate::assert_list(fill, types = "data_extract_spec", null.ok = TRUE) |
245 | 14x |
assert_single_selection(fill) |
246 | ||
247 | 14x |
checkmate::assert_list(size, types = "data_extract_spec", null.ok = TRUE) |
248 | 14x |
assert_single_selection(size) |
249 | ||
250 | 14x |
checkmate::assert_flag(use_density) |
251 | ||
252 |
# Determines color, fill & size if they are not explicitly set |
|
253 | 14x |
checkmate::assert_flag(color_settings) |
254 | 14x |
if (color_settings) { |
255 | 2x |
if (is.null(color)) { |
256 | 2x |
color <- x |
257 | 2x |
color[[1]]$select <- teal.transform::select_spec(choices = color[[1]]$select$choices, selected = NULL) |
258 |
} |
|
259 | 2x |
if (is.null(fill)) { |
260 | 2x |
fill <- x |
261 | 2x |
fill[[1]]$select <- teal.transform::select_spec(choices = fill[[1]]$select$choices, selected = NULL) |
262 |
} |
|
263 | 2x |
if (is.null(size)) { |
264 | 2x |
size <- x |
265 | 2x |
size[[1]]$select <- teal.transform::select_spec(choices = size[[1]]$select$choices, selected = NULL) |
266 |
} |
|
267 |
} else { |
|
268 | 12x |
if (!is.null(c(color, fill, size))) { |
269 | 3x |
stop("'color_settings' argument needs to be set to TRUE if 'color', 'fill', and/or 'size' is/are supplied.") |
270 |
} |
|
271 |
} |
|
272 | ||
273 | 11x |
checkmate::assert_flag(free_x_scales) |
274 | 11x |
checkmate::assert_flag(free_y_scales) |
275 | ||
276 | 11x |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
277 | 10x |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
278 | 8x |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
279 | 7x |
checkmate::assert_numeric( |
280 | 7x |
plot_width[1], |
281 | 7x |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
282 |
) |
|
283 | ||
284 | 5x |
checkmate::assert_flag(rotate_xaxis_labels) |
285 | 5x |
checkmate::assert_flag(swap_axes) |
286 | ||
287 | 5x |
ggtheme <- match.arg(ggtheme) |
288 | 5x |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
289 | ||
290 | 5x |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
291 | 5x |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
292 | ||
293 | 5x |
assert_decorators(decorators, "plot") |
294 |
# End of assertions |
|
295 | ||
296 |
# Make UI args |
|
297 | 5x |
args <- as.list(environment()) |
298 | ||
299 | 5x |
data_extract_list <- list( |
300 | 5x |
x = x, |
301 | 5x |
y = y, |
302 | 5x |
row_facet = row_facet, |
303 | 5x |
col_facet = col_facet, |
304 | 5x |
color_settings = color_settings, |
305 | 5x |
color = color, |
306 | 5x |
fill = fill, |
307 | 5x |
size = size |
308 |
) |
|
309 | ||
310 | 5x |
ans <- module( |
311 | 5x |
label = label, |
312 | 5x |
server = srv_g_bivariate, |
313 | 5x |
ui = ui_g_bivariate, |
314 | 5x |
ui_args = args, |
315 | 5x |
server_args = c( |
316 | 5x |
data_extract_list, |
317 | 5x |
list(plot_height = plot_height, plot_width = plot_width, ggplot2_args = ggplot2_args, decorators = decorators) |
318 |
), |
|
319 | 5x |
transformators = transformators, |
320 | 5x |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
321 |
) |
|
322 | 5x |
attr(ans, "teal_bookmarkable") <- TRUE |
323 | 5x |
ans |
324 |
} |
|
325 | ||
326 |
# UI function for the bivariate module |
|
327 |
ui_g_bivariate <- function(id, ...) { |
|
328 | ! |
args <- list(...) |
329 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset( |
330 | ! |
args$x, args$y, args$row_facet, args$col_facet, args$color, args$fill, args$size |
331 |
) |
|
332 | ||
333 | ! |
ns <- NS(id) |
334 | ! |
teal.widgets::standard_layout( |
335 | ! |
output = teal.widgets::white_small_well( |
336 | ! |
tags$div(teal.widgets::plot_with_settings_ui(id = ns("myplot"))) |
337 |
), |
|
338 | ! |
encoding = tags$div( |
339 |
### Reporter |
|
340 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
341 |
### |
|
342 | ! |
tags$label("Encodings", class = "text-primary"), |
343 | ! |
teal.transform::datanames_input(args[c("x", "y", "row_facet", "col_facet", "color", "fill", "size")]), |
344 | ! |
teal.transform::data_extract_ui( |
345 | ! |
id = ns("x"), |
346 | ! |
label = "X variable", |
347 | ! |
data_extract_spec = args$x, |
348 | ! |
is_single_dataset = is_single_dataset_value |
349 |
), |
|
350 | ! |
teal.transform::data_extract_ui( |
351 | ! |
id = ns("y"), |
352 | ! |
label = "Y variable", |
353 | ! |
data_extract_spec = args$y, |
354 | ! |
is_single_dataset = is_single_dataset_value |
355 |
), |
|
356 | ! |
conditionalPanel( |
357 | ! |
condition = |
358 | ! |
"$(\"button[data-id*='-x-dataset'][data-id$='-select']\").text() == '- Nothing selected - ' || |
359 | ! |
$(\"button[data-id*='-y-dataset'][data-id$='-select']\").text() == '- Nothing selected - ' ", |
360 | ! |
shinyWidgets::radioGroupButtons( |
361 | ! |
inputId = ns("use_density"), |
362 | ! |
label = NULL, |
363 | ! |
choices = c("frequency", "density"), |
364 | ! |
selected = ifelse(args$use_density, "density", "frequency"), |
365 | ! |
justified = TRUE |
366 |
) |
|
367 |
), |
|
368 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")), |
369 | ! |
if (!is.null(args$row_facet) || !is.null(args$col_facet)) { |
370 | ! |
tags$div( |
371 | ! |
class = "data-extract-box", |
372 | ! |
tags$label("Facetting"), |
373 | ! |
shinyWidgets::switchInput(inputId = ns("facetting"), value = args$facet, size = "mini"), |
374 | ! |
conditionalPanel( |
375 | ! |
condition = paste0("input['", ns("facetting"), "']"), |
376 | ! |
tags$div( |
377 | ! |
if (!is.null(args$row_facet)) { |
378 | ! |
teal.transform::data_extract_ui( |
379 | ! |
id = ns("row_facet"), |
380 | ! |
label = "Row facetting variable", |
381 | ! |
data_extract_spec = args$row_facet, |
382 | ! |
is_single_dataset = is_single_dataset_value |
383 |
) |
|
384 |
}, |
|
385 | ! |
if (!is.null(args$col_facet)) { |
386 | ! |
teal.transform::data_extract_ui( |
387 | ! |
id = ns("col_facet"), |
388 | ! |
label = "Column facetting variable", |
389 | ! |
data_extract_spec = args$col_facet, |
390 | ! |
is_single_dataset = is_single_dataset_value |
391 |
) |
|
392 |
}, |
|
393 | ! |
checkboxInput(ns("free_x_scales"), "free x scales", value = args$free_x_scales), |
394 | ! |
checkboxInput(ns("free_y_scales"), "free y scales", value = args$free_y_scales) |
395 |
) |
|
396 |
) |
|
397 |
) |
|
398 |
}, |
|
399 | ! |
if (args$color_settings) { |
400 |
# Put a grey border around the coloring settings |
|
401 | ! |
tags$div( |
402 | ! |
class = "data-extract-box", |
403 | ! |
tags$label("Color settings"), |
404 | ! |
shinyWidgets::switchInput(inputId = ns("coloring"), value = TRUE, size = "mini"), |
405 | ! |
conditionalPanel( |
406 | ! |
condition = paste0("input['", ns("coloring"), "']"), |
407 | ! |
tags$div( |
408 | ! |
teal.transform::data_extract_ui( |
409 | ! |
id = ns("color"), |
410 | ! |
label = "Outline color by variable", |
411 | ! |
data_extract_spec = args$color, |
412 | ! |
is_single_dataset = is_single_dataset_value |
413 |
), |
|
414 | ! |
teal.transform::data_extract_ui( |
415 | ! |
id = ns("fill"), |
416 | ! |
label = "Fill color by variable", |
417 | ! |
data_extract_spec = args$fill, |
418 | ! |
is_single_dataset = is_single_dataset_value |
419 |
), |
|
420 | ! |
tags$div( |
421 | ! |
id = ns("size_settings"), |
422 | ! |
teal.transform::data_extract_ui( |
423 | ! |
id = ns("size"), |
424 | ! |
label = "Size of points by variable (only if x and y are numeric)", |
425 | ! |
data_extract_spec = args$size, |
426 | ! |
is_single_dataset = is_single_dataset_value |
427 |
) |
|
428 |
) |
|
429 |
) |
|
430 |
) |
|
431 |
) |
|
432 |
}, |
|
433 | ! |
teal.widgets::panel_group( |
434 | ! |
teal.widgets::panel_item( |
435 | ! |
title = "Plot settings", |
436 | ! |
checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = args$rotate_xaxis_labels), |
437 | ! |
checkboxInput(ns("swap_axes"), "Swap axes", value = args$swap_axes), |
438 | ! |
selectInput( |
439 | ! |
inputId = ns("ggtheme"), |
440 | ! |
label = "Theme (by ggplot):", |
441 | ! |
choices = ggplot_themes, |
442 | ! |
selected = args$ggtheme, |
443 | ! |
multiple = FALSE |
444 |
), |
|
445 | ! |
sliderInput( |
446 | ! |
ns("alpha"), "Opacity Scatterplot:", |
447 | ! |
min = 0, max = 1, |
448 | ! |
step = .05, value = .5, ticks = FALSE |
449 |
), |
|
450 | ! |
sliderInput( |
451 | ! |
ns("fixed_size"), "Scatterplot point size:", |
452 | ! |
min = 1, max = 8, |
453 | ! |
step = 1, value = 2, ticks = FALSE |
454 |
), |
|
455 | ! |
checkboxInput(ns("add_lines"), "Add lines"), |
456 |
) |
|
457 |
) |
|
458 |
), |
|
459 | ! |
forms = tagList( |
460 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
461 |
), |
|
462 | ! |
pre_output = args$pre_output, |
463 | ! |
post_output = args$post_output |
464 |
) |
|
465 |
} |
|
466 | ||
467 |
# Server function for the bivariate module |
|
468 |
srv_g_bivariate <- function(id, |
|
469 |
data, |
|
470 |
reporter, |
|
471 |
filter_panel_api, |
|
472 |
x, |
|
473 |
y, |
|
474 |
row_facet, |
|
475 |
col_facet, |
|
476 |
color_settings = FALSE, |
|
477 |
color, |
|
478 |
fill, |
|
479 |
size, |
|
480 |
plot_height, |
|
481 |
plot_width, |
|
482 |
ggplot2_args, |
|
483 |
decorators) { |
|
484 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
485 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
486 | ! |
checkmate::assert_class(data, "reactive") |
487 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
488 | ! |
moduleServer(id, function(input, output, session) { |
489 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
490 | ||
491 | ! |
ns <- session$ns |
492 | ||
493 | ! |
data_extract <- list( |
494 | ! |
x = x, y = y, row_facet = row_facet, col_facet = col_facet, |
495 | ! |
color = color, fill = fill, size = size |
496 |
) |
|
497 | ||
498 | ! |
rule_var <- function(other) { |
499 | ! |
function(value) { |
500 | ! |
othervalue <- selector_list()[[other]]()$select |
501 | ! |
if (length(value) == 0L && length(othervalue) == 0L) { |
502 | ! |
"Please select at least one of x-variable or y-variable" |
503 |
} |
|
504 |
} |
|
505 |
} |
|
506 | ! |
rule_diff <- function(other) { |
507 | ! |
function(value) { |
508 | ! |
othervalue <- selector_list()[[other]]()[["select"]] |
509 | ! |
if (!is.null(othervalue)) { |
510 | ! |
if (identical(value, othervalue)) { |
511 | ! |
"Row and column facetting variables must be different." |
512 |
} |
|
513 |
} |
|
514 |
} |
|
515 |
} |
|
516 | ||
517 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
518 | ! |
data_extract = data_extract, |
519 | ! |
datasets = data, |
520 | ! |
select_validation_rule = list( |
521 | ! |
x = rule_var("y"), |
522 | ! |
y = rule_var("x"), |
523 | ! |
row_facet = shinyvalidate::compose_rules( |
524 | ! |
shinyvalidate::sv_optional(), |
525 | ! |
rule_diff("col_facet") |
526 |
), |
|
527 | ! |
col_facet = shinyvalidate::compose_rules( |
528 | ! |
shinyvalidate::sv_optional(), |
529 | ! |
rule_diff("row_facet") |
530 |
) |
|
531 |
) |
|
532 |
) |
|
533 | ||
534 | ! |
iv_r <- reactive({ |
535 | ! |
iv_facet <- shinyvalidate::InputValidator$new() |
536 | ! |
iv_child <- teal.transform::compose_and_enable_validators(iv_facet, selector_list, |
537 | ! |
validator_names = c("row_facet", "col_facet") |
538 |
) |
|
539 | ! |
iv_child$condition(~ isTRUE(input$facetting)) |
540 | ||
541 | ! |
iv <- shinyvalidate::InputValidator$new() |
542 | ! |
iv$add_validator(iv_child) |
543 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list, validator_names = c("x", "y")) |
544 |
}) |
|
545 | ||
546 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
547 | ! |
selector_list = selector_list, |
548 | ! |
datasets = data |
549 |
) |
|
550 | ||
551 | ! |
anl_merged_q <- reactive({ |
552 | ! |
req(anl_merged_input()) |
553 | ! |
data() %>% |
554 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
555 |
}) |
|
556 | ||
557 | ! |
merged <- list( |
558 | ! |
anl_input_r = anl_merged_input, |
559 | ! |
anl_q_r = anl_merged_q |
560 |
) |
|
561 | ||
562 | ! |
output_q <- reactive({ |
563 | ! |
teal::validate_inputs(iv_r()) |
564 | ||
565 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
566 | ! |
teal::validate_has_data(ANL, 3) |
567 | ||
568 | ! |
x_col_vec <- as.vector(merged$anl_input_r()$columns_source$x) |
569 | ! |
x_name <- `if`(is.null(x_col_vec), character(0), x_col_vec) |
570 | ! |
y_col_vec <- as.vector(merged$anl_input_r()$columns_source$y) |
571 | ! |
y_name <- `if`(is.null(y_col_vec), character(0), y_col_vec) |
572 | ||
573 | ! |
row_facet_name <- as.vector(merged$anl_input_r()$columns_source$row_facet) |
574 | ! |
col_facet_name <- as.vector(merged$anl_input_r()$columns_source$col_facet) |
575 | ! |
color_name <- if ("color" %in% names(merged$anl_input_r()$columns_source)) { |
576 | ! |
as.vector(merged$anl_input_r()$columns_source$color) |
577 |
} else { |
|
578 | ! |
character(0) |
579 |
} |
|
580 | ! |
fill_name <- if ("fill" %in% names(merged$anl_input_r()$columns_source)) { |
581 | ! |
as.vector(merged$anl_input_r()$columns_source$fill) |
582 |
} else { |
|
583 | ! |
character(0) |
584 |
} |
|
585 | ! |
size_name <- if ("size" %in% names(merged$anl_input_r()$columns_source)) { |
586 | ! |
as.vector(merged$anl_input_r()$columns_source$size) |
587 |
} else { |
|
588 | ! |
character(0) |
589 |
} |
|
590 | ||
591 | ! |
use_density <- input$use_density == "density" |
592 | ! |
free_x_scales <- input$free_x_scales |
593 | ! |
free_y_scales <- input$free_y_scales |
594 | ! |
ggtheme <- input$ggtheme |
595 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
596 | ! |
swap_axes <- input$swap_axes |
597 | ||
598 | ! |
is_scatterplot <- all(vapply(ANL[c(x_name, y_name)], is.numeric, logical(1))) && |
599 | ! |
length(x_name) > 0 && length(y_name) > 0 |
600 | ||
601 | ! |
if (is_scatterplot) { |
602 | ! |
shinyjs::show("alpha") |
603 | ! |
alpha <- input$alpha |
604 | ! |
shinyjs::show("add_lines") |
605 | ||
606 | ! |
if (color_settings && input$coloring) { |
607 | ! |
shinyjs::hide("fixed_size") |
608 | ! |
shinyjs::show("size_settings") |
609 | ! |
size <- NULL |
610 |
} else { |
|
611 | ! |
shinyjs::show("fixed_size") |
612 | ! |
size <- input$fixed_size |
613 |
} |
|
614 |
} else { |
|
615 | ! |
shinyjs::hide("add_lines") |
616 | ! |
updateCheckboxInput(session, "add_lines", value = restoreInput(ns("add_lines"), FALSE)) |
617 | ! |
shinyjs::hide("alpha") |
618 | ! |
shinyjs::hide("fixed_size") |
619 | ! |
shinyjs::hide("size_settings") |
620 | ! |
alpha <- 1 |
621 | ! |
size <- NULL |
622 |
} |
|
623 | ||
624 | ! |
teal::validate_has_data(ANL[, c(x_name, y_name), drop = FALSE], 3, complete = TRUE, allow_inf = FALSE) |
625 | ||
626 | ! |
cl <- bivariate_plot_call( |
627 | ! |
data_name = "ANL", |
628 | ! |
x = x_name, |
629 | ! |
y = y_name, |
630 | ! |
x_class = ifelse(!identical(x_name, character(0)), class(ANL[[x_name]]), "NULL"), |
631 | ! |
y_class = ifelse(!identical(y_name, character(0)), class(ANL[[y_name]]), "NULL"), |
632 | ! |
x_label = varname_w_label(x_name, ANL), |
633 | ! |
y_label = varname_w_label(y_name, ANL), |
634 | ! |
freq = !use_density, |
635 | ! |
theme = ggtheme, |
636 | ! |
rotate_xaxis_labels = rotate_xaxis_labels, |
637 | ! |
swap_axes = swap_axes, |
638 | ! |
alpha = alpha, |
639 | ! |
size = size, |
640 | ! |
ggplot2_args = ggplot2_args |
641 |
) |
|
642 | ||
643 | ! |
facetting <- (isTRUE(input$facetting) && (!is.null(row_facet_name) || !is.null(col_facet_name))) |
644 | ||
645 | ! |
if (facetting) { |
646 | ! |
facet_cl <- facet_ggplot_call(row_facet_name, col_facet_name, free_x_scales, free_y_scales) |
647 | ||
648 | ! |
if (!is.null(facet_cl)) { |
649 | ! |
cl <- call("+", cl, facet_cl) |
650 |
} |
|
651 |
} |
|
652 | ||
653 | ! |
if (input$add_lines) { |
654 | ! |
cl <- call("+", cl, quote(geom_line(size = 1))) |
655 |
} |
|
656 | ||
657 | ! |
coloring_cl <- NULL |
658 | ! |
if (color_settings) { |
659 | ! |
if (input$coloring) { |
660 | ! |
coloring_cl <- coloring_ggplot_call( |
661 | ! |
colour = color_name, |
662 | ! |
fill = fill_name, |
663 | ! |
size = size_name, |
664 | ! |
is_point = any(grepl("geom_point", cl %>% deparse())) |
665 |
) |
|
666 | ! |
legend_lbls <- substitute( |
667 | ! |
expr = labs(color = color_name, fill = fill_name, size = size_name), |
668 | ! |
env = list( |
669 | ! |
color_name = varname_w_label(color_name, ANL), |
670 | ! |
fill_name = varname_w_label(fill_name, ANL), |
671 | ! |
size_name = varname_w_label(size_name, ANL) |
672 |
) |
|
673 |
) |
|
674 |
} |
|
675 | ! |
if (!is.null(coloring_cl)) { |
676 | ! |
cl <- call("+", call("+", cl, coloring_cl), legend_lbls) |
677 |
} |
|
678 |
} |
|
679 | ||
680 | ! |
teal.code::eval_code(merged$anl_q_r(), substitute(expr = plot <- cl, env = list(cl = cl))) |
681 |
}) |
|
682 | ||
683 | ! |
decorated_output_q_facets <- srv_decorate_teal_data( |
684 | ! |
"decorator", |
685 | ! |
data = output_q, |
686 | ! |
decorators = select_decorators(decorators, "plot"), |
687 | ! |
expr = reactive({ |
688 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
689 | ! |
row_facet_name <- as.vector(merged$anl_input_r()$columns_source$row_facet) |
690 | ! |
col_facet_name <- as.vector(merged$anl_input_r()$columns_source$col_facet) |
691 | ||
692 |
# Add labels to facets |
|
693 | ! |
nulled_row_facet_name <- varname_w_label(row_facet_name, ANL) |
694 | ! |
nulled_col_facet_name <- varname_w_label(col_facet_name, ANL) |
695 | ! |
facetting <- (isTRUE(input$facetting) && (!is.null(row_facet_name) || !is.null(col_facet_name))) |
696 | ! |
without_facet <- (is.null(nulled_row_facet_name) && is.null(nulled_col_facet_name)) || !facetting |
697 | ||
698 | ! |
print_call <- if (without_facet) { |
699 | ! |
quote(print(plot)) |
700 |
} else { |
|
701 | ! |
substitute( |
702 | ! |
expr = { |
703 |
# Add facetting labels |
|
704 |
# optional: grid.newpage() # nolint: commented_code. |
|
705 |
# Prefixed with teal.modules.general as its usage will appear in "Show R code" |
|
706 | ! |
plot <- teal.modules.general::add_facet_labels( |
707 | ! |
plot, |
708 | ! |
xfacet_label = nulled_col_facet_name, |
709 | ! |
yfacet_label = nulled_row_facet_name |
710 |
) |
|
711 | ! |
grid::grid.newpage() |
712 | ! |
grid::grid.draw(plot) |
713 |
}, |
|
714 | ! |
env = list(nulled_col_facet_name = nulled_col_facet_name, nulled_row_facet_name = nulled_row_facet_name) |
715 |
) |
|
716 |
} |
|
717 | ! |
print_call |
718 |
}), |
|
719 | ! |
expr_is_reactive = TRUE |
720 |
) |
|
721 | ||
722 | ! |
plot_r <- reactive(req(decorated_output_q_facets())[["plot"]]) |
723 | ||
724 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
725 | ! |
id = "myplot", |
726 | ! |
plot_r = plot_r, |
727 | ! |
height = plot_height, |
728 | ! |
width = plot_width |
729 |
) |
|
730 | ||
731 |
# Render R code. |
|
732 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_output_q_facets()))) |
733 | ||
734 | ! |
teal.widgets::verbatim_popup_srv( |
735 | ! |
id = "rcode", |
736 | ! |
verbatim_content = source_code_r, |
737 | ! |
title = "Bivariate Plot" |
738 |
) |
|
739 | ||
740 |
### REPORTER |
|
741 | ! |
if (with_reporter) { |
742 | ! |
card_fun <- function(comment, label) { |
743 | ! |
card <- teal::report_card_template( |
744 | ! |
title = "Bivariate Plot", |
745 | ! |
label = label, |
746 | ! |
with_filter = with_filter, |
747 | ! |
filter_panel_api = filter_panel_api |
748 |
) |
|
749 | ! |
card$append_text("Plot", "header3") |
750 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
751 | ! |
if (!comment == "") { |
752 | ! |
card$append_text("Comment", "header3") |
753 | ! |
card$append_text(comment) |
754 |
} |
|
755 | ! |
card$append_src(source_code_r()) |
756 | ! |
card |
757 |
} |
|
758 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
759 |
} |
|
760 |
### |
|
761 |
}) |
|
762 |
} |
|
763 | ||
764 |
# Get Substituted ggplot call |
|
765 |
bivariate_plot_call <- function(data_name, |
|
766 |
x = character(0), |
|
767 |
y = character(0), |
|
768 |
x_class = "NULL", |
|
769 |
y_class = "NULL", |
|
770 |
x_label = NULL, |
|
771 |
y_label = NULL, |
|
772 |
freq = TRUE, |
|
773 |
theme = "gray", |
|
774 |
rotate_xaxis_labels = FALSE, |
|
775 |
swap_axes = FALSE, |
|
776 |
alpha = double(0), |
|
777 |
size = 2, |
|
778 |
ggplot2_args = teal.widgets::ggplot2_args()) { |
|
779 | ! |
supported_types <- c("NULL", "numeric", "integer", "factor", "character", "logical", "ordered") |
780 | ! |
validate(need(x_class %in% supported_types, paste0("Data type '", x_class, "' is not supported."))) |
781 | ! |
validate(need(y_class %in% supported_types, paste0("Data type '", y_class, "' is not supported."))) |
782 | ||
783 | ||
784 | ! |
if (identical(x, character(0))) { |
785 | ! |
x <- x_label <- "-" |
786 |
} else { |
|
787 | ! |
x <- if (is.call(x)) x else as.name(x) |
788 |
} |
|
789 | ! |
if (identical(y, character(0))) { |
790 | ! |
y <- y_label <- "-" |
791 |
} else { |
|
792 | ! |
y <- if (is.call(y)) y else as.name(y) |
793 |
} |
|
794 | ||
795 | ! |
cl <- bivariate_ggplot_call( |
796 | ! |
x_class = x_class, |
797 | ! |
y_class = y_class, |
798 | ! |
freq = freq, |
799 | ! |
theme = theme, |
800 | ! |
rotate_xaxis_labels = rotate_xaxis_labels, |
801 | ! |
swap_axes = swap_axes, |
802 | ! |
alpha = alpha, |
803 | ! |
size = size, |
804 | ! |
ggplot2_args = ggplot2_args, |
805 | ! |
x = x, |
806 | ! |
y = y, |
807 | ! |
xlab = x_label, |
808 | ! |
ylab = y_label, |
809 | ! |
data_name = data_name |
810 |
) |
|
811 |
} |
|
812 | ||
813 |
# Create ggplot part of plot call |
|
814 |
# Due to the type of the x and y variable the plot type is chosen |
|
815 |
bivariate_ggplot_call <- function(x_class, |
|
816 |
y_class, |
|
817 |
freq = TRUE, |
|
818 |
theme = "gray", |
|
819 |
rotate_xaxis_labels = FALSE, |
|
820 |
swap_axes = FALSE, |
|
821 |
size = double(0), |
|
822 |
alpha = double(0), |
|
823 |
x = NULL, |
|
824 |
y = NULL, |
|
825 |
xlab = "-", |
|
826 |
ylab = "-", |
|
827 |
data_name = "ANL", |
|
828 |
ggplot2_args = teal.widgets::ggplot2_args()) { |
|
829 | 42x |
x_class <- switch(x_class, |
830 | 42x |
"character" = , |
831 | 42x |
"ordered" = , |
832 | 42x |
"logical" = , |
833 | 42x |
"factor" = "factor", |
834 | 42x |
"integer" = , |
835 | 42x |
"numeric" = "numeric", |
836 | 42x |
"NULL" = "NULL", |
837 | 42x |
stop("unsupported x_class: ", x_class) |
838 |
) |
|
839 | 42x |
y_class <- switch(y_class, |
840 | 42x |
"character" = , |
841 | 42x |
"ordered" = , |
842 | 42x |
"logical" = , |
843 | 42x |
"factor" = "factor", |
844 | 42x |
"integer" = , |
845 | 42x |
"numeric" = "numeric", |
846 | 42x |
"NULL" = "NULL", |
847 | 42x |
stop("unsupported y_class: ", y_class) |
848 |
) |
|
849 | ||
850 | 42x |
if (all(c(x_class, y_class) == "NULL")) { |
851 | ! |
stop("either x or y is required") |
852 |
} |
|
853 | ||
854 | 42x |
reduce_plot_call <- function(...) { |
855 | 104x |
args <- Filter(Negate(is.null), list(...)) |
856 | 104x |
Reduce(function(x, y) call("+", x, y), args) |
857 |
} |
|
858 | ||
859 | 42x |
plot_call <- substitute(ggplot(data_name), env = list(data_name = as.name(data_name))) |
860 | ||
861 |
# Single data plots |
|
862 | 42x |
if (x_class == "numeric" && y_class == "NULL") { |
863 | 6x |
plot_call <- reduce_plot_call(plot_call, substitute(aes(x = xval), env = list(xval = x))) |
864 | ||
865 | 6x |
if (freq) { |
866 | 4x |
plot_call <- reduce_plot_call( |
867 | 4x |
plot_call, |
868 | 4x |
quote(geom_histogram(bins = 30)), |
869 | 4x |
quote(ylab("Frequency")) |
870 |
) |
|
871 |
} else { |
|
872 | 2x |
plot_call <- reduce_plot_call( |
873 | 2x |
plot_call, |
874 | 2x |
quote(geom_histogram(bins = 30, aes(y = after_stat(density)))), |
875 | 2x |
quote(geom_density(aes(y = after_stat(density)))), |
876 | 2x |
quote(ylab("Density")) |
877 |
) |
|
878 |
} |
|
879 | 36x |
} else if (x_class == "NULL" && y_class == "numeric") { |
880 | 6x |
plot_call <- reduce_plot_call(plot_call, substitute(aes(x = yval), env = list(yval = y))) |
881 | ||
882 | 6x |
if (freq) { |
883 | 4x |
plot_call <- reduce_plot_call( |
884 | 4x |
plot_call, |
885 | 4x |
quote(geom_histogram(bins = 30)), |
886 | 4x |
quote(ylab("Frequency")) |
887 |
) |
|
888 |
} else { |
|
889 | 2x |
plot_call <- reduce_plot_call( |
890 | 2x |
plot_call, |
891 | 2x |
quote(geom_histogram(bins = 30, aes(y = after_stat(density)))), |
892 | 2x |
quote(geom_density(aes(y = after_stat(density)))), |
893 | 2x |
quote(ylab("Density")) |
894 |
) |
|
895 |
} |
|
896 | 30x |
} else if (x_class == "factor" && y_class == "NULL") { |
897 | 4x |
plot_call <- reduce_plot_call(plot_call, substitute(aes(x = xval), env = list(xval = x))) |
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 | 26x |
} else if (x_class == "NULL" && y_class == "factor") { |
913 | 4x |
plot_call <- reduce_plot_call(plot_call, substitute(aes(x = yval), env = list(yval = y))) |
914 | ||
915 | 4x |
if (freq) { |
916 | 2x |
plot_call <- reduce_plot_call( |
917 | 2x |
plot_call, |
918 | 2x |
quote(geom_bar()), |
919 | 2x |
quote(ylab("Frequency")) |
920 |
) |
|
921 |
} else { |
|
922 | 2x |
plot_call <- reduce_plot_call( |
923 | 2x |
plot_call, |
924 | 2x |
quote(geom_bar(aes(y = after_stat(prop), group = 1))), |
925 | 2x |
quote(ylab("Fraction")) |
926 |
) |
|
927 |
} |
|
928 |
# Numeric Plots |
|
929 | 22x |
} else if (x_class == "numeric" && y_class == "numeric") { |
930 | 2x |
plot_call <- reduce_plot_call( |
931 | 2x |
plot_call, |
932 | 2x |
substitute(aes(x = xval, y = yval), env = list(xval = x, yval = y)), |
933 |
# pch = 21 for consistent coloring behaviour b/w all geoms (outline and fill properties) |
|
934 | 2x |
`if`( |
935 | 2x |
!is.null(size), |
936 | 2x |
substitute( |
937 | 2x |
geom_point(alpha = alphaval, size = sizeval, pch = 21), |
938 | 2x |
env = list(alphaval = alpha, sizeval = size) |
939 |
), |
|
940 | 2x |
substitute( |
941 | 2x |
geom_point(alpha = alphaval, pch = 21), |
942 | 2x |
env = list(alphaval = alpha) |
943 |
) |
|
944 |
) |
|
945 |
) |
|
946 | 20x |
} else if ((x_class == "numeric" && y_class == "factor") || (x_class == "factor" && y_class == "numeric")) { |
947 | 6x |
plot_call <- reduce_plot_call( |
948 | 6x |
plot_call, |
949 | 6x |
substitute(aes(x = xval, y = yval), env = list(xval = x, yval = y)), |
950 | 6x |
quote(geom_boxplot()) |
951 |
) |
|
952 |
# Factor and character plots |
|
953 | 14x |
} else if (x_class == "factor" && y_class == "factor") { |
954 | 14x |
plot_call <- reduce_plot_call( |
955 | 14x |
plot_call, |
956 | 14x |
substitute( |
957 | 14x |
ggmosaic::geom_mosaic(aes(x = ggmosaic::product(xval), fill = yval), na.rm = TRUE), |
958 | 14x |
env = list(xval = x, yval = y) |
959 |
) |
|
960 |
) |
|
961 |
} else { |
|
962 | ! |
stop("x y type combination not allowed") |
963 |
} |
|
964 | ||
965 | 42x |
labs_base <- if (x_class == "NULL") { |
966 | 10x |
list(x = substitute(ylab, list(ylab = ylab))) |
967 | 42x |
} else if (y_class == "NULL") { |
968 | 10x |
list(x = substitute(xlab, list(xlab = xlab))) |
969 |
} else { |
|
970 | 22x |
list( |
971 | 22x |
x = substitute(xlab, list(xlab = xlab)), |
972 | 22x |
y = substitute(ylab, list(ylab = ylab)) |
973 |
) |
|
974 |
} |
|
975 | ||
976 | 42x |
dev_ggplot2_args <- teal.widgets::ggplot2_args(labs = labs_base) |
977 | ||
978 | 42x |
if (rotate_xaxis_labels) { |
979 | ! |
dev_ggplot2_args$theme <- list(axis.text.x = quote(element_text(angle = 45, hjust = 1))) |
980 |
} |
|
981 | ||
982 | 42x |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
983 | 42x |
user_plot = ggplot2_args, |
984 | 42x |
module_plot = dev_ggplot2_args |
985 |
) |
|
986 | ||
987 | 42x |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args(all_ggplot2_args, ggtheme = theme) |
988 | ||
989 | 42x |
plot_call <- reduce_plot_call( |
990 | 42x |
plot_call, |
991 | 42x |
parsed_ggplot2_args$labs, |
992 | 42x |
parsed_ggplot2_args$ggtheme, |
993 | 42x |
parsed_ggplot2_args$theme |
994 |
) |
|
995 | ||
996 | 42x |
if (swap_axes) { |
997 | ! |
plot_call <- reduce_plot_call(plot_call, quote(coord_flip())) |
998 |
} |
|
999 | ||
1000 | 42x |
plot_call |
1001 |
} |
|
1002 | ||
1003 |
# Create facet call |
|
1004 |
facet_ggplot_call <- function(row_facet = character(0), |
|
1005 |
col_facet = character(0), |
|
1006 |
free_x_scales = FALSE, |
|
1007 |
free_y_scales = FALSE) { |
|
1008 | ! |
scales <- if (free_x_scales && free_y_scales) { |
1009 | ! |
"free" |
1010 | ! |
} else if (free_x_scales) { |
1011 | ! |
"free_x" |
1012 | ! |
} else if (free_y_scales) { |
1013 | ! |
"free_y" |
1014 |
} else { |
|
1015 | ! |
"fixed" |
1016 |
} |
|
1017 | ||
1018 | ! |
if (identical(row_facet, character(0)) && identical(col_facet, character(0))) { |
1019 | ! |
NULL |
1020 | ! |
} else if (!identical(row_facet, character(0)) && !identical(col_facet, character(0))) { |
1021 | ! |
call( |
1022 | ! |
"facet_grid", |
1023 | ! |
rows = call_fun_dots("vars", row_facet), |
1024 | ! |
cols = call_fun_dots("vars", col_facet), |
1025 | ! |
scales = scales |
1026 |
) |
|
1027 | ! |
} else if (identical(row_facet, character(0)) && !identical(col_facet, character(0))) { |
1028 | ! |
call("facet_grid", cols = call_fun_dots("vars", col_facet), scales = scales) |
1029 | ! |
} else if (!identical(row_facet, character(0)) && identical(col_facet, character(0))) { |
1030 | ! |
call("facet_grid", rows = call_fun_dots("vars", row_facet), scales = scales) |
1031 |
} |
|
1032 |
} |
|
1033 | ||
1034 |
coloring_ggplot_call <- function(colour, |
|
1035 |
fill, |
|
1036 |
size, |
|
1037 |
is_point = FALSE) { |
|
1038 |
if ( |
|
1039 | 15x |
!identical(colour, character(0)) && |
1040 | 15x |
!identical(fill, character(0)) && |
1041 | 15x |
is_point && |
1042 | 15x |
!identical(size, character(0)) |
1043 |
) { |
|
1044 | 1x |
substitute( |
1045 | 1x |
expr = aes(colour = colour_name, fill = fill_name, size = size_name), |
1046 | 1x |
env = list(colour_name = as.name(colour), fill_name = as.name(fill), size_name = as.name(size)) |
1047 |
) |
|
1048 |
} else if ( |
|
1049 | 14x |
identical(colour, character(0)) && |
1050 | 14x |
!identical(fill, character(0)) && |
1051 | 14x |
is_point && |
1052 | 14x |
identical(size, character(0)) |
1053 |
) { |
|
1054 | 1x |
substitute(expr = aes(fill = fill_name), env = list(fill_name = as.name(fill))) |
1055 |
} else if ( |
|
1056 | 13x |
!identical(colour, character(0)) && |
1057 | 13x |
!identical(fill, character(0)) && |
1058 | 13x |
(!is_point || identical(size, character(0))) |
1059 |
) { |
|
1060 | 3x |
substitute( |
1061 | 3x |
expr = aes(colour = colour_name, fill = fill_name), |
1062 | 3x |
env = list(colour_name = as.name(colour), fill_name = as.name(fill)) |
1063 |
) |
|
1064 |
} else if ( |
|
1065 | 10x |
!identical(colour, character(0)) && |
1066 | 10x |
identical(fill, character(0)) && |
1067 | 10x |
(!is_point || identical(size, character(0))) |
1068 |
) { |
|
1069 | 1x |
substitute(expr = aes(colour = colour_name), env = list(colour_name = as.name(colour))) |
1070 |
} else if ( |
|
1071 | 9x |
identical(colour, character(0)) && |
1072 | 9x |
!identical(fill, character(0)) && |
1073 | 9x |
(!is_point || identical(size, character(0))) |
1074 |
) { |
|
1075 | 2x |
substitute(expr = aes(fill = fill_name), env = list(fill_name = as.name(fill))) |
1076 |
} else if ( |
|
1077 | 7x |
identical(colour, character(0)) && |
1078 | 7x |
identical(fill, character(0)) && |
1079 | 7x |
is_point && |
1080 | 7x |
!identical(size, character(0)) |
1081 |
) { |
|
1082 | 1x |
substitute(expr = aes(size = size_name), env = list(size_name = as.name(size))) |
1083 |
} else if ( |
|
1084 | 6x |
!identical(colour, character(0)) && |
1085 | 6x |
identical(fill, character(0)) && |
1086 | 6x |
is_point && |
1087 | 6x |
!identical(size, character(0)) |
1088 |
) { |
|
1089 | 1x |
substitute( |
1090 | 1x |
expr = aes(colour = colour_name, size = size_name), |
1091 | 1x |
env = list(colour_name = as.name(colour), size_name = as.name(size)) |
1092 |
) |
|
1093 |
} else if ( |
|
1094 | 5x |
identical(colour, character(0)) && |
1095 | 5x |
!identical(fill, character(0)) && |
1096 | 5x |
is_point && |
1097 | 5x |
!identical(size, character(0)) |
1098 |
) { |
|
1099 | 1x |
substitute( |
1100 | 1x |
expr = aes(colour = colour_name, fill = fill_name, size = size_name), |
1101 | 1x |
env = list(colour_name = as.name(fill), fill_name = as.name(fill), size_name = as.name(size)) |
1102 |
) |
|
1103 |
} else { |
|
1104 | 4x |
NULL |
1105 |
} |
|
1106 |
} |
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 matrix |
|
2 |
#' |
|
3 |
#' Generates a scatterplot matrix from selected `variables` from datasets. |
|
4 |
#' Each plot within the matrix represents the relationship between two variables, |
|
5 |
#' providing the overview of correlations and distributions across selected data. |
|
6 |
#' |
|
7 |
#' @note For more examples, please see the vignette "Using scatterplot matrix" via |
|
8 |
#' `vignette("using-scatterplot-matrix", package = "teal.modules.general")`. |
|
9 |
#' |
|
10 |
#' @inheritParams teal::module |
|
11 |
#' @inheritParams tm_g_scatterplot |
|
12 |
#' @inheritParams shared_params |
|
13 |
#' |
|
14 |
#' @param variables (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
15 |
#' Specifies plotting variables from an incoming dataset with filtering and selecting. In case of |
|
16 |
#' `data_extract_spec` use `select_spec(..., ordered = TRUE)` if plot elements should be |
|
17 |
#' rendered according to selection order. |
|
18 |
#' |
|
19 |
#' @inherit shared_params return |
|
20 |
#' |
|
21 |
#' @section Decorating Module: |
|
22 |
#' |
|
23 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
24 |
#' - `plot` (`trellis` - output of `lattice::splom`) |
|
25 |
#' |
|
26 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
27 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
28 |
#' See code snippet below: |
|
29 |
#' |
|
30 |
#' ``` |
|
31 |
#' tm_g_scatterplotmatrix( |
|
32 |
#' ..., # arguments for module |
|
33 |
#' decorators = list( |
|
34 |
#' plot = teal_transform_module(...) # applied to the `plot` output |
|
35 |
#' ) |
|
36 |
#' ) |
|
37 |
#' ``` |
|
38 |
#' |
|
39 |
#' For additional details and examples of decorators, refer to the vignette |
|
40 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
41 |
#' |
|
42 |
#' @examplesShinylive |
|
43 |
#' library(teal.modules.general) |
|
44 |
#' interactive <- function() TRUE |
|
45 |
#' {{ next_example }} |
|
46 |
#' @examples |
|
47 |
#' # general data example |
|
48 |
#' data <- teal_data() |
|
49 |
#' data <- within(data, { |
|
50 |
#' countries <- data.frame( |
|
51 |
#' id = c("DE", "FR", "IT", "ES", "PT", "GR", "NL", "BE", "LU", "AT"), |
|
52 |
#' government = factor( |
|
53 |
#' c(2, 2, 2, 1, 2, 2, 1, 1, 1, 2), |
|
54 |
#' labels = c("Monarchy", "Republic") |
|
55 |
#' ), |
|
56 |
#' language_family = factor( |
|
57 |
#' c(1, 3, 3, 3, 3, 2, 1, 1, 3, 1), |
|
58 |
#' labels = c("Germanic", "Hellenic", "Romance") |
|
59 |
#' ), |
|
60 |
#' population = c(83, 67, 60, 47, 10, 11, 17, 11, 0.6, 9), |
|
61 |
#' area = c(357, 551, 301, 505, 92, 132, 41, 30, 2.6, 83), |
|
62 |
#' gdp = c(3.4, 2.7, 2.1, 1.4, 0.3, 0.2, 0.7, 0.5, 0.1, 0.4), |
|
63 |
#' debt = c(2.1, 2.3, 2.4, 2.6, 2.3, 2.4, 2.3, 2.4, 2.3, 2.4) |
|
64 |
#' ) |
|
65 |
#' sales <- data.frame( |
|
66 |
#' id = 1:50, |
|
67 |
#' country_id = sample( |
|
68 |
#' c("DE", "FR", "IT", "ES", "PT", "GR", "NL", "BE", "LU", "AT"), |
|
69 |
#' size = 50, |
|
70 |
#' replace = TRUE |
|
71 |
#' ), |
|
72 |
#' year = sort(sample(2010:2020, 50, replace = TRUE)), |
|
73 |
#' venue = sample(c("small", "medium", "large", "online"), 50, replace = TRUE), |
|
74 |
#' cancelled = sample(c(TRUE, FALSE), 50, replace = TRUE), |
|
75 |
#' quantity = rnorm(50, 100, 20), |
|
76 |
#' costs = rnorm(50, 80, 20), |
|
77 |
#' profit = rnorm(50, 20, 10) |
|
78 |
#' ) |
|
79 |
#' }) |
|
80 |
#' join_keys(data) <- join_keys( |
|
81 |
#' join_key("countries", "countries", "id"), |
|
82 |
#' join_key("sales", "sales", "id"), |
|
83 |
#' join_key("countries", "sales", c("id" = "country_id")) |
|
84 |
#' ) |
|
85 |
#' |
|
86 |
#' app <- init( |
|
87 |
#' data = data, |
|
88 |
#' modules = modules( |
|
89 |
#' tm_g_scatterplotmatrix( |
|
90 |
#' label = "Scatterplot matrix", |
|
91 |
#' variables = list( |
|
92 |
#' data_extract_spec( |
|
93 |
#' dataname = "countries", |
|
94 |
#' select = select_spec( |
|
95 |
#' label = "Select variables:", |
|
96 |
#' choices = variable_choices(data[["countries"]]), |
|
97 |
#' selected = c("area", "gdp", "debt"), |
|
98 |
#' multiple = TRUE, |
|
99 |
#' ordered = TRUE, |
|
100 |
#' fixed = FALSE |
|
101 |
#' ) |
|
102 |
#' ), |
|
103 |
#' data_extract_spec( |
|
104 |
#' dataname = "sales", |
|
105 |
#' filter = filter_spec( |
|
106 |
#' label = "Select variable:", |
|
107 |
#' vars = "country_id", |
|
108 |
#' choices = value_choices(data[["sales"]], "country_id"), |
|
109 |
#' selected = c("DE", "FR", "IT", "ES", "PT", "GR", "NL", "BE", "LU", "AT"), |
|
110 |
#' multiple = TRUE |
|
111 |
#' ), |
|
112 |
#' select = select_spec( |
|
113 |
#' label = "Select variables:", |
|
114 |
#' choices = variable_choices(data[["sales"]], c("quantity", "costs", "profit")), |
|
115 |
#' selected = c("quantity", "costs", "profit"), |
|
116 |
#' multiple = TRUE, |
|
117 |
#' ordered = TRUE, |
|
118 |
#' fixed = FALSE |
|
119 |
#' ) |
|
120 |
#' ) |
|
121 |
#' ) |
|
122 |
#' ) |
|
123 |
#' ) |
|
124 |
#' ) |
|
125 |
#' if (interactive()) { |
|
126 |
#' shinyApp(app$ui, app$server) |
|
127 |
#' } |
|
128 |
#' |
|
129 |
#' @examplesShinylive |
|
130 |
#' library(teal.modules.general) |
|
131 |
#' interactive <- function() TRUE |
|
132 |
#' {{ next_example }} |
|
133 |
#' @examples |
|
134 |
#' # CDISC data example |
|
135 |
#' data <- teal_data() |
|
136 |
#' data <- within(data, { |
|
137 |
#' ADSL <- teal.data::rADSL |
|
138 |
#' ADRS <- teal.data::rADRS |
|
139 |
#' }) |
|
140 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
141 |
#' |
|
142 |
#' app <- init( |
|
143 |
#' data = data, |
|
144 |
#' modules = modules( |
|
145 |
#' tm_g_scatterplotmatrix( |
|
146 |
#' label = "Scatterplot matrix", |
|
147 |
#' variables = list( |
|
148 |
#' data_extract_spec( |
|
149 |
#' dataname = "ADSL", |
|
150 |
#' select = select_spec( |
|
151 |
#' label = "Select variables:", |
|
152 |
#' choices = variable_choices(data[["ADSL"]]), |
|
153 |
#' selected = c("AGE", "RACE", "SEX"), |
|
154 |
#' multiple = TRUE, |
|
155 |
#' ordered = TRUE, |
|
156 |
#' fixed = FALSE |
|
157 |
#' ) |
|
158 |
#' ), |
|
159 |
#' data_extract_spec( |
|
160 |
#' dataname = "ADRS", |
|
161 |
#' filter = filter_spec( |
|
162 |
#' label = "Select endpoints:", |
|
163 |
#' vars = c("PARAMCD", "AVISIT"), |
|
164 |
#' choices = value_choices(data[["ADRS"]], c("PARAMCD", "AVISIT"), c("PARAM", "AVISIT")), |
|
165 |
#' selected = "INVET - END OF INDUCTION", |
|
166 |
#' multiple = TRUE |
|
167 |
#' ), |
|
168 |
#' select = select_spec( |
|
169 |
#' label = "Select variables:", |
|
170 |
#' choices = variable_choices(data[["ADRS"]]), |
|
171 |
#' selected = c("AGE", "AVAL", "ADY"), |
|
172 |
#' multiple = TRUE, |
|
173 |
#' ordered = TRUE, |
|
174 |
#' fixed = FALSE |
|
175 |
#' ) |
|
176 |
#' ) |
|
177 |
#' ) |
|
178 |
#' ) |
|
179 |
#' ) |
|
180 |
#' ) |
|
181 |
#' if (interactive()) { |
|
182 |
#' shinyApp(app$ui, app$server) |
|
183 |
#' } |
|
184 |
#' |
|
185 |
#' @export |
|
186 |
#' |
|
187 |
tm_g_scatterplotmatrix <- function(label = "Scatterplot Matrix", |
|
188 |
variables, |
|
189 |
plot_height = c(600, 200, 2000), |
|
190 |
plot_width = NULL, |
|
191 |
pre_output = NULL, |
|
192 |
post_output = NULL, |
|
193 |
transformators = list(), |
|
194 |
decorators = list()) { |
|
195 | ! |
message("Initializing tm_g_scatterplotmatrix") |
196 | ||
197 |
# Normalize the parameters |
|
198 | ! |
if (inherits(variables, "data_extract_spec")) variables <- list(variables) |
199 | ||
200 |
# Start of assertions |
|
201 | ! |
checkmate::assert_string(label) |
202 | ! |
checkmate::assert_list(variables, types = "data_extract_spec") |
203 | ||
204 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
205 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
206 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
207 | ! |
checkmate::assert_numeric( |
208 | ! |
plot_width[1], |
209 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
210 |
) |
|
211 | ||
212 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
213 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
214 | ||
215 | ! |
assert_decorators(decorators, "plot") |
216 |
# End of assertions |
|
217 | ||
218 |
# Make UI args |
|
219 | ! |
args <- as.list(environment()) |
220 | ||
221 | ! |
ans <- module( |
222 | ! |
label = label, |
223 | ! |
server = srv_g_scatterplotmatrix, |
224 | ! |
ui = ui_g_scatterplotmatrix, |
225 | ! |
ui_args = args, |
226 | ! |
server_args = list( |
227 | ! |
variables = variables, |
228 | ! |
plot_height = plot_height, |
229 | ! |
plot_width = plot_width, |
230 | ! |
decorators = decorators |
231 |
), |
|
232 | ! |
transformators = transformators, |
233 | ! |
datanames = teal.transform::get_extract_datanames(variables) |
234 |
) |
|
235 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
236 | ! |
ans |
237 |
} |
|
238 | ||
239 |
# UI function for the scatterplot matrix module |
|
240 |
ui_g_scatterplotmatrix <- function(id, ...) { |
|
241 | ! |
args <- list(...) |
242 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$variables) |
243 | ! |
ns <- NS(id) |
244 | ! |
teal.widgets::standard_layout( |
245 | ! |
output = teal.widgets::white_small_well( |
246 | ! |
textOutput(ns("message")), |
247 | ! |
tags$br(), |
248 | ! |
teal.widgets::plot_with_settings_ui(id = ns("myplot")) |
249 |
), |
|
250 | ! |
encoding = tags$div( |
251 |
### Reporter |
|
252 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
253 |
### |
|
254 | ! |
tags$label("Encodings", class = "text-primary"), |
255 | ! |
teal.transform::datanames_input(args$variables), |
256 | ! |
teal.transform::data_extract_ui( |
257 | ! |
id = ns("variables"), |
258 | ! |
label = "Variables", |
259 | ! |
data_extract_spec = args$variables, |
260 | ! |
is_single_dataset = is_single_dataset_value |
261 |
), |
|
262 | ! |
tags$hr(), |
263 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")), |
264 | ! |
teal.widgets::panel_group( |
265 | ! |
teal.widgets::panel_item( |
266 | ! |
title = "Plot settings", |
267 | ! |
sliderInput( |
268 | ! |
ns("alpha"), "Opacity:", |
269 | ! |
min = 0, max = 1, |
270 | ! |
step = .05, value = .5, ticks = FALSE |
271 |
), |
|
272 | ! |
sliderInput( |
273 | ! |
ns("cex"), "Points size:", |
274 | ! |
min = 0.2, max = 3, |
275 | ! |
step = .05, value = .65, ticks = FALSE |
276 |
), |
|
277 | ! |
checkboxInput(ns("cor"), "Add Correlation", value = FALSE), |
278 | ! |
radioButtons( |
279 | ! |
ns("cor_method"), "Select Correlation Method", |
280 | ! |
choiceNames = c("Pearson", "Kendall", "Spearman"), |
281 | ! |
choiceValues = c("pearson", "kendall", "spearman"), |
282 | ! |
inline = TRUE |
283 |
), |
|
284 | ! |
checkboxInput(ns("cor_na_omit"), "Omit Missing Values", value = TRUE) |
285 |
) |
|
286 |
) |
|
287 |
), |
|
288 | ! |
forms = tagList( |
289 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
290 |
), |
|
291 | ! |
pre_output = args$pre_output, |
292 | ! |
post_output = args$post_output |
293 |
) |
|
294 |
} |
|
295 | ||
296 |
# Server function for the scatterplot matrix module |
|
297 |
srv_g_scatterplotmatrix <- function(id, |
|
298 |
data, |
|
299 |
reporter, |
|
300 |
filter_panel_api, |
|
301 |
variables, |
|
302 |
plot_height, |
|
303 |
plot_width, |
|
304 |
decorators) { |
|
305 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
306 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
307 | ! |
checkmate::assert_class(data, "reactive") |
308 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
309 | ! |
moduleServer(id, function(input, output, session) { |
310 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
311 | ||
312 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
313 | ! |
data_extract = list(variables = variables), |
314 | ! |
datasets = data, |
315 | ! |
select_validation_rule = list( |
316 | ! |
variables = ~ if (length(.) <= 1) "Please select at least 2 columns." |
317 |
) |
|
318 |
) |
|
319 | ||
320 | ! |
iv_r <- reactive({ |
321 | ! |
iv <- shinyvalidate::InputValidator$new() |
322 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
323 |
}) |
|
324 | ||
325 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
326 | ! |
datasets = data, |
327 | ! |
selector_list = selector_list |
328 |
) |
|
329 | ||
330 | ! |
anl_merged_q <- reactive({ |
331 | ! |
req(anl_merged_input()) |
332 | ! |
data() %>% |
333 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
334 |
}) |
|
335 | ||
336 | ! |
merged <- list( |
337 | ! |
anl_input_r = anl_merged_input, |
338 | ! |
anl_q_r = anl_merged_q |
339 |
) |
|
340 | ||
341 |
# plot |
|
342 | ! |
output_q <- reactive({ |
343 | ! |
teal::validate_inputs(iv_r()) |
344 | ||
345 | ! |
qenv <- merged$anl_q_r() |
346 | ! |
ANL <- qenv[["ANL"]] |
347 | ||
348 | ! |
cols_names <- merged$anl_input_r()$columns_source$variables |
349 | ! |
alpha <- input$alpha |
350 | ! |
cex <- input$cex |
351 | ! |
add_cor <- input$cor |
352 | ! |
cor_method <- input$cor_method |
353 | ! |
cor_na_omit <- input$cor_na_omit |
354 | ||
355 | ! |
cor_na_action <- if (isTruthy(cor_na_omit)) { |
356 | ! |
"na.omit" |
357 |
} else { |
|
358 | ! |
"na.fail" |
359 |
} |
|
360 | ||
361 | ! |
teal::validate_has_data(ANL, 10) |
362 | ! |
teal::validate_has_data(ANL[, cols_names, drop = FALSE], 10, complete = TRUE, allow_inf = FALSE) |
363 | ||
364 |
# get labels and proper variable names |
|
365 | ! |
varnames <- varname_w_label(cols_names, ANL, wrap_width = 20) |
366 | ||
367 |
# check character columns. If any, then those are converted to factors |
|
368 | ! |
check_char <- vapply(ANL[, cols_names], is.character, logical(1)) |
369 | ! |
if (any(check_char)) { |
370 | ! |
qenv <- teal.code::eval_code( |
371 | ! |
qenv, |
372 | ! |
substitute( |
373 | ! |
expr = ANL <- ANL[, cols_names] %>% |
374 | ! |
dplyr::mutate_if(is.character, as.factor) %>% |
375 | ! |
droplevels(), |
376 | ! |
env = list(cols_names = cols_names) |
377 |
) |
|
378 |
) |
|
379 |
} else { |
|
380 | ! |
qenv <- teal.code::eval_code( |
381 | ! |
qenv, |
382 | ! |
substitute( |
383 | ! |
expr = ANL <- ANL[, cols_names] %>% |
384 | ! |
droplevels(), |
385 | ! |
env = list(cols_names = cols_names) |
386 |
) |
|
387 |
) |
|
388 |
} |
|
389 | ||
390 | ||
391 |
# create plot |
|
392 | ! |
if (add_cor) { |
393 | ! |
shinyjs::show("cor_method") |
394 | ! |
shinyjs::show("cor_use") |
395 | ! |
shinyjs::show("cor_na_omit") |
396 | ||
397 | ! |
qenv <- teal.code::eval_code( |
398 | ! |
qenv, |
399 | ! |
substitute( |
400 | ! |
expr = { |
401 | ! |
plot <- lattice::splom( |
402 | ! |
ANL, |
403 | ! |
varnames = varnames_value, |
404 | ! |
panel = function(x, y, ...) { |
405 | ! |
lattice::panel.splom(x = x, y = y, ...) |
406 | ! |
cpl <- lattice::current.panel.limits() |
407 | ! |
lattice::panel.text( |
408 | ! |
mean(cpl$xlim), |
409 | ! |
mean(cpl$ylim), |
410 | ! |
get_scatterplotmatrix_stats( |
411 | ! |
x, |
412 | ! |
y, |
413 | ! |
.f = stats::cor.test, |
414 | ! |
.f_args = list(method = cor_method, na.action = cor_na_action) |
415 |
), |
|
416 | ! |
alpha = 0.6, |
417 | ! |
fontsize = 18, |
418 | ! |
fontface = "bold" |
419 |
) |
|
420 |
}, |
|
421 | ! |
pch = 16, |
422 | ! |
alpha = alpha_value, |
423 | ! |
cex = cex_value |
424 |
) |
|
425 |
}, |
|
426 | ! |
env = list( |
427 | ! |
varnames_value = varnames, |
428 | ! |
cor_method = cor_method, |
429 | ! |
cor_na_action = cor_na_action, |
430 | ! |
alpha_value = alpha, |
431 | ! |
cex_value = cex |
432 |
) |
|
433 |
) |
|
434 |
) |
|
435 |
} else { |
|
436 | ! |
shinyjs::hide("cor_method") |
437 | ! |
shinyjs::hide("cor_use") |
438 | ! |
shinyjs::hide("cor_na_omit") |
439 | ! |
qenv <- teal.code::eval_code( |
440 | ! |
qenv, |
441 | ! |
substitute( |
442 | ! |
expr = { |
443 | ! |
plot <- lattice::splom( |
444 | ! |
ANL, |
445 | ! |
varnames = varnames_value, |
446 | ! |
pch = 16, |
447 | ! |
alpha = alpha_value, |
448 | ! |
cex = cex_value |
449 |
) |
|
450 |
}, |
|
451 | ! |
env = list(varnames_value = varnames, alpha_value = alpha, cex_value = cex) |
452 |
) |
|
453 |
) |
|
454 |
} |
|
455 | ! |
qenv |
456 |
}) |
|
457 | ||
458 | ! |
decorated_output_q <- srv_decorate_teal_data( |
459 | ! |
id = "decorator", |
460 | ! |
data = output_q, |
461 | ! |
decorators = select_decorators(decorators, "plot"), |
462 | ! |
expr = print(plot) |
463 |
) |
|
464 | ||
465 | ! |
plot_r <- reactive(req(decorated_output_q())[["plot"]]) |
466 | ||
467 |
# Insert the plot into a plot_with_settings module |
|
468 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
469 | ! |
id = "myplot", |
470 | ! |
plot_r = plot_r, |
471 | ! |
height = plot_height, |
472 | ! |
width = plot_width |
473 |
) |
|
474 | ||
475 |
# show a message if conversion to factors took place |
|
476 | ! |
output$message <- renderText({ |
477 | ! |
req(iv_r()$is_valid()) |
478 | ! |
req(selector_list()$variables()) |
479 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
480 | ! |
cols_names <- unique(unname(do.call(c, merged$anl_input_r()$columns_source))) |
481 | ! |
check_char <- vapply(ANL[, cols_names], is.character, logical(1)) |
482 | ! |
if (any(check_char)) { |
483 | ! |
is_single <- sum(check_char) == 1 |
484 | ! |
paste( |
485 | ! |
"Character", |
486 | ! |
ifelse(is_single, "variable", "variables"), |
487 | ! |
paste0("(", paste(cols_names[check_char], collapse = ", "), ")"), |
488 | ! |
ifelse(is_single, "was", "were"), |
489 | ! |
"converted to", |
490 | ! |
ifelse(is_single, "factor.", "factors.") |
491 |
) |
|
492 |
} else { |
|
493 |
"" |
|
494 |
} |
|
495 |
}) |
|
496 | ||
497 |
# Render R code. |
|
498 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_output_q()))) |
499 | ||
500 | ! |
teal.widgets::verbatim_popup_srv( |
501 | ! |
id = "rcode", |
502 | ! |
verbatim_content = source_code_r, |
503 | ! |
title = "Show R Code for Scatterplotmatrix" |
504 |
) |
|
505 | ||
506 |
### REPORTER |
|
507 | ! |
if (with_reporter) { |
508 | ! |
card_fun <- function(comment, label) { |
509 | ! |
card <- teal::report_card_template( |
510 | ! |
title = "Scatter Plot Matrix", |
511 | ! |
label = label, |
512 | ! |
with_filter = with_filter, |
513 | ! |
filter_panel_api = filter_panel_api |
514 |
) |
|
515 | ! |
card$append_text("Plot", "header3") |
516 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
517 | ! |
if (!comment == "") { |
518 | ! |
card$append_text("Comment", "header3") |
519 | ! |
card$append_text(comment) |
520 |
} |
|
521 | ! |
card$append_src(source_code_r()) |
522 | ! |
card |
523 |
} |
|
524 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
525 |
} |
|
526 |
### |
|
527 |
}) |
|
528 |
} |
|
529 | ||
530 |
#' Get stats for x-y pairs in scatterplot matrix |
|
531 |
#' |
|
532 |
#' Uses [stats::cor.test()] per default for all numerical input variables and converts results |
|
533 |
#' to character vector. |
|
534 |
#' Could be extended if different stats for different variable types are needed. |
|
535 |
#' Meant to be called from [lattice::panel.text()]. |
|
536 |
#' |
|
537 |
#' Presently we need to use a formula input for `stats::cor.test` because |
|
538 |
#' `na.fail` only gets evaluated when a formula is passed (see below). |
|
539 |
#' ``` |
|
540 |
#' x = c(1,3,5,7,NA) |
|
541 |
#' y = c(3,6,7,8,1) |
|
542 |
#' stats::cor.test(x, y, na.action = "na.fail") |
|
543 |
#' stats::cor.test(~ x + y, na.action = "na.fail") |
|
544 |
#' ``` |
|
545 |
#' |
|
546 |
#' @param x,y (`numeric`) vectors of data values. `x` and `y` must have the same length. |
|
547 |
#' @param .f (`function`) function that accepts x and y as formula input `~ x + y`. |
|
548 |
#' Default `stats::cor.test`. |
|
549 |
#' @param .f_args (`list`) of arguments to be passed to `.f`. |
|
550 |
#' @param round_stat (`integer(1)`) optional, number of decimal places to use when rounding the estimate. |
|
551 |
#' @param round_pval (`integer(1)`) optional, number of decimal places to use when rounding the p-value. |
|
552 |
#' |
|
553 |
#' @return Character with stats. For [stats::cor.test()] correlation coefficient and p-value. |
|
554 |
#' |
|
555 |
#' @examples |
|
556 |
#' set.seed(1) |
|
557 |
#' x <- runif(25, 0, 1) |
|
558 |
#' y <- runif(25, 0, 1) |
|
559 |
#' x[c(3, 10, 18)] <- NA |
|
560 |
#' |
|
561 |
#' get_scatterplotmatrix_stats(x, y, .f = stats::cor.test, .f_args = list(method = "pearson")) |
|
562 |
#' get_scatterplotmatrix_stats(x, y, .f = stats::cor.test, .f_args = list( |
|
563 |
#' method = "pearson", |
|
564 |
#' na.action = na.fail |
|
565 |
#' )) |
|
566 |
#' |
|
567 |
#' @export |
|
568 |
#' |
|
569 |
get_scatterplotmatrix_stats <- function(x, y, |
|
570 |
.f = stats::cor.test, |
|
571 |
.f_args = list(), |
|
572 |
round_stat = 2, |
|
573 |
round_pval = 4) { |
|
574 | 6x |
if (is.numeric(x) && is.numeric(y)) { |
575 | 3x |
stat <- tryCatch(do.call(.f, c(list(~ x + y), .f_args)), error = function(e) NA) |
576 | ||
577 | 3x |
if (anyNA(stat)) { |
578 | 1x |
return("NA") |
579 | 2x |
} else if (all(c("estimate", "p.value") %in% names(stat))) { |
580 | 2x |
return(paste( |
581 | 2x |
c( |
582 | 2x |
paste0(names(stat$estimate), ":", round(stat$estimate, round_stat)), |
583 | 2x |
paste0("P:", round(stat$p.value, round_pval)) |
584 |
), |
|
585 | 2x |
collapse = "\n" |
586 |
)) |
|
587 |
} else { |
|
588 | ! |
stop("function not supported") |
589 |
} |
|
590 |
} else { |
|
591 | 3x |
if ("method" %in% names(.f_args)) { |
592 | 3x |
if (.f_args$method == "pearson") { |
593 | 1x |
return("cor:-") |
594 |
} |
|
595 | 2x |
if (.f_args$method == "kendall") { |
596 | 1x |
return("tau:-") |
597 |
} |
|
598 | 1x |
if (.f_args$method == "spearman") { |
599 | 1x |
return("rho:-") |
600 |
} |
|
601 |
} |
|
602 | ! |
return("-") |
603 |
} |
|
604 |
} |
1 |
#' `teal` module: Distribution analysis |
|
2 |
#' |
|
3 |
#' Module is designed to explore the distribution of a single variable within a given dataset. |
|
4 |
#' It offers several tools, such as histograms, Q-Q plots, and various statistical tests to |
|
5 |
#' visually and statistically analyze the variable's distribution. |
|
6 |
#' |
|
7 |
#' @inheritParams teal::module |
|
8 |
#' @inheritParams teal.widgets::standard_layout |
|
9 |
#' @inheritParams shared_params |
|
10 |
#' |
|
11 |
#' @param dist_var (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
12 |
#' Variable(s) for which the distribution will be analyzed. |
|
13 |
#' @param strata_var (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
14 |
#' Categorical variable used to split the distribution analysis. |
|
15 |
#' @param group_var (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
16 |
#' Variable used for faceting plot into multiple panels. |
|
17 |
#' @param freq (`logical`) optional, whether to display frequency (`TRUE`) or density (`FALSE`). |
|
18 |
#' Defaults to density (`FALSE`). |
|
19 |
#' @param bins (`integer(1)` or `integer(3)`) optional, specifies the number of bins for the histogram. |
|
20 |
#' - When the length of `bins` is one: The histogram bins will have a fixed size based on the `bins` provided. |
|
21 |
#' - When the length of `bins` is three: The histogram bins are dynamically adjusted based on vector of `value`, `min`, |
|
22 |
#' and `max`. |
|
23 |
#' Defaults to `c(30L, 1L, 100L)`. |
|
24 |
#' |
|
25 |
#' @param ggplot2_args `r roxygen_ggplot2_args_param("Histogram", "QQplot")` |
|
26 |
#' |
|
27 |
#' @inherit shared_params return |
|
28 |
#' |
|
29 |
#' @section Decorating Module: |
|
30 |
#' |
|
31 |
#' This module generates the following objects, which can be modified in place using decorators:: |
|
32 |
#' - `histogram_plot` (`ggplot2`) |
|
33 |
#' - `qq_plot` (`ggplot2`) |
|
34 |
#' - `summary_table` (`listing_df` created with [rlistings::as_listing()]) |
|
35 |
#' - `test_table` (`listing_df` created with [rlistings::as_listing()]) |
|
36 |
#' |
|
37 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
38 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
39 |
#' See code snippet below: |
|
40 |
#' |
|
41 |
#' ``` |
|
42 |
#' tm_g_distribution( |
|
43 |
#' ..., # arguments for module |
|
44 |
#' decorators = list( |
|
45 |
#' histogram_plot = teal_transform_module(...), # applied only to `histogram_plot` output |
|
46 |
#' qq_plot = teal_transform_module(...), # applied only to `qq_plot` output |
|
47 |
#' summary_table = teal_transform_module(...), # applied only to `summary_table` output |
|
48 |
#' test_table = teal_transform_module(...) # applied only to `test_table` output |
|
49 |
#' ) |
|
50 |
#' ) |
|
51 |
#' ``` |
|
52 |
#' |
|
53 |
#' For additional details and examples of decorators, refer to the vignette |
|
54 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
55 |
#' |
|
56 |
#' @examplesShinylive |
|
57 |
#' library(teal.modules.general) |
|
58 |
#' interactive <- function() TRUE |
|
59 |
#' {{ next_example }} |
|
60 |
# nolint start: line_length_linter. |
|
61 |
#' @examples |
|
62 |
# nolint end: line_length_linter. |
|
63 |
#' # general data example |
|
64 |
#' data <- teal_data() |
|
65 |
#' data <- within(data, { |
|
66 |
#' iris <- iris |
|
67 |
#' }) |
|
68 |
#' |
|
69 |
#' app <- init( |
|
70 |
#' data = data, |
|
71 |
#' modules = list( |
|
72 |
#' tm_g_distribution( |
|
73 |
#' dist_var = data_extract_spec( |
|
74 |
#' dataname = "iris", |
|
75 |
#' select = select_spec(variable_choices("iris"), "Petal.Length") |
|
76 |
#' ) |
|
77 |
#' ) |
|
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 |
# nolint start: line_length_linter. |
|
89 |
#' @examples |
|
90 |
# nolint end: line_length_linter. |
|
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 |
#' vars1 <- choices_selected( |
|
99 |
#' variable_choices(data[["ADSL"]], c("ARM", "COUNTRY", "SEX")), |
|
100 |
#' selected = NULL |
|
101 |
#' ) |
|
102 |
#' |
|
103 |
#' app <- init( |
|
104 |
#' data = data, |
|
105 |
#' modules = modules( |
|
106 |
#' tm_g_distribution( |
|
107 |
#' dist_var = data_extract_spec( |
|
108 |
#' dataname = "ADSL", |
|
109 |
#' select = select_spec( |
|
110 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1")), |
|
111 |
#' selected = "BMRKR1", |
|
112 |
#' multiple = FALSE, |
|
113 |
#' fixed = FALSE |
|
114 |
#' ) |
|
115 |
#' ), |
|
116 |
#' strata_var = data_extract_spec( |
|
117 |
#' dataname = "ADSL", |
|
118 |
#' filter = filter_spec( |
|
119 |
#' vars = vars1, |
|
120 |
#' multiple = TRUE |
|
121 |
#' ) |
|
122 |
#' ), |
|
123 |
#' group_var = data_extract_spec( |
|
124 |
#' dataname = "ADSL", |
|
125 |
#' filter = filter_spec( |
|
126 |
#' vars = vars1, |
|
127 |
#' multiple = TRUE |
|
128 |
#' ) |
|
129 |
#' ) |
|
130 |
#' ) |
|
131 |
#' ) |
|
132 |
#' ) |
|
133 |
#' if (interactive()) { |
|
134 |
#' shinyApp(app$ui, app$server) |
|
135 |
#' } |
|
136 |
#' |
|
137 |
#' @export |
|
138 |
#' |
|
139 |
tm_g_distribution <- function(label = "Distribution Module", |
|
140 |
dist_var, |
|
141 |
strata_var = NULL, |
|
142 |
group_var = NULL, |
|
143 |
freq = FALSE, |
|
144 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
145 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
146 |
bins = c(30L, 1L, 100L), |
|
147 |
plot_height = c(600, 200, 2000), |
|
148 |
plot_width = NULL, |
|
149 |
pre_output = NULL, |
|
150 |
post_output = NULL, |
|
151 |
transformators = list(), |
|
152 |
decorators = list()) { |
|
153 | ! |
message("Initializing tm_g_distribution") |
154 | ||
155 |
# Normalize the parameters |
|
156 | ! |
if (inherits(dist_var, "data_extract_spec")) dist_var <- list(dist_var) |
157 | ! |
if (inherits(strata_var, "data_extract_spec")) strata_var <- list(strata_var) |
158 | ! |
if (inherits(group_var, "data_extract_spec")) group_var <- list(group_var) |
159 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
160 | ||
161 |
# Start of assertions |
|
162 | ! |
checkmate::assert_string(label) |
163 | ||
164 | ! |
checkmate::assert_list(dist_var, "data_extract_spec") |
165 | ! |
checkmate::assert_false(dist_var[[1L]]$select$multiple) |
166 | ||
167 | ! |
checkmate::assert_list(strata_var, types = "data_extract_spec", null.ok = TRUE) |
168 | ! |
checkmate::assert_list(group_var, types = "data_extract_spec", null.ok = TRUE) |
169 | ! |
checkmate::assert_flag(freq) |
170 | ! |
ggtheme <- match.arg(ggtheme) |
171 | ||
172 | ! |
plot_choices <- c("Histogram", "QQplot") |
173 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
174 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
175 | ||
176 | ! |
if (length(bins) == 1) { |
177 | ! |
checkmate::assert_numeric(bins, any.missing = FALSE, lower = 1) |
178 |
} else { |
|
179 | ! |
checkmate::assert_numeric(bins, len = 3, any.missing = FALSE, lower = 1) |
180 | ! |
checkmate::assert_numeric(bins[1], lower = bins[2], upper = bins[3], .var.name = "bins") |
181 |
} |
|
182 | ||
183 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
184 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
185 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
186 | ! |
checkmate::assert_numeric( |
187 | ! |
plot_width[1], |
188 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
189 |
) |
|
190 | ||
191 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
192 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
193 | ||
194 | ! |
available_decorators <- c("histogram_plot", "qq_plot", "test_table", "summary_table") |
195 | ! |
assert_decorators(decorators, names = available_decorators) |
196 | ||
197 |
# End of assertions |
|
198 | ||
199 |
# Make UI args |
|
200 | ! |
args <- as.list(environment()) |
201 | ||
202 | ! |
data_extract_list <- list( |
203 | ! |
dist_var = dist_var, |
204 | ! |
strata_var = strata_var, |
205 | ! |
group_var = group_var |
206 |
) |
|
207 | ||
208 | ! |
ans <- module( |
209 | ! |
label = label, |
210 | ! |
server = srv_distribution, |
211 | ! |
server_args = c( |
212 | ! |
data_extract_list, |
213 | ! |
list( |
214 | ! |
plot_height = plot_height, |
215 | ! |
plot_width = plot_width, |
216 | ! |
ggplot2_args = ggplot2_args, |
217 | ! |
decorators = decorators |
218 |
) |
|
219 |
), |
|
220 | ! |
ui = ui_distribution, |
221 | ! |
ui_args = args, |
222 | ! |
transformators = transformators, |
223 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
224 |
) |
|
225 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
226 | ! |
ans |
227 |
} |
|
228 | ||
229 |
# UI function for the distribution module |
|
230 |
ui_distribution <- function(id, ...) { |
|
231 | ! |
args <- list(...) |
232 | ! |
ns <- NS(id) |
233 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$dist_var, args$strata_var, args$group_var) |
234 | ||
235 | ! |
teal.widgets::standard_layout( |
236 | ! |
output = teal.widgets::white_small_well( |
237 | ! |
tabsetPanel( |
238 | ! |
id = ns("tabs"), |
239 | ! |
tabPanel("Histogram", teal.widgets::plot_with_settings_ui(id = ns("hist_plot"))), |
240 | ! |
tabPanel("QQplot", teal.widgets::plot_with_settings_ui(id = ns("qq_plot"))) |
241 |
), |
|
242 | ! |
tags$h3("Statistics Table"), |
243 | ! |
DT::dataTableOutput(ns("summary_table")), |
244 | ! |
tags$h3("Tests"), |
245 | ! |
conditionalPanel( |
246 | ! |
sprintf("input['%s'].length === 0", ns("dist_tests")), |
247 | ! |
div( |
248 | ! |
id = ns("please_select_a_test"), |
249 | ! |
"Please select a test" |
250 |
) |
|
251 |
), |
|
252 | ! |
conditionalPanel( |
253 | ! |
sprintf("input['%s'].length > 0", ns("dist_tests")), |
254 | ! |
DT::dataTableOutput(ns("t_stats")) |
255 |
) |
|
256 |
), |
|
257 | ! |
encoding = tags$div( |
258 |
### Reporter |
|
259 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
260 |
### |
|
261 | ! |
tags$label("Encodings", class = "text-primary"), |
262 | ! |
teal.transform::datanames_input(args[c("dist_var", "strata_var")]), |
263 | ! |
teal.transform::data_extract_ui( |
264 | ! |
id = ns("dist_i"), |
265 | ! |
label = "Variable", |
266 | ! |
data_extract_spec = args$dist_var, |
267 | ! |
is_single_dataset = is_single_dataset_value |
268 |
), |
|
269 | ! |
if (!is.null(args$group_var)) { |
270 | ! |
tagList( |
271 | ! |
teal.transform::data_extract_ui( |
272 | ! |
id = ns("group_i"), |
273 | ! |
label = "Group by", |
274 | ! |
data_extract_spec = args$group_var, |
275 | ! |
is_single_dataset = is_single_dataset_value |
276 |
), |
|
277 | ! |
uiOutput(ns("scales_types_ui")) |
278 |
) |
|
279 |
}, |
|
280 | ! |
if (!is.null(args$strata_var)) { |
281 | ! |
teal.transform::data_extract_ui( |
282 | ! |
id = ns("strata_i"), |
283 | ! |
label = "Stratify by", |
284 | ! |
data_extract_spec = args$strata_var, |
285 | ! |
is_single_dataset = is_single_dataset_value |
286 |
) |
|
287 |
}, |
|
288 | ! |
teal.widgets::panel_group( |
289 | ! |
conditionalPanel( |
290 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'Histogram'"), |
291 | ! |
teal.widgets::panel_item( |
292 | ! |
"Histogram", |
293 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("bins"), "Bins", args$bins, ticks = FALSE, step = 1), |
294 | ! |
shinyWidgets::prettyRadioButtons( |
295 | ! |
ns("main_type"), |
296 | ! |
label = "Plot Type:", |
297 | ! |
choices = c("Density", "Frequency"), |
298 | ! |
selected = if (!args$freq) "Density" else "Frequency", |
299 | ! |
bigger = FALSE, |
300 | ! |
inline = TRUE |
301 |
), |
|
302 | ! |
checkboxInput(ns("add_dens"), label = "Overlay Density", value = TRUE), |
303 | ! |
ui_decorate_teal_data( |
304 | ! |
ns("d_density"), |
305 | ! |
decorators = select_decorators(args$decorators, "histogram_plot") |
306 |
), |
|
307 | ! |
collapsed = FALSE |
308 |
) |
|
309 |
), |
|
310 | ! |
conditionalPanel( |
311 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'QQplot'"), |
312 | ! |
teal.widgets::panel_item( |
313 | ! |
"QQ Plot", |
314 | ! |
checkboxInput(ns("qq_line"), label = "Add diagonal line(s)", TRUE), |
315 | ! |
ui_decorate_teal_data( |
316 | ! |
ns("d_qq"), |
317 | ! |
decorators = select_decorators(args$decorators, "qq_plot") |
318 |
), |
|
319 | ! |
collapsed = FALSE |
320 |
) |
|
321 |
), |
|
322 | ! |
ui_decorate_teal_data( |
323 | ! |
ns("d_summary"), |
324 | ! |
decorators = select_decorators(args$decorators, "summary_table") |
325 |
), |
|
326 | ! |
ui_decorate_teal_data( |
327 | ! |
ns("d_test"), |
328 | ! |
decorators = select_decorators(args$decorators, "test_table") |
329 |
), |
|
330 | ! |
conditionalPanel( |
331 | ! |
condition = paste0("input['", ns("main_type"), "'] == 'Density'"), |
332 | ! |
teal.widgets::panel_item( |
333 | ! |
"Theoretical Distribution", |
334 | ! |
teal.widgets::optionalSelectInput( |
335 | ! |
ns("t_dist"), |
336 | ! |
tags$div( |
337 | ! |
class = "teal-tooltip", |
338 | ! |
tagList( |
339 | ! |
"Distribution:", |
340 | ! |
icon("circle-info"), |
341 | ! |
tags$span( |
342 | ! |
class = "tooltiptext", |
343 | ! |
"Default parameters are optimized with MASS::fitdistr function." |
344 |
) |
|
345 |
) |
|
346 |
), |
|
347 | ! |
choices = c("normal", "lognormal", "gamma", "unif"), |
348 | ! |
selected = NULL, |
349 | ! |
multiple = FALSE |
350 |
), |
|
351 | ! |
numericInput(ns("dist_param1"), label = "param1", value = NULL), |
352 | ! |
numericInput(ns("dist_param2"), label = "param2", value = NULL), |
353 | ! |
tags$span(actionButton(ns("params_reset"), "Default params")), |
354 | ! |
collapsed = FALSE |
355 |
) |
|
356 |
) |
|
357 |
), |
|
358 | ! |
teal.widgets::panel_item( |
359 | ! |
"Tests", |
360 | ! |
teal.widgets::optionalSelectInput( |
361 | ! |
ns("dist_tests"), |
362 | ! |
"Tests:", |
363 | ! |
choices = c( |
364 | ! |
"Shapiro-Wilk", |
365 | ! |
if (!is.null(args$strata_var)) "t-test (two-samples, not paired)", |
366 | ! |
if (!is.null(args$strata_var)) "one-way ANOVA", |
367 | ! |
if (!is.null(args$strata_var)) "Fligner-Killeen", |
368 | ! |
if (!is.null(args$strata_var)) "F-test", |
369 | ! |
"Kolmogorov-Smirnov (one-sample)", |
370 | ! |
"Anderson-Darling (one-sample)", |
371 | ! |
"Cramer-von Mises (one-sample)", |
372 | ! |
if (!is.null(args$strata_var)) "Kolmogorov-Smirnov (two-samples)" |
373 |
), |
|
374 | ! |
selected = NULL |
375 |
) |
|
376 |
), |
|
377 | ! |
teal.widgets::panel_item( |
378 | ! |
"Statistics Table", |
379 | ! |
sliderInput(ns("roundn"), "Round to n digits", min = 0, max = 10, value = 2) |
380 |
), |
|
381 | ! |
teal.widgets::panel_item( |
382 | ! |
title = "Plot settings", |
383 | ! |
selectInput( |
384 | ! |
inputId = ns("ggtheme"), |
385 | ! |
label = "Theme (by ggplot):", |
386 | ! |
choices = ggplot_themes, |
387 | ! |
selected = args$ggtheme, |
388 | ! |
multiple = FALSE |
389 |
) |
|
390 |
) |
|
391 |
), |
|
392 | ! |
forms = tagList( |
393 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
394 |
), |
|
395 | ! |
pre_output = args$pre_output, |
396 | ! |
post_output = args$post_output |
397 |
) |
|
398 |
} |
|
399 | ||
400 |
# Server function for the distribution module |
|
401 |
srv_distribution <- function(id, |
|
402 |
data, |
|
403 |
reporter, |
|
404 |
filter_panel_api, |
|
405 |
dist_var, |
|
406 |
strata_var, |
|
407 |
group_var, |
|
408 |
plot_height, |
|
409 |
plot_width, |
|
410 |
ggplot2_args, |
|
411 |
decorators) { |
|
412 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
413 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
414 | ! |
checkmate::assert_class(data, "reactive") |
415 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
416 | ! |
moduleServer(id, function(input, output, session) { |
417 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
418 | ||
419 | ! |
setBookmarkExclude("params_reset") |
420 | ||
421 | ! |
ns <- session$ns |
422 | ||
423 | ! |
rule_req <- function(value) { |
424 | ! |
if (isTRUE(input$dist_tests %in% c( |
425 | ! |
"Fligner-Killeen", |
426 | ! |
"t-test (two-samples, not paired)", |
427 | ! |
"F-test", |
428 | ! |
"Kolmogorov-Smirnov (two-samples)", |
429 | ! |
"one-way ANOVA" |
430 |
))) { |
|
431 | ! |
if (!shinyvalidate::input_provided(value)) { |
432 | ! |
"Please select stratify variable." |
433 |
} |
|
434 |
} |
|
435 |
} |
|
436 | ! |
rule_dupl <- function(...) { |
437 | ! |
if (identical(input$dist_tests, "Fligner-Killeen")) { |
438 | ! |
strata <- selector_list()$strata_i()$select |
439 | ! |
group <- selector_list()$group_i()$select |
440 | ! |
if (isTRUE(strata == group)) { |
441 | ! |
"Please select different variables for strata and group." |
442 |
} |
|
443 |
} |
|
444 |
} |
|
445 | ||
446 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
447 | ! |
data_extract = list( |
448 | ! |
dist_i = dist_var, |
449 | ! |
strata_i = strata_var, |
450 | ! |
group_i = group_var |
451 |
), |
|
452 | ! |
data, |
453 | ! |
select_validation_rule = list( |
454 | ! |
dist_i = shinyvalidate::sv_required("Please select a variable") |
455 |
), |
|
456 | ! |
filter_validation_rule = list( |
457 | ! |
strata_i = shinyvalidate::compose_rules( |
458 | ! |
rule_req, |
459 | ! |
rule_dupl |
460 |
), |
|
461 | ! |
group_i = rule_dupl |
462 |
) |
|
463 |
) |
|
464 | ||
465 | ! |
iv_r <- reactive({ |
466 | ! |
iv <- shinyvalidate::InputValidator$new() |
467 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list, validator_names = "dist_i") |
468 |
}) |
|
469 | ||
470 | ! |
iv_r_dist <- reactive({ |
471 | ! |
iv <- shinyvalidate::InputValidator$new() |
472 | ! |
teal.transform::compose_and_enable_validators( |
473 | ! |
iv, selector_list, |
474 | ! |
validator_names = c("strata_i", "group_i") |
475 |
) |
|
476 |
}) |
|
477 | ! |
rule_dist_1 <- function(value) { |
478 | ! |
if (!is.null(input$t_dist)) { |
479 | ! |
switch(input$t_dist, |
480 | ! |
"normal" = if (!shinyvalidate::input_provided(value)) "mean is required", |
481 | ! |
"lognormal" = if (!shinyvalidate::input_provided(value)) "meanlog is required", |
482 | ! |
"gamma" = { |
483 | ! |
if (!shinyvalidate::input_provided(value)) "shape is required" else if (value <= 0) "shape must be positive" |
484 |
}, |
|
485 | ! |
"unif" = NULL |
486 |
) |
|
487 |
} |
|
488 |
} |
|
489 | ! |
rule_dist_2 <- function(value) { |
490 | ! |
if (!is.null(input$t_dist)) { |
491 | ! |
switch(input$t_dist, |
492 | ! |
"normal" = { |
493 | ! |
if (!shinyvalidate::input_provided(value)) { |
494 | ! |
"sd is required" |
495 | ! |
} else if (value < 0) { |
496 | ! |
"sd must be non-negative" |
497 |
} |
|
498 |
}, |
|
499 | ! |
"lognormal" = { |
500 | ! |
if (!shinyvalidate::input_provided(value)) { |
501 | ! |
"sdlog is required" |
502 | ! |
} else if (value < 0) { |
503 | ! |
"sdlog must be non-negative" |
504 |
} |
|
505 |
}, |
|
506 | ! |
"gamma" = { |
507 | ! |
if (!shinyvalidate::input_provided(value)) { |
508 | ! |
"rate is required" |
509 | ! |
} else if (value <= 0) { |
510 | ! |
"rate must be positive" |
511 |
} |
|
512 |
}, |
|
513 | ! |
"unif" = NULL |
514 |
) |
|
515 |
} |
|
516 |
} |
|
517 | ||
518 | ! |
rule_dist <- function(value) { |
519 | ! |
if (isTRUE(input$tabs == "QQplot") || |
520 | ! |
isTRUE(input$dist_tests %in% c( |
521 | ! |
"Kolmogorov-Smirnov (one-sample)", |
522 | ! |
"Anderson-Darling (one-sample)", |
523 | ! |
"Cramer-von Mises (one-sample)" |
524 |
))) { |
|
525 | ! |
if (!shinyvalidate::input_provided(value)) { |
526 | ! |
"Please select the theoretical distribution." |
527 |
} |
|
528 |
} |
|
529 |
} |
|
530 | ||
531 | ! |
iv_dist <- shinyvalidate::InputValidator$new() |
532 | ! |
iv_dist$add_rule("t_dist", rule_dist) |
533 | ! |
iv_dist$add_rule("dist_param1", rule_dist_1) |
534 | ! |
iv_dist$add_rule("dist_param2", rule_dist_2) |
535 | ! |
iv_dist$enable() |
536 | ||
537 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
538 | ! |
selector_list = selector_list, |
539 | ! |
datasets = data |
540 |
) |
|
541 | ||
542 | ! |
anl_merged_q <- reactive({ |
543 | ! |
req(anl_merged_input()) |
544 | ! |
data() %>% |
545 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
546 |
}) |
|
547 | ||
548 | ! |
merged <- list( |
549 | ! |
anl_input_r = anl_merged_input, |
550 | ! |
anl_q_r = anl_merged_q |
551 |
) |
|
552 | ||
553 | ! |
output$scales_types_ui <- renderUI({ |
554 | ! |
if ("group_i" %in% names(selector_list()) && length(selector_list()$group_i()$filters[[1]]$selected) > 0) { |
555 | ! |
shinyWidgets::prettyRadioButtons( |
556 | ! |
ns("scales_type"), |
557 | ! |
label = "Scales:", |
558 | ! |
choices = c("Fixed", "Free"), |
559 | ! |
selected = "Fixed", |
560 | ! |
bigger = FALSE, |
561 | ! |
inline = TRUE |
562 |
) |
|
563 |
} |
|
564 |
}) |
|
565 | ||
566 | ! |
observeEvent( |
567 | ! |
eventExpr = list( |
568 | ! |
input$t_dist, |
569 | ! |
input$params_reset, |
570 | ! |
selector_list()$dist_i()$select |
571 |
), |
|
572 | ! |
handlerExpr = { |
573 | ! |
params <- |
574 | ! |
if (length(input$t_dist) != 0) { |
575 | ! |
get_dist_params <- function(x, dist) { |
576 | ! |
if (dist == "unif") { |
577 | ! |
return(stats::setNames(range(x, na.rm = TRUE), c("min", "max"))) |
578 |
} |
|
579 | ! |
tryCatch( |
580 | ! |
MASS::fitdistr(x, densfun = dist)$estimate, |
581 | ! |
error = function(e) c(param1 = NA_real_, param2 = NA_real_) |
582 |
) |
|
583 |
} |
|
584 | ||
585 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
586 | ! |
round(get_dist_params(as.numeric(stats::na.omit(ANL[[merge_vars()$dist_var]])), input$t_dist), 2) |
587 |
} else { |
|
588 | ! |
c("param1" = NA_real_, "param2" = NA_real_) |
589 |
} |
|
590 | ||
591 | ! |
params_vals <- unname(params) |
592 | ! |
params_names <- names(params) |
593 | ||
594 | ! |
updateNumericInput( |
595 | ! |
inputId = "dist_param1", |
596 | ! |
label = params_names[1], |
597 | ! |
value = restoreInput(ns("dist_param1"), params_vals[1]) |
598 |
) |
|
599 | ! |
updateNumericInput( |
600 | ! |
inputId = "dist_param2", |
601 | ! |
label = params_names[2], |
602 | ! |
value = restoreInput(ns("dist_param1"), params_vals[2]) |
603 |
) |
|
604 |
}, |
|
605 | ! |
ignoreInit = TRUE |
606 |
) |
|
607 | ||
608 | ! |
observeEvent(input$params_reset, { |
609 | ! |
updateActionButton(inputId = "params_reset", label = "Reset params") |
610 |
}) |
|
611 | ||
612 | ! |
merge_vars <- reactive({ |
613 | ! |
teal::validate_inputs(iv_r()) |
614 | ||
615 | ! |
dist_var <- as.vector(merged$anl_input_r()$columns_source$dist_i) |
616 | ! |
s_var <- as.vector(merged$anl_input_r()$columns_source$strata_i) |
617 | ! |
g_var <- as.vector(merged$anl_input_r()$columns_source$group_i) |
618 | ||
619 | ! |
dist_var_name <- if (length(dist_var)) as.name(dist_var) else NULL |
620 | ! |
s_var_name <- if (length(s_var)) as.name(s_var) else NULL |
621 | ! |
g_var_name <- if (length(g_var)) as.name(g_var) else NULL |
622 | ||
623 | ! |
list( |
624 | ! |
dist_var = dist_var, |
625 | ! |
s_var = s_var, |
626 | ! |
g_var = g_var, |
627 | ! |
dist_var_name = dist_var_name, |
628 | ! |
s_var_name = s_var_name, |
629 | ! |
g_var_name = g_var_name |
630 |
) |
|
631 |
}) |
|
632 | ||
633 |
# common qenv |
|
634 | ! |
common_q <- reactive({ |
635 |
# Create a private stack for this function only. |
|
636 | ||
637 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
638 | ! |
dist_var <- merge_vars()$dist_var |
639 | ! |
s_var <- merge_vars()$s_var |
640 | ! |
g_var <- merge_vars()$g_var |
641 | ||
642 | ! |
dist_var_name <- merge_vars()$dist_var_name |
643 | ! |
s_var_name <- merge_vars()$s_var_name |
644 | ! |
g_var_name <- merge_vars()$g_var_name |
645 | ||
646 | ! |
roundn <- input$roundn |
647 | ! |
dist_param1 <- input$dist_param1 |
648 | ! |
dist_param2 <- input$dist_param2 |
649 |
# isolated as dist_param1/dist_param2 already triggered the reactivity |
|
650 | ! |
t_dist <- isolate(input$t_dist) |
651 | ||
652 | ! |
qenv <- merged$anl_q_r() |
653 | ||
654 | ! |
if (length(g_var) > 0) { |
655 | ! |
validate( |
656 | ! |
need( |
657 | ! |
inherits(ANL[[g_var]], c("integer", "factor", "character")), |
658 | ! |
"Group by variable must be `factor`, `character`, or `integer`" |
659 |
) |
|
660 |
) |
|
661 | ! |
qenv <- teal.code::eval_code( |
662 | ! |
qenv, |
663 | ! |
substitute( |
664 | ! |
expr = ANL[[g_var]] <- forcats::fct_na_value_to_level(as.factor(ANL[[g_var]]), "NA"), |
665 | ! |
env = list(g_var = g_var) |
666 |
) |
|
667 |
) |
|
668 |
} |
|
669 | ||
670 | ! |
if (length(s_var) > 0) { |
671 | ! |
validate( |
672 | ! |
need( |
673 | ! |
inherits(ANL[[s_var]], c("integer", "factor", "character")), |
674 | ! |
"Stratify by variable must be `factor`, `character`, or `integer`" |
675 |
) |
|
676 |
) |
|
677 | ! |
qenv <- teal.code::eval_code( |
678 | ! |
qenv, |
679 | ! |
substitute( |
680 | ! |
expr = ANL[[s_var]] <- forcats::fct_na_value_to_level(as.factor(ANL[[s_var]]), "NA"), |
681 | ! |
env = list(s_var = s_var) |
682 |
) |
|
683 |
) |
|
684 |
} |
|
685 | ||
686 | ! |
validate(need(is.numeric(ANL[[dist_var]]), "Please select a numeric variable.")) |
687 | ! |
teal::validate_has_data(ANL, 1, complete = TRUE) |
688 | ||
689 | ! |
if (length(t_dist) != 0) { |
690 | ! |
map_distr_nams <- list( |
691 | ! |
normal = c("mean", "sd"), |
692 | ! |
lognormal = c("meanlog", "sdlog"), |
693 | ! |
gamma = c("shape", "rate"), |
694 | ! |
unif = c("min", "max") |
695 |
) |
|
696 | ! |
params_names_raw <- map_distr_nams[[t_dist]] |
697 | ||
698 | ! |
qenv <- teal.code::eval_code( |
699 | ! |
qenv, |
700 | ! |
substitute( |
701 | ! |
expr = { |
702 | ! |
params <- as.list(c(dist_param1, dist_param2)) |
703 | ! |
names(params) <- params_names_raw |
704 |
}, |
|
705 | ! |
env = list( |
706 | ! |
dist_param1 = dist_param1, |
707 | ! |
dist_param2 = dist_param2, |
708 | ! |
params_names_raw = params_names_raw |
709 |
) |
|
710 |
) |
|
711 |
) |
|
712 |
} |
|
713 | ||
714 | ! |
if (length(s_var) == 0 && length(g_var) == 0) { |
715 | ! |
teal.code::eval_code( |
716 | ! |
qenv, |
717 | ! |
substitute( |
718 | ! |
expr = { |
719 | ! |
summary_table_data <- ANL %>% |
720 | ! |
dplyr::summarise( |
721 | ! |
min = round(min(dist_var_name, na.rm = TRUE), roundn), |
722 | ! |
median = round(stats::median(dist_var_name, na.rm = TRUE), roundn), |
723 | ! |
mean = round(mean(dist_var_name, na.rm = TRUE), roundn), |
724 | ! |
max = round(max(dist_var_name, na.rm = TRUE), roundn), |
725 | ! |
sd = round(stats::sd(dist_var_name, na.rm = TRUE), roundn), |
726 | ! |
count = dplyr::n() |
727 |
) |
|
728 |
}, |
|
729 | ! |
env = list( |
730 | ! |
dist_var_name = as.name(dist_var), |
731 | ! |
roundn = roundn |
732 |
) |
|
733 |
) |
|
734 |
) |
|
735 |
} else { |
|
736 | ! |
teal.code::eval_code( |
737 | ! |
qenv, |
738 | ! |
substitute( |
739 | ! |
expr = { |
740 | ! |
strata_vars <- strata_vars_raw |
741 | ! |
summary_table_data <- ANL %>% |
742 | ! |
dplyr::group_by_at(dplyr::vars(dplyr::any_of(strata_vars))) %>% |
743 | ! |
dplyr::summarise( |
744 | ! |
min = round(min(dist_var_name, na.rm = TRUE), roundn), |
745 | ! |
median = round(stats::median(dist_var_name, na.rm = TRUE), roundn), |
746 | ! |
mean = round(mean(dist_var_name, na.rm = TRUE), roundn), |
747 | ! |
max = round(max(dist_var_name, na.rm = TRUE), roundn), |
748 | ! |
sd = round(stats::sd(dist_var_name, na.rm = TRUE), roundn), |
749 | ! |
count = dplyr::n() |
750 |
) |
|
751 |
}, |
|
752 | ! |
env = list( |
753 | ! |
dist_var_name = dist_var_name, |
754 | ! |
strata_vars_raw = c(g_var, s_var), |
755 | ! |
roundn = roundn |
756 |
) |
|
757 |
) |
|
758 |
) |
|
759 |
} |
|
760 |
}) |
|
761 | ||
762 |
# distplot qenv ---- |
|
763 | ! |
dist_q <- eventReactive( |
764 | ! |
eventExpr = { |
765 | ! |
common_q() |
766 | ! |
input$scales_type |
767 | ! |
input$main_type |
768 | ! |
input$bins |
769 | ! |
input$add_dens |
770 | ! |
is.null(input$ggtheme) |
771 |
}, |
|
772 | ! |
valueExpr = { |
773 | ! |
dist_var <- merge_vars()$dist_var |
774 | ! |
s_var <- merge_vars()$s_var |
775 | ! |
g_var <- merge_vars()$g_var |
776 | ! |
dist_var_name <- merge_vars()$dist_var_name |
777 | ! |
s_var_name <- merge_vars()$s_var_name |
778 | ! |
g_var_name <- merge_vars()$g_var_name |
779 | ! |
t_dist <- input$t_dist |
780 | ! |
dist_param1 <- input$dist_param1 |
781 | ! |
dist_param2 <- input$dist_param2 |
782 | ||
783 | ! |
scales_type <- input$scales_type |
784 | ||
785 | ! |
ndensity <- 512 |
786 | ! |
main_type_var <- input$main_type |
787 | ! |
bins_var <- input$bins |
788 | ! |
add_dens_var <- input$add_dens |
789 | ! |
ggtheme <- input$ggtheme |
790 | ||
791 | ! |
teal::validate_inputs(iv_dist) |
792 | ||
793 | ! |
qenv <- common_q() |
794 | ||
795 | ! |
m_type <- if (main_type_var == "Density") "density" else "count" |
796 | ||
797 | ! |
plot_call <- if (length(s_var) == 0 && length(g_var) == 0) { |
798 | ! |
substitute( |
799 | ! |
expr = ggplot(ANL, aes(dist_var_name)) + |
800 | ! |
geom_histogram( |
801 | ! |
position = "identity", aes(y = after_stat(m_type)), bins = bins_var, alpha = 0.3 |
802 |
), |
|
803 | ! |
env = list( |
804 | ! |
m_type = as.name(m_type), bins_var = bins_var, dist_var_name = as.name(dist_var) |
805 |
) |
|
806 |
) |
|
807 | ! |
} else if (length(s_var) != 0 && length(g_var) == 0) { |
808 | ! |
substitute( |
809 | ! |
expr = ggplot(ANL, aes(dist_var_name, col = s_var_name)) + |
810 | ! |
geom_histogram( |
811 | ! |
position = "identity", aes(y = after_stat(m_type), fill = s_var), bins = bins_var, alpha = 0.3 |
812 |
), |
|
813 | ! |
env = list( |
814 | ! |
m_type = as.name(m_type), |
815 | ! |
bins_var = bins_var, |
816 | ! |
dist_var_name = dist_var_name, |
817 | ! |
s_var = as.name(s_var), |
818 | ! |
s_var_name = s_var_name |
819 |
) |
|
820 |
) |
|
821 | ! |
} else if (length(s_var) == 0 && length(g_var) != 0) { |
822 | ! |
req(scales_type) |
823 | ! |
substitute( |
824 | ! |
expr = ggplot(ANL[ANL[[g_var]] != "NA", ], aes(dist_var_name)) + |
825 | ! |
geom_histogram( |
826 | ! |
position = "identity", aes(y = after_stat(m_type)), bins = bins_var, alpha = 0.3 |
827 |
) + |
|
828 | ! |
facet_wrap(~g_var_name, ncol = 1, scales = scales_raw), |
829 | ! |
env = list( |
830 | ! |
m_type = as.name(m_type), |
831 | ! |
bins_var = bins_var, |
832 | ! |
dist_var_name = dist_var_name, |
833 | ! |
g_var = g_var, |
834 | ! |
g_var_name = g_var_name, |
835 | ! |
scales_raw = tolower(scales_type) |
836 |
) |
|
837 |
) |
|
838 |
} else { |
|
839 | ! |
req(scales_type) |
840 | ! |
substitute( |
841 | ! |
expr = ggplot(ANL[ANL[[g_var]] != "NA", ], aes(dist_var_name, col = s_var_name)) + |
842 | ! |
geom_histogram( |
843 | ! |
position = "identity", |
844 | ! |
aes(y = after_stat(m_type), fill = s_var), bins = bins_var, alpha = 0.3 |
845 |
) + |
|
846 | ! |
facet_wrap(~g_var_name, ncol = 1, scales = scales_raw), |
847 | ! |
env = list( |
848 | ! |
m_type = as.name(m_type), |
849 | ! |
bins_var = bins_var, |
850 | ! |
dist_var_name = dist_var_name, |
851 | ! |
g_var = g_var, |
852 | ! |
s_var = as.name(s_var), |
853 | ! |
g_var_name = g_var_name, |
854 | ! |
s_var_name = s_var_name, |
855 | ! |
scales_raw = tolower(scales_type) |
856 |
) |
|
857 |
) |
|
858 |
} |
|
859 | ||
860 | ! |
if (add_dens_var) { |
861 | ! |
plot_call <- substitute( |
862 | ! |
expr = plot_call + |
863 | ! |
stat_density( |
864 | ! |
aes(y = after_stat(const * m_type2)), |
865 | ! |
geom = "line", |
866 | ! |
position = "identity", |
867 | ! |
alpha = 0.5, |
868 | ! |
size = 2, |
869 | ! |
n = ndensity |
870 |
), |
|
871 | ! |
env = list( |
872 | ! |
plot_call = plot_call, |
873 | ! |
const = if (main_type_var == "Density") { |
874 | ! |
1 |
875 |
} else { |
|
876 | ! |
diff(range(qenv[["ANL"]][[dist_var]], na.rm = TRUE)) / bins_var |
877 |
}, |
|
878 | ! |
m_type2 = if (main_type_var == "Density") as.name("density") else as.name("count"), |
879 | ! |
ndensity = ndensity |
880 |
) |
|
881 |
) |
|
882 |
} |
|
883 | ||
884 | ! |
if (length(t_dist) != 0 && main_type_var == "Density" && length(g_var) == 0 && length(s_var) == 0) { |
885 | ! |
qenv <- teal.code::eval_code( |
886 | ! |
qenv, |
887 | ! |
substitute( |
888 | ! |
df_params <- as.data.frame(append(params, list(name = t_dist))), |
889 | ! |
env = list(t_dist = t_dist) |
890 |
) |
|
891 |
) |
|
892 | ! |
datas <- quote(data.frame(x = 0.7, y = 1, tb = I(list(df_params = df_params)))) |
893 | ! |
label <- quote(tb) |
894 | ||
895 | ! |
plot_call <- substitute( |
896 | ! |
expr = plot_call + ggpp::geom_table_npc( |
897 | ! |
data = data, |
898 | ! |
aes(npcx = x, npcy = y, label = label), |
899 | ! |
hjust = 0, vjust = 1, size = 4 |
900 |
), |
|
901 | ! |
env = list(plot_call = plot_call, data = datas, label = label) |
902 |
) |
|
903 |
} |
|
904 | ||
905 | ! |
if ( |
906 | ! |
length(s_var) == 0 && |
907 | ! |
length(g_var) == 0 && |
908 | ! |
main_type_var == "Density" && |
909 | ! |
length(t_dist) != 0 && |
910 | ! |
main_type_var == "Density" |
911 |
) { |
|
912 | ! |
map_dist <- stats::setNames( |
913 | ! |
c("dnorm", "dlnorm", "dgamma", "dunif"), |
914 | ! |
c("normal", "lognormal", "gamma", "unif") |
915 |
) |
|
916 | ! |
plot_call <- substitute( |
917 | ! |
expr = plot_call + stat_function( |
918 | ! |
data = data.frame(x = range(ANL[[dist_var]]), color = mapped_dist), |
919 | ! |
aes(x, color = color), |
920 | ! |
fun = mapped_dist_name, |
921 | ! |
n = ndensity, |
922 | ! |
size = 2, |
923 | ! |
args = params |
924 |
) + |
|
925 | ! |
scale_color_manual(values = stats::setNames("blue", mapped_dist), aesthetics = "color"), |
926 | ! |
env = list( |
927 | ! |
plot_call = plot_call, |
928 | ! |
dist_var = dist_var, |
929 | ! |
ndensity = ndensity, |
930 | ! |
mapped_dist = unname(map_dist[t_dist]), |
931 | ! |
mapped_dist_name = as.name(unname(map_dist[t_dist])) |
932 |
) |
|
933 |
) |
|
934 |
} |
|
935 | ||
936 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
937 | ! |
user_plot = ggplot2_args[["Histogram"]], |
938 | ! |
user_default = ggplot2_args$default |
939 |
) |
|
940 | ||
941 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
942 | ! |
all_ggplot2_args, |
943 | ! |
ggtheme = ggtheme |
944 |
) |
|
945 | ||
946 | ! |
teal.code::eval_code( |
947 | ! |
qenv, |
948 | ! |
substitute( |
949 | ! |
expr = histogram_plot <- plot_call, |
950 | ! |
env = list(plot_call = Reduce(function(x, y) call("+", x, y), c(plot_call, parsed_ggplot2_args))) |
951 |
) |
|
952 |
) |
|
953 |
} |
|
954 |
) |
|
955 | ||
956 |
# qqplot qenv ---- |
|
957 | ! |
qq_q <- eventReactive( |
958 | ! |
eventExpr = { |
959 | ! |
common_q() |
960 | ! |
input$scales_type |
961 | ! |
input$qq_line |
962 | ! |
is.null(input$ggtheme) |
963 | ! |
input$tabs |
964 |
}, |
|
965 | ! |
valueExpr = { |
966 | ! |
dist_var <- merge_vars()$dist_var |
967 | ! |
s_var <- merge_vars()$s_var |
968 | ! |
g_var <- merge_vars()$g_var |
969 | ! |
dist_var_name <- merge_vars()$dist_var_name |
970 | ! |
s_var_name <- merge_vars()$s_var_name |
971 | ! |
g_var_name <- merge_vars()$g_var_name |
972 | ! |
dist_param1 <- input$dist_param1 |
973 | ! |
dist_param2 <- input$dist_param2 |
974 | ||
975 | ! |
scales_type <- input$scales_type |
976 | ! |
ggtheme <- input$ggtheme |
977 | ||
978 | ! |
teal::validate_inputs(iv_r_dist(), iv_dist) |
979 | ! |
t_dist <- req(input$t_dist) # Not validated when tab is not selected |
980 | ! |
qenv <- common_q() |
981 | ||
982 | ! |
plot_call <- if (length(s_var) == 0 && length(g_var) == 0) { |
983 | ! |
substitute( |
984 | ! |
expr = ggplot(ANL, aes_string(sample = dist_var)), |
985 | ! |
env = list(dist_var = dist_var) |
986 |
) |
|
987 | ! |
} else if (length(s_var) != 0 && length(g_var) == 0) { |
988 | ! |
substitute( |
989 | ! |
expr = ggplot(ANL, aes_string(sample = dist_var, color = s_var)), |
990 | ! |
env = list(dist_var = dist_var, s_var = s_var) |
991 |
) |
|
992 | ! |
} else if (length(s_var) == 0 && length(g_var) != 0) { |
993 | ! |
substitute( |
994 | ! |
expr = ggplot(ANL[ANL[[g_var]] != "NA", ], aes_string(sample = dist_var)) + |
995 | ! |
facet_wrap(~g_var_name, ncol = 1, scales = scales_raw), |
996 | ! |
env = list( |
997 | ! |
dist_var = dist_var, |
998 | ! |
g_var = g_var, |
999 | ! |
g_var_name = g_var_name, |
1000 | ! |
scales_raw = tolower(scales_type) |
1001 |
) |
|
1002 |
) |
|
1003 |
} else { |
|
1004 | ! |
substitute( |
1005 | ! |
expr = ggplot(ANL[ANL[[g_var]] != "NA", ], aes_string(sample = dist_var, color = s_var)) + |
1006 | ! |
facet_wrap(~g_var_name, ncol = 1, scales = scales_raw), |
1007 | ! |
env = list( |
1008 | ! |
dist_var = dist_var, |
1009 | ! |
g_var = g_var, |
1010 | ! |
s_var = s_var, |
1011 | ! |
g_var_name = g_var_name, |
1012 | ! |
scales_raw = tolower(scales_type) |
1013 |
) |
|
1014 |
) |
|
1015 |
} |
|
1016 | ||
1017 | ! |
map_dist <- stats::setNames( |
1018 | ! |
c("qnorm", "qlnorm", "qgamma", "qunif"), |
1019 | ! |
c("normal", "lognormal", "gamma", "unif") |
1020 |
) |
|
1021 | ||
1022 | ! |
plot_call <- substitute( |
1023 | ! |
expr = plot_call + |
1024 | ! |
stat_qq(distribution = mapped_dist, dparams = params), |
1025 | ! |
env = list(plot_call = plot_call, mapped_dist = as.name(unname(map_dist[t_dist]))) |
1026 |
) |
|
1027 | ||
1028 | ! |
if (length(t_dist) != 0 && length(g_var) == 0 && length(s_var) == 0) { |
1029 | ! |
qenv <- teal.code::eval_code( |
1030 | ! |
qenv, |
1031 | ! |
substitute( |
1032 | ! |
df_params <- as.data.frame(append(params, list(name = t_dist))), |
1033 | ! |
env = list(t_dist = t_dist) |
1034 |
) |
|
1035 |
) |
|
1036 | ! |
datas <- quote(data.frame(x = 0.7, y = 1, tb = I(list(df_params = df_params)))) |
1037 | ! |
label <- quote(tb) |
1038 | ||
1039 | ! |
plot_call <- substitute( |
1040 | ! |
expr = plot_call + |
1041 | ! |
ggpp::geom_table_npc( |
1042 | ! |
data = data, |
1043 | ! |
aes(npcx = x, npcy = y, label = label), |
1044 | ! |
hjust = 0, |
1045 | ! |
vjust = 1, |
1046 | ! |
size = 4 |
1047 |
), |
|
1048 | ! |
env = list( |
1049 | ! |
plot_call = plot_call, |
1050 | ! |
data = datas, |
1051 | ! |
label = label |
1052 |
) |
|
1053 |
) |
|
1054 |
} |
|
1055 | ||
1056 | ! |
if (isTRUE(input$qq_line)) { |
1057 | ! |
plot_call <- substitute( |
1058 | ! |
expr = plot_call + |
1059 | ! |
stat_qq_line(distribution = mapped_dist, dparams = params), |
1060 | ! |
env = list(plot_call = plot_call, mapped_dist = as.name(unname(map_dist[t_dist]))) |
1061 |
) |
|
1062 |
} |
|
1063 | ||
1064 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
1065 | ! |
user_plot = ggplot2_args[["QQplot"]], |
1066 | ! |
user_default = ggplot2_args$default, |
1067 | ! |
module_plot = teal.widgets::ggplot2_args(labs = list(x = "theoretical", y = "sample")) |
1068 |
) |
|
1069 | ||
1070 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
1071 | ! |
all_ggplot2_args, |
1072 | ! |
ggtheme = ggtheme |
1073 |
) |
|
1074 | ||
1075 | ! |
teal.code::eval_code( |
1076 | ! |
qenv, |
1077 | ! |
substitute( |
1078 | ! |
expr = qq_plot <- plot_call, |
1079 | ! |
env = list(plot_call = Reduce(function(x, y) call("+", x, y), c(plot_call, parsed_ggplot2_args))) |
1080 |
) |
|
1081 |
) |
|
1082 |
} |
|
1083 |
) |
|
1084 | ||
1085 |
# test qenv ---- |
|
1086 | ! |
test_q <- eventReactive( |
1087 | ! |
ignoreNULL = FALSE, |
1088 | ! |
eventExpr = { |
1089 | ! |
common_q() |
1090 | ! |
input$dist_param1 |
1091 | ! |
input$dist_param2 |
1092 | ! |
input$dist_tests |
1093 |
}, |
|
1094 | ! |
valueExpr = { |
1095 |
# Create a private stack for this function only. |
|
1096 | ! |
ANL <- common_q()[["ANL"]] |
1097 | ||
1098 | ! |
dist_var <- merge_vars()$dist_var |
1099 | ! |
s_var <- merge_vars()$s_var |
1100 | ! |
g_var <- merge_vars()$g_var |
1101 | ||
1102 | ! |
dist_var_name <- merge_vars()$dist_var_name |
1103 | ! |
s_var_name <- merge_vars()$s_var_name |
1104 | ! |
g_var_name <- merge_vars()$g_var_name |
1105 | ||
1106 | ! |
dist_param1 <- input$dist_param1 |
1107 | ! |
dist_param2 <- input$dist_param2 |
1108 | ! |
dist_tests <- input$dist_tests |
1109 | ! |
t_dist <- input$t_dist |
1110 | ||
1111 | ! |
req(dist_tests) |
1112 | ||
1113 | ! |
teal::validate_inputs(iv_dist) |
1114 | ||
1115 | ! |
if (length(s_var) > 0 || length(g_var) > 0) { |
1116 | ! |
counts <- ANL %>% |
1117 | ! |
dplyr::group_by_at(dplyr::vars(dplyr::any_of(c(s_var, g_var)))) %>% |
1118 | ! |
dplyr::summarise(n = dplyr::n()) |
1119 | ||
1120 | ! |
validate(need(all(counts$n > 5), "Please select strata*group with at least 5 observation each.")) |
1121 |
} |
|
1122 | ||
1123 | ||
1124 | ! |
if (dist_tests %in% c( |
1125 | ! |
"t-test (two-samples, not paired)", |
1126 | ! |
"F-test", |
1127 | ! |
"Kolmogorov-Smirnov (two-samples)" |
1128 |
)) { |
|
1129 | ! |
if (length(g_var) == 0 && length(s_var) > 0) { |
1130 | ! |
validate(need( |
1131 | ! |
length(unique(ANL[[s_var]])) == 2, |
1132 | ! |
"Please select stratify variable with 2 levels." |
1133 |
)) |
|
1134 |
} |
|
1135 | ! |
if (length(g_var) > 0 && length(s_var) > 0) { |
1136 | ! |
validate(need( |
1137 | ! |
all(stats::na.omit(as.vector( |
1138 | ! |
tapply(ANL[[s_var]], list(ANL[[g_var]]), function(x) length(unique(x))) == 2 |
1139 |
))), |
|
1140 | ! |
"Please select stratify variable with 2 levels, per each group." |
1141 |
)) |
|
1142 |
} |
|
1143 |
} |
|
1144 | ||
1145 | ! |
map_dist <- stats::setNames( |
1146 | ! |
c("pnorm", "plnorm", "pgamma", "punif"), |
1147 | ! |
c("normal", "lognormal", "gamma", "unif") |
1148 |
) |
|
1149 | ! |
sks_args <- list( |
1150 | ! |
test = quote(stats::ks.test), |
1151 | ! |
args = bquote(append(list(.[[.(dist_var)]], .(map_dist[t_dist])), params)), |
1152 | ! |
groups = c(g_var, s_var) |
1153 |
) |
|
1154 | ! |
ssw_args <- list( |
1155 | ! |
test = quote(stats::shapiro.test), |
1156 | ! |
args = bquote(list(.[[.(dist_var)]])), |
1157 | ! |
groups = c(g_var, s_var) |
1158 |
) |
|
1159 | ! |
mfil_args <- list( |
1160 | ! |
test = quote(stats::fligner.test), |
1161 | ! |
args = bquote(list(.[[.(dist_var)]], .[[.(s_var)]])), |
1162 | ! |
groups = c(g_var) |
1163 |
) |
|
1164 | ! |
sad_args <- list( |
1165 | ! |
test = quote(goftest::ad.test), |
1166 | ! |
args = bquote(append(list(.[[.(dist_var)]], .(map_dist[t_dist])), params)), |
1167 | ! |
groups = c(g_var, s_var) |
1168 |
) |
|
1169 | ! |
scvm_args <- list( |
1170 | ! |
test = quote(goftest::cvm.test), |
1171 | ! |
args = bquote(append(list(.[[.(dist_var)]], .(map_dist[t_dist])), params)), |
1172 | ! |
groups = c(g_var, s_var) |
1173 |
) |
|
1174 | ! |
manov_args <- list( |
1175 | ! |
test = quote(stats::aov), |
1176 | ! |
args = bquote(list(stats::formula(.(dist_var_name) ~ .(s_var_name)), .)), |
1177 | ! |
groups = c(g_var) |
1178 |
) |
|
1179 | ! |
mt_args <- list( |
1180 | ! |
test = quote(stats::t.test), |
1181 | ! |
args = bquote(unname(split(.[[.(dist_var)]], .[[.(s_var)]], drop = TRUE))), |
1182 | ! |
groups = c(g_var) |
1183 |
) |
|
1184 | ! |
mv_args <- list( |
1185 | ! |
test = quote(stats::var.test), |
1186 | ! |
args = bquote(unname(split(.[[.(dist_var)]], .[[.(s_var)]], drop = TRUE))), |
1187 | ! |
groups = c(g_var) |
1188 |
) |
|
1189 | ! |
mks_args <- list( |
1190 | ! |
test = quote(stats::ks.test), |
1191 | ! |
args = bquote(unname(split(.[[.(dist_var)]], .[[.(s_var)]], drop = TRUE))), |
1192 | ! |
groups = c(g_var) |
1193 |
) |
|
1194 | ||
1195 | ! |
tests_base <- switch(dist_tests, |
1196 | ! |
"Kolmogorov-Smirnov (one-sample)" = sks_args, |
1197 | ! |
"Shapiro-Wilk" = ssw_args, |
1198 | ! |
"Fligner-Killeen" = mfil_args, |
1199 | ! |
"one-way ANOVA" = manov_args, |
1200 | ! |
"t-test (two-samples, not paired)" = mt_args, |
1201 | ! |
"F-test" = mv_args, |
1202 | ! |
"Kolmogorov-Smirnov (two-samples)" = mks_args, |
1203 | ! |
"Anderson-Darling (one-sample)" = sad_args, |
1204 | ! |
"Cramer-von Mises (one-sample)" = scvm_args |
1205 |
) |
|
1206 | ||
1207 | ! |
env <- list( |
1208 | ! |
t_test = t_dist, |
1209 | ! |
dist_var = dist_var, |
1210 | ! |
g_var = g_var, |
1211 | ! |
s_var = s_var, |
1212 | ! |
args = tests_base$args, |
1213 | ! |
groups = tests_base$groups, |
1214 | ! |
test = tests_base$test, |
1215 | ! |
dist_var_name = dist_var_name, |
1216 | ! |
g_var_name = g_var_name, |
1217 | ! |
s_var_name = s_var_name |
1218 |
) |
|
1219 | ||
1220 | ! |
qenv <- common_q() |
1221 | ||
1222 | ! |
if (length(s_var) == 0 && length(g_var) == 0) { |
1223 | ! |
qenv <- teal.code::eval_code( |
1224 | ! |
qenv, |
1225 | ! |
substitute( |
1226 | ! |
expr = { |
1227 | ! |
test_table_data <- ANL %>% |
1228 | ! |
dplyr::select(dist_var) %>% |
1229 | ! |
with(., generics::glance(do.call(test, args))) %>% |
1230 | ! |
dplyr::mutate_if(is.numeric, round, 3) |
1231 |
}, |
|
1232 | ! |
env = env |
1233 |
) |
|
1234 |
) |
|
1235 |
} else { |
|
1236 | ! |
qenv <- teal.code::eval_code( |
1237 | ! |
qenv, |
1238 | ! |
substitute( |
1239 | ! |
expr = { |
1240 | ! |
test_table_data <- ANL %>% |
1241 | ! |
dplyr::select(dist_var, s_var, g_var) %>% |
1242 | ! |
dplyr::group_by_at(dplyr::vars(dplyr::any_of(groups))) %>% |
1243 | ! |
dplyr::do(tests = generics::glance(do.call(test, args))) %>% |
1244 | ! |
tidyr::unnest(tests) %>% |
1245 | ! |
dplyr::mutate_if(is.numeric, round, 3) |
1246 |
}, |
|
1247 | ! |
env = env |
1248 |
) |
|
1249 |
) |
|
1250 |
} |
|
1251 |
} |
|
1252 |
) |
|
1253 | ||
1254 |
# outputs ---- |
|
1255 | ! |
output_dist_q <- reactive(c(common_q(), req(dist_q()))) |
1256 | ! |
output_qq_q <- reactive(c(common_q(), req(qq_q()))) |
1257 | ||
1258 |
# Summary table listing has to be created separately to allow for qenv join |
|
1259 | ! |
output_summary_q <- reactive({ |
1260 | ! |
if (iv_r()$is_valid()) { |
1261 | ! |
within(common_q(), summary_table <- rlistings::as_listing(summary_table_data)) |
1262 |
} else { |
|
1263 | ! |
within(common_q(), summary_table <- rlistings::as_listing(summary_table_data[0L, ])) |
1264 |
} |
|
1265 |
}) |
|
1266 | ||
1267 | ! |
output_test_q <- reactive({ |
1268 |
# wrapped in if since could lead into validate error - we do want to continue |
|
1269 | ! |
test_q_out <- try(test_q(), silent = TRUE) |
1270 | ! |
if (!inherits(test_q_out, c("try-error", "error"))) { |
1271 | ! |
c( |
1272 | ! |
common_q(), |
1273 | ! |
within(test_q_out, { |
1274 | ! |
test_table <- rlistings::as_listing(test_table_data) |
1275 |
}) |
|
1276 |
) |
|
1277 |
} else { |
|
1278 | ! |
within(common_q(), test_table <- rlistings::as_listing(data.frame(missing = character(0L)))) |
1279 |
} |
|
1280 |
}) |
|
1281 | ||
1282 | ! |
decorated_output_dist_q <- srv_decorate_teal_data( |
1283 | ! |
"d_density", |
1284 | ! |
data = output_dist_q, |
1285 | ! |
decorators = select_decorators(decorators, "histogram_plot"), |
1286 | ! |
expr = print(histogram_plot) |
1287 |
) |
|
1288 | ||
1289 | ! |
decorated_output_qq_q <- srv_decorate_teal_data( |
1290 | ! |
"d_qq", |
1291 | ! |
data = output_qq_q, |
1292 | ! |
decorators = select_decorators(decorators, "qq_plot"), |
1293 | ! |
expr = print(qq_plot) |
1294 |
) |
|
1295 | ||
1296 | ! |
decorated_output_summary_q <- srv_decorate_teal_data( |
1297 | ! |
"d_summary", |
1298 | ! |
data = output_summary_q, |
1299 | ! |
decorators = select_decorators(decorators, "summary_table"), |
1300 | ! |
expr = summary_table |
1301 |
) |
|
1302 | ||
1303 | ! |
decorated_output_test_q <- srv_decorate_teal_data( |
1304 | ! |
"d_test", |
1305 | ! |
data = output_test_q, |
1306 | ! |
decorators = select_decorators(decorators, "test_table"), |
1307 | ! |
expr = test_table |
1308 |
) |
|
1309 | ||
1310 | ! |
decorated_output_q <- reactive({ |
1311 | ! |
tab <- req(input$tabs) # tab is NULL upon app launch, hence will crash without this statement |
1312 | ! |
test_q_out <- try(test_q(), silent = TRUE) |
1313 | ! |
decorated_test_q_out <- if (inherits(test_q_out, c("try-error", "error"))) { |
1314 | ! |
teal.code::qenv() |
1315 |
} else { |
|
1316 | ! |
decorated_output_test_q() |
1317 |
} |
|
1318 | ||
1319 | ! |
out_q <- switch(tab, |
1320 | ! |
Histogram = decorated_output_dist_q(), |
1321 | ! |
QQplot = decorated_output_qq_q() |
1322 |
) |
|
1323 | ! |
c(out_q, decorated_output_summary_q(), decorated_test_q_out) |
1324 |
}) |
|
1325 | ||
1326 | ! |
dist_r <- reactive(req(decorated_output_dist_q())[["histogram_plot"]]) |
1327 | ||
1328 | ! |
qq_r <- reactive(req(decorated_output_qq_q())[["qq_plot"]]) |
1329 | ||
1330 | ! |
output$summary_table <- DT::renderDataTable( |
1331 | ! |
expr = decorated_output_summary_q()[["summary_table_data"]], |
1332 | ! |
options = list( |
1333 | ! |
autoWidth = TRUE, |
1334 | ! |
columnDefs = list(list(width = "200px", targets = "_all")) |
1335 |
), |
|
1336 | ! |
rownames = FALSE |
1337 |
) |
|
1338 | ||
1339 | ! |
tests_r <- reactive({ |
1340 | ! |
req(iv_r()$is_valid()) |
1341 | ! |
teal::validate_inputs(iv_r_dist()) |
1342 | ! |
req(test_q()) # Ensure original errors are displayed |
1343 | ! |
DT::datatable( |
1344 | ! |
data = decorated_output_test_q()[["test_table_data"]], |
1345 | ! |
options = list(scrollX = TRUE), |
1346 | ! |
rownames = FALSE |
1347 |
) |
|
1348 |
}) |
|
1349 | ||
1350 | ! |
pws1 <- teal.widgets::plot_with_settings_srv( |
1351 | ! |
id = "hist_plot", |
1352 | ! |
plot_r = dist_r, |
1353 | ! |
height = plot_height, |
1354 | ! |
width = plot_width, |
1355 | ! |
brushing = FALSE |
1356 |
) |
|
1357 | ||
1358 | ! |
pws2 <- teal.widgets::plot_with_settings_srv( |
1359 | ! |
id = "qq_plot", |
1360 | ! |
plot_r = qq_r, |
1361 | ! |
height = plot_height, |
1362 | ! |
width = plot_width, |
1363 | ! |
brushing = FALSE |
1364 |
) |
|
1365 | ||
1366 | ! |
output$t_stats <- DT::renderDataTable(expr = tests_r()) |
1367 | ||
1368 |
# Render R code. |
|
1369 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_output_q()))) |
1370 | ||
1371 | ! |
teal.widgets::verbatim_popup_srv( |
1372 | ! |
id = "rcode", |
1373 | ! |
verbatim_content = source_code_r, |
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 | ! |
card$append_table(decorated_output_summary_q()[["summary_table"]]) |
1394 | ! |
tests_error <- tryCatch(expr = tests_r(), error = function(e) "error") |
1395 | ! |
if (inherits(tests_error, "data.frame")) { |
1396 | ! |
card$append_text("Tests table", "header3") |
1397 | ! |
card$append_table(tests_r()) |
1398 |
} |
|
1399 | ||
1400 | ! |
if (!comment == "") { |
1401 | ! |
card$append_text("Comment", "header3") |
1402 | ! |
card$append_text(comment) |
1403 |
} |
|
1404 | ! |
card$append_src(source_code_r()) |
1405 | ! |
card |
1406 |
} |
|
1407 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
1408 |
} |
|
1409 |
### |
|
1410 |
}) |
|
1411 |
} |
1 |
#' `teal` module: Scatterplot and regression analysis |
|
2 |
#' |
|
3 |
#' Module for visualizing regression analysis, including scatterplots and |
|
4 |
#' various regression diagnostics plots. |
|
5 |
#' It allows users to explore the relationship between a set of regressors and a response variable, |
|
6 |
#' visualize residuals, and identify outliers. |
|
7 |
#' |
|
8 |
#' @note For more examples, please see the vignette "Using regression plots" via |
|
9 |
#' `vignette("using-regression-plots", package = "teal.modules.general")`. |
|
10 |
#' |
|
11 |
#' @inheritParams teal::module |
|
12 |
#' @inheritParams shared_params |
|
13 |
#' @param regressor (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
14 |
#' Regressor variables from an incoming dataset with filtering and selecting. |
|
15 |
#' @param response (`data_extract_spec` or `list` of multiple `data_extract_spec`) |
|
16 |
#' Response variables from an incoming dataset with filtering and selecting. |
|
17 |
#' @param default_outlier_label (`character`) optional, default column selected to label outliers. |
|
18 |
#' @param default_plot_type (`numeric`) optional, defaults to "Response vs Regressor". |
|
19 |
#' 1. Response vs Regressor |
|
20 |
#' 2. Residuals vs Fitted |
|
21 |
#' 3. Normal Q-Q |
|
22 |
#' 4. Scale-Location |
|
23 |
#' 5. Cook's distance |
|
24 |
#' 6. Residuals vs Leverage |
|
25 |
#' 7. Cook's dist vs Leverage |
|
26 |
#' @param label_segment_threshold (`numeric(1)` or `numeric(3)`) |
|
27 |
#' Minimum distance between label and point on the plot that triggers the creation of |
|
28 |
#' a line segment between the two. |
|
29 |
#' This may happen when the label cannot be placed next to the point as it overlaps another |
|
30 |
#' label or point. |
|
31 |
#' The value is used as the `min.segment.length` parameter to the [ggrepel::geom_text_repel()] function. |
|
32 |
#' |
|
33 |
#' It can take the following forms: |
|
34 |
#' - `numeric(1)`: Fixed value used for the minimum distance and the slider is not presented in the UI. |
|
35 |
#' - `numeric(3)`: A slider is presented in the UI (under "Plot settings") to adjust the minimum distance dynamically. |
|
36 |
#' |
|
37 |
#' It takes the form of `c(value, min, max)` and it is passed to the `value_min_max` |
|
38 |
#' argument in `teal.widgets::optionalSliderInputValMinMax`. |
|
39 |
#' |
|
40 |
# nolint start: line_length. |
|
41 |
#' @param ggplot2_args `r roxygen_ggplot2_args_param("Response vs Regressor", "Residuals vs Fitted", "Scale-Location", "Cook's distance", "Residuals vs Leverage", "Cook's dist vs Leverage")` |
|
42 |
# nolint end: line_length. |
|
43 |
#' |
|
44 |
#' @inherit shared_params return |
|
45 |
#' |
|
46 |
#' @section Decorating Module: |
|
47 |
#' |
|
48 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
49 |
#' - `plot` (`ggplot2`) |
|
50 |
#' |
|
51 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
52 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
53 |
#' See code snippet below: |
|
54 |
#' |
|
55 |
#' ``` |
|
56 |
#' tm_a_regression( |
|
57 |
#' ..., # arguments for module |
|
58 |
#' decorators = list( |
|
59 |
#' plot = teal_transform_module(...) # applied to the `plot` output |
|
60 |
#' ) |
|
61 |
#' ) |
|
62 |
#' ``` |
|
63 |
#' |
|
64 |
#' For additional details and examples of decorators, refer to the vignette |
|
65 |
#' `vignette("decorate-modules-output", package = "teal")` or the [`teal::teal_transform_module()`] documentation. |
|
66 |
#' |
|
67 |
#' @examplesShinylive |
|
68 |
#' library(teal.modules.general) |
|
69 |
#' interactive <- function() TRUE |
|
70 |
#' {{ next_example }} |
|
71 |
#' @examples |
|
72 |
#' |
|
73 |
#' # general data example |
|
74 |
#' data <- teal_data() |
|
75 |
#' data <- within(data, { |
|
76 |
#' require(nestcolor) |
|
77 |
#' CO2 <- CO2 |
|
78 |
#' }) |
|
79 |
#' |
|
80 |
#' app <- init( |
|
81 |
#' data = data, |
|
82 |
#' modules = modules( |
|
83 |
#' tm_a_regression( |
|
84 |
#' label = "Regression", |
|
85 |
#' response = data_extract_spec( |
|
86 |
#' dataname = "CO2", |
|
87 |
#' select = select_spec( |
|
88 |
#' label = "Select variable:", |
|
89 |
#' choices = "uptake", |
|
90 |
#' selected = "uptake", |
|
91 |
#' multiple = FALSE, |
|
92 |
#' fixed = TRUE |
|
93 |
#' ) |
|
94 |
#' ), |
|
95 |
#' regressor = data_extract_spec( |
|
96 |
#' dataname = "CO2", |
|
97 |
#' select = select_spec( |
|
98 |
#' label = "Select variables:", |
|
99 |
#' choices = variable_choices(data[["CO2"]], c("conc", "Treatment")), |
|
100 |
#' selected = "conc", |
|
101 |
#' multiple = TRUE, |
|
102 |
#' fixed = FALSE |
|
103 |
#' ) |
|
104 |
#' ) |
|
105 |
#' ) |
|
106 |
#' ) |
|
107 |
#' ) |
|
108 |
#' if (interactive()) { |
|
109 |
#' shinyApp(app$ui, app$server) |
|
110 |
#' } |
|
111 |
#' |
|
112 |
#' @examplesShinylive |
|
113 |
#' library(teal.modules.general) |
|
114 |
#' interactive <- function() TRUE |
|
115 |
#' {{ next_example }} |
|
116 |
#' @examples |
|
117 |
#' # CDISC data example |
|
118 |
#' data <- teal_data() |
|
119 |
#' data <- within(data, { |
|
120 |
#' require(nestcolor) |
|
121 |
#' ADSL <- teal.data::rADSL |
|
122 |
#' }) |
|
123 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
124 |
#' |
|
125 |
#' app <- init( |
|
126 |
#' data = data, |
|
127 |
#' modules = modules( |
|
128 |
#' tm_a_regression( |
|
129 |
#' label = "Regression", |
|
130 |
#' response = data_extract_spec( |
|
131 |
#' dataname = "ADSL", |
|
132 |
#' select = select_spec( |
|
133 |
#' label = "Select variable:", |
|
134 |
#' choices = "BMRKR1", |
|
135 |
#' selected = "BMRKR1", |
|
136 |
#' multiple = FALSE, |
|
137 |
#' fixed = TRUE |
|
138 |
#' ) |
|
139 |
#' ), |
|
140 |
#' regressor = data_extract_spec( |
|
141 |
#' dataname = "ADSL", |
|
142 |
#' select = select_spec( |
|
143 |
#' label = "Select variables:", |
|
144 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "SEX", "RACE")), |
|
145 |
#' selected = "AGE", |
|
146 |
#' multiple = TRUE, |
|
147 |
#' fixed = FALSE |
|
148 |
#' ) |
|
149 |
#' ) |
|
150 |
#' ) |
|
151 |
#' ) |
|
152 |
#' ) |
|
153 |
#' if (interactive()) { |
|
154 |
#' shinyApp(app$ui, app$server) |
|
155 |
#' } |
|
156 |
#' |
|
157 |
#' @export |
|
158 |
#' |
|
159 |
tm_a_regression <- function(label = "Regression Analysis", |
|
160 |
regressor, |
|
161 |
response, |
|
162 |
plot_height = c(600, 200, 2000), |
|
163 |
plot_width = NULL, |
|
164 |
alpha = c(1, 0, 1), |
|
165 |
size = c(2, 1, 8), |
|
166 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
167 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
168 |
pre_output = NULL, |
|
169 |
post_output = NULL, |
|
170 |
default_plot_type = 1, |
|
171 |
default_outlier_label = "USUBJID", |
|
172 |
label_segment_threshold = c(0.5, 0, 10), |
|
173 |
transformators = list(), |
|
174 |
decorators = list()) { |
|
175 | ! |
message("Initializing tm_a_regression") |
176 | ||
177 |
# Normalize the parameters |
|
178 | ! |
if (inherits(regressor, "data_extract_spec")) regressor <- list(regressor) |
179 | ! |
if (inherits(response, "data_extract_spec")) response <- list(response) |
180 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
181 | ||
182 |
# Start of assertions |
|
183 | ! |
checkmate::assert_string(label) |
184 | ! |
checkmate::assert_list(regressor, types = "data_extract_spec") |
185 | ||
186 | ! |
checkmate::assert_list(response, types = "data_extract_spec") |
187 | ! |
assert_single_selection(response) |
188 | ||
189 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
190 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
191 | ||
192 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
193 | ! |
checkmate::assert_numeric( |
194 | ! |
plot_width[1], |
195 | ! |
lower = plot_width[2], |
196 | ! |
upper = plot_width[3], |
197 | ! |
null.ok = TRUE, |
198 | ! |
.var.name = "plot_width" |
199 |
) |
|
200 | ||
201 | ! |
if (length(alpha) == 1) { |
202 | ! |
checkmate::assert_numeric(alpha, any.missing = FALSE, finite = TRUE) |
203 |
} else { |
|
204 | ! |
checkmate::assert_numeric(alpha, len = 3, any.missing = FALSE, finite = TRUE) |
205 | ! |
checkmate::assert_numeric(alpha[1], lower = alpha[2], upper = alpha[3], .var.name = "alpha") |
206 |
} |
|
207 | ||
208 | ! |
if (length(size) == 1) { |
209 | ! |
checkmate::assert_numeric(size, any.missing = FALSE, finite = TRUE) |
210 |
} else { |
|
211 | ! |
checkmate::assert_numeric(size, len = 3, any.missing = FALSE, finite = TRUE) |
212 | ! |
checkmate::assert_numeric(size[1], lower = size[2], upper = size[3], .var.name = "size") |
213 |
} |
|
214 | ||
215 | ! |
ggtheme <- match.arg(ggtheme) |
216 | ||
217 | ! |
plot_choices <- c( |
218 | ! |
"Response vs Regressor", "Residuals vs Fitted", "Normal Q-Q", "Scale-Location", |
219 | ! |
"Cook's distance", "Residuals vs Leverage", "Cook's dist vs Leverage" |
220 |
) |
|
221 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
222 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
223 | ||
224 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
225 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
226 | ! |
checkmate::assert_choice(default_plot_type, seq.int(1L, length(plot_choices))) |
227 | ! |
checkmate::assert_string(default_outlier_label) |
228 | ! |
checkmate::assert_list(decorators, "teal_transform_module") |
229 | ||
230 | ! |
if (length(label_segment_threshold) == 1) { |
231 | ! |
checkmate::assert_numeric(label_segment_threshold, any.missing = FALSE, finite = TRUE) |
232 |
} else { |
|
233 | ! |
checkmate::assert_numeric(label_segment_threshold, len = 3, any.missing = FALSE, finite = TRUE) |
234 | ! |
checkmate::assert_numeric( |
235 | ! |
label_segment_threshold[1], |
236 | ! |
lower = label_segment_threshold[2], |
237 | ! |
upper = label_segment_threshold[3], |
238 | ! |
.var.name = "label_segment_threshold" |
239 |
) |
|
240 |
} |
|
241 | ! |
assert_decorators(decorators, "plot") |
242 |
# End of assertions |
|
243 | ||
244 |
# Make UI args |
|
245 | ! |
args <- as.list(environment()) |
246 | ! |
args[["plot_choices"]] <- plot_choices |
247 | ! |
data_extract_list <- list( |
248 | ! |
regressor = regressor, |
249 | ! |
response = response |
250 |
) |
|
251 | ||
252 | ! |
ans <- module( |
253 | ! |
label = label, |
254 | ! |
server = srv_a_regression, |
255 | ! |
ui = ui_a_regression, |
256 | ! |
ui_args = args, |
257 | ! |
server_args = c( |
258 | ! |
data_extract_list, |
259 | ! |
list( |
260 | ! |
plot_height = plot_height, |
261 | ! |
plot_width = plot_width, |
262 | ! |
default_outlier_label = default_outlier_label, |
263 | ! |
ggplot2_args = ggplot2_args, |
264 | ! |
decorators = decorators |
265 |
) |
|
266 |
), |
|
267 | ! |
transformators = transformators, |
268 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
269 |
) |
|
270 | ! |
attr(ans, "teal_bookmarkable") <- FALSE |
271 | ! |
ans |
272 |
} |
|
273 | ||
274 |
# UI function for the regression module |
|
275 |
ui_a_regression <- function(id, ...) { |
|
276 | ! |
ns <- NS(id) |
277 | ! |
args <- list(...) |
278 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$regressor, args$response) |
279 | ! |
teal.widgets::standard_layout( |
280 | ! |
output = teal.widgets::white_small_well(tags$div( |
281 | ! |
teal.widgets::plot_with_settings_ui(id = ns("myplot")), |
282 | ! |
tags$div(verbatimTextOutput(ns("text"))) |
283 |
)), |
|
284 | ! |
encoding = tags$div( |
285 |
### Reporter |
|
286 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
287 |
### |
|
288 | ! |
tags$label("Encodings", class = "text-primary"), |
289 | ! |
teal.transform::datanames_input(args[c("response", "regressor")]), |
290 | ! |
teal.transform::data_extract_ui( |
291 | ! |
id = ns("response"), |
292 | ! |
label = "Response variable", |
293 | ! |
data_extract_spec = args$response, |
294 | ! |
is_single_dataset = is_single_dataset_value |
295 |
), |
|
296 | ! |
teal.transform::data_extract_ui( |
297 | ! |
id = ns("regressor"), |
298 | ! |
label = "Regressor variables", |
299 | ! |
data_extract_spec = args$regressor, |
300 | ! |
is_single_dataset = is_single_dataset_value |
301 |
), |
|
302 | ! |
radioButtons( |
303 | ! |
ns("plot_type"), |
304 | ! |
label = "Plot type:", |
305 | ! |
choices = args$plot_choices, |
306 | ! |
selected = args$plot_choices[args$default_plot_type] |
307 |
), |
|
308 | ! |
checkboxInput(ns("show_outlier"), label = "Display outlier labels", value = TRUE), |
309 | ! |
conditionalPanel( |
310 | ! |
condition = "input['show_outlier']", |
311 | ! |
ns = ns, |
312 | ! |
teal.widgets::optionalSliderInput( |
313 | ! |
ns("outlier"), |
314 | ! |
tags$div( |
315 | ! |
class = "teal-tooltip", |
316 | ! |
tagList( |
317 | ! |
"Outlier definition:", |
318 | ! |
icon("circle-info"), |
319 | ! |
tags$span( |
320 | ! |
class = "tooltiptext", |
321 | ! |
paste( |
322 | ! |
"Use the slider to choose the cut-off value to define outliers.", |
323 | ! |
"Points with a Cook's distance greater than", |
324 | ! |
"the value on the slider times the mean of the Cook's distance of the dataset will have labels." |
325 |
) |
|
326 |
) |
|
327 |
) |
|
328 |
), |
|
329 | ! |
min = 1, max = 10, value = 9, ticks = FALSE, step = .1 |
330 |
), |
|
331 | ! |
teal.widgets::optionalSelectInput( |
332 | ! |
ns("label_var"), |
333 | ! |
multiple = FALSE, |
334 | ! |
label = "Outlier label" |
335 |
) |
|
336 |
), |
|
337 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "plot")), |
338 | ! |
teal.widgets::panel_group( |
339 | ! |
teal.widgets::panel_item( |
340 | ! |
title = "Plot settings", |
341 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("alpha"), "Opacity:", args$alpha, ticks = FALSE), |
342 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("size"), "Points size:", args$size, ticks = FALSE), |
343 | ! |
teal.widgets::optionalSliderInputValMinMax( |
344 | ! |
inputId = ns("label_min_segment"), |
345 | ! |
label = tags$div( |
346 | ! |
class = "teal-tooltip", |
347 | ! |
tagList( |
348 | ! |
"Label min. segment:", |
349 | ! |
icon("circle-info"), |
350 | ! |
tags$span( |
351 | ! |
class = "tooltiptext", |
352 | ! |
paste( |
353 | ! |
"Use the slider to choose the cut-off value to define minimum distance between label and point", |
354 | ! |
"that generates a line segment.", |
355 | ! |
"It's only valid when 'Display outlier labels' is checked." |
356 |
) |
|
357 |
) |
|
358 |
) |
|
359 |
), |
|
360 | ! |
value_min_max = args$label_segment_threshold, |
361 |
# Extra parameters to sliderInput |
|
362 | ! |
ticks = FALSE, |
363 | ! |
step = .1, |
364 | ! |
round = FALSE |
365 |
), |
|
366 | ! |
selectInput( |
367 | ! |
inputId = ns("ggtheme"), |
368 | ! |
label = "Theme (by ggplot):", |
369 | ! |
choices = ggplot_themes, |
370 | ! |
selected = args$ggtheme, |
371 | ! |
multiple = FALSE |
372 |
) |
|
373 |
) |
|
374 |
) |
|
375 |
), |
|
376 | ! |
forms = tagList( |
377 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
378 |
), |
|
379 | ! |
pre_output = args$pre_output, |
380 | ! |
post_output = args$post_output |
381 |
) |
|
382 |
} |
|
383 | ||
384 |
# Server function for the regression module |
|
385 |
srv_a_regression <- function(id, |
|
386 |
data, |
|
387 |
reporter, |
|
388 |
filter_panel_api, |
|
389 |
response, |
|
390 |
regressor, |
|
391 |
plot_height, |
|
392 |
plot_width, |
|
393 |
ggplot2_args, |
|
394 |
default_outlier_label, |
|
395 |
decorators) { |
|
396 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
397 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
398 | ! |
checkmate::assert_class(data, "reactive") |
399 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
400 | ! |
moduleServer(id, function(input, output, session) { |
401 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
402 | ||
403 | ! |
ns <- session$ns |
404 | ||
405 | ! |
rule_rvr1 <- function(value) { |
406 | ! |
if (isTRUE(input$plot_type == "Response vs Regressor")) { |
407 | ! |
if (length(value) > 1L) { |
408 | ! |
"This plot can only have one regressor." |
409 |
} |
|
410 |
} |
|
411 |
} |
|
412 | ! |
rule_rvr2 <- function(other) { |
413 | ! |
function(value) { |
414 | ! |
if (isTRUE(input$plot_type == "Response vs Regressor")) { |
415 | ! |
otherval <- selector_list()[[other]]()$select |
416 | ! |
if (isTRUE(value == otherval)) { |
417 | ! |
"Response and Regressor must be different." |
418 |
} |
|
419 |
} |
|
420 |
} |
|
421 |
} |
|
422 | ||
423 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
424 | ! |
data_extract = list(response = response, regressor = regressor), |
425 | ! |
datasets = data, |
426 | ! |
select_validation_rule = list( |
427 | ! |
regressor = shinyvalidate::compose_rules( |
428 | ! |
shinyvalidate::sv_required("At least one regressor should be selected."), |
429 | ! |
rule_rvr1, |
430 | ! |
rule_rvr2("response") |
431 |
), |
|
432 | ! |
response = shinyvalidate::compose_rules( |
433 | ! |
shinyvalidate::sv_required("At least one response should be selected."), |
434 | ! |
rule_rvr2("regressor") |
435 |
) |
|
436 |
) |
|
437 |
) |
|
438 | ||
439 | ! |
iv_r <- reactive({ |
440 | ! |
iv <- shinyvalidate::InputValidator$new() |
441 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
442 |
}) |
|
443 | ||
444 | ! |
iv_out <- shinyvalidate::InputValidator$new() |
445 | ! |
iv_out$condition(~ isTRUE(input$show_outlier)) |
446 | ! |
iv_out$add_rule("label_var", shinyvalidate::sv_required("Please provide an `Outlier label` variable")) |
447 | ! |
iv_out$enable() |
448 | ||
449 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
450 | ! |
selector_list = selector_list, |
451 | ! |
datasets = data |
452 |
) |
|
453 | ||
454 | ! |
regression_var <- reactive({ |
455 | ! |
teal::validate_inputs(iv_r()) |
456 | ||
457 | ! |
list( |
458 | ! |
response = as.vector(anl_merged_input()$columns_source$response), |
459 | ! |
regressor = as.vector(anl_merged_input()$columns_source$regressor) |
460 |
) |
|
461 |
}) |
|
462 | ||
463 | ! |
anl_merged_q <- reactive({ |
464 | ! |
req(anl_merged_input()) |
465 | ! |
data() %>% |
466 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
467 |
}) |
|
468 | ||
469 |
# sets qenv object and populates it with data merge call and fit expression |
|
470 | ! |
fit_r <- reactive({ |
471 | ! |
ANL <- anl_merged_q()[["ANL"]] |
472 | ! |
teal::validate_has_data(ANL, 10) |
473 | ||
474 | ! |
validate(need(is.numeric(ANL[regression_var()$response][[1]]), "Response variable should be numeric.")) |
475 | ||
476 | ! |
teal::validate_has_data( |
477 | ! |
ANL[, c(regression_var()$response, regression_var()$regressor)], 10, |
478 | ! |
complete = TRUE, allow_inf = FALSE |
479 |
) |
|
480 | ||
481 | ! |
form <- stats::as.formula( |
482 | ! |
paste( |
483 | ! |
regression_var()$response, |
484 | ! |
paste( |
485 | ! |
regression_var()$regressor, |
486 | ! |
collapse = " + " |
487 |
), |
|
488 | ! |
sep = " ~ " |
489 |
) |
|
490 |
) |
|
491 | ||
492 | ! |
if (input$show_outlier) { |
493 | ! |
opts <- teal.transform::variable_choices(ANL) |
494 | ! |
selected <- if (!is.null(isolate(input$label_var)) && isolate(input$label_var) %in% as.character(opts)) { |
495 | ! |
isolate(input$label_var) |
496 |
} else { |
|
497 | ! |
if (length(opts[as.character(opts) == default_outlier_label]) == 0) { |
498 | ! |
opts[[1]] |
499 |
} else { |
|
500 | ! |
opts[as.character(opts) == default_outlier_label] |
501 |
} |
|
502 |
} |
|
503 | ! |
teal.widgets::updateOptionalSelectInput( |
504 | ! |
session = session, |
505 | ! |
inputId = "label_var", |
506 | ! |
choices = opts, |
507 | ! |
selected = restoreInput(ns("label_var"), selected) |
508 |
) |
|
509 | ||
510 | ! |
data <- fortify(stats::lm(form, data = ANL)) |
511 | ! |
cooksd <- data$.cooksd[!is.nan(data$.cooksd)] |
512 | ! |
max_outlier <- max(ceiling(max(cooksd) / mean(cooksd)), 2) |
513 | ! |
cur_outlier <- isolate(input$outlier) |
514 | ! |
updateSliderInput( |
515 | ! |
session = session, |
516 | ! |
inputId = "outlier", |
517 | ! |
min = 1, |
518 | ! |
max = max_outlier, |
519 | ! |
value = restoreInput(ns("outlier"), if (cur_outlier < max_outlier) cur_outlier else max_outlier * .9) |
520 |
) |
|
521 |
} |
|
522 | ||
523 | ! |
anl_merged_q() %>% |
524 | ! |
teal.code::eval_code(substitute(fit <- stats::lm(form, data = ANL), env = list(form = form))) %>% |
525 | ! |
teal.code::eval_code(quote({ |
526 | ! |
for (regressor in names(fit$contrasts)) { |
527 | ! |
alts <- paste0(levels(ANL[[regressor]]), collapse = "|") |
528 | ! |
names(fit$coefficients) <- gsub( |
529 | ! |
paste0("^(", regressor, ")(", alts, ")$"), paste0("\\1", ": ", "\\2"), names(fit$coefficients) |
530 |
) |
|
531 |
} |
|
532 |
})) %>% |
|
533 | ! |
teal.code::eval_code(quote(summary(fit))) |
534 |
}) |
|
535 | ||
536 | ! |
label_col <- reactive({ |
537 | ! |
teal::validate_inputs(iv_out) |
538 | ||
539 | ! |
substitute( |
540 | ! |
expr = dplyr::if_else( |
541 | ! |
data$.cooksd > outliers * mean(data$.cooksd, na.rm = TRUE), |
542 | ! |
as.character(stats::na.omit(ANL)[[label_var]]), |
543 |
"" |
|
544 |
) %>% |
|
545 | ! |
dplyr::if_else(is.na(.), "cooksd == NaN", .), |
546 | ! |
env = list(outliers = input$outlier, label_var = input$label_var) |
547 |
) |
|
548 |
}) |
|
549 | ||
550 | ! |
label_min_segment <- reactive({ |
551 | ! |
input$label_min_segment |
552 |
}) |
|
553 | ||
554 | ! |
outlier_label <- reactive({ |
555 | ! |
substitute( |
556 | ! |
expr = ggrepel::geom_text_repel( |
557 | ! |
label = label_col, |
558 | ! |
color = "red", |
559 | ! |
hjust = 0, |
560 | ! |
vjust = 1, |
561 | ! |
max.overlaps = Inf, |
562 | ! |
min.segment.length = label_min_segment, |
563 | ! |
segment.alpha = 0.5, |
564 | ! |
seed = 123 |
565 |
), |
|
566 | ! |
env = list(label_col = label_col(), label_min_segment = label_min_segment()) |
567 |
) |
|
568 |
}) |
|
569 | ||
570 | ! |
output_plot_base <- reactive({ |
571 | ! |
base_fit <- fit_r() |
572 | ! |
teal.code::eval_code( |
573 | ! |
base_fit, |
574 | ! |
quote({ |
575 | ! |
class(fit$residuals) <- NULL |
576 | ||
577 | ! |
data <- ggplot2::fortify(fit) |
578 | ||
579 | ! |
smooth <- function(x, y) { |
580 | ! |
as.data.frame(stats::lowess(x, y, f = 2 / 3, iter = 3)) |
581 |
} |
|
582 | ||
583 | ! |
smoothy_aes <- ggplot2::aes_string(x = "x", y = "y") |
584 | ||
585 | ! |
reg_form <- deparse(fit$call[[2]]) |
586 |
}) |
|
587 |
) |
|
588 |
}) |
|
589 | ||
590 | ! |
output_plot_0 <- reactive({ |
591 | ! |
fit <- fit_r()[["fit"]] |
592 | ! |
ANL <- anl_merged_q()[["ANL"]] |
593 | ||
594 | ! |
stopifnot(ncol(fit$model) == 2) |
595 | ||
596 | ! |
if (!is.factor(ANL[[regression_var()$regressor]])) { |
597 | ! |
shinyjs::show("size") |
598 | ! |
shinyjs::show("alpha") |
599 | ! |
plot <- substitute( |
600 | ! |
expr = ggplot(fit$model[, 2:1], aes_string(regressor, response)) + |
601 | ! |
geom_point(size = size, alpha = alpha) + |
602 | ! |
stat_smooth(method = "lm", formula = y ~ x, se = FALSE), |
603 | ! |
env = list( |
604 | ! |
regressor = regression_var()$regressor, |
605 | ! |
response = regression_var()$response, |
606 | ! |
size = input$size, |
607 | ! |
alpha = input$alpha |
608 |
) |
|
609 |
) |
|
610 | ! |
if (input$show_outlier) { |
611 | ! |
plot <- substitute( |
612 | ! |
expr = plot + outlier_label, |
613 | ! |
env = list(plot = plot, outlier_label = outlier_label()) |
614 |
) |
|
615 |
} |
|
616 |
} else { |
|
617 | ! |
shinyjs::hide("size") |
618 | ! |
shinyjs::hide("alpha") |
619 | ! |
plot <- substitute( |
620 | ! |
expr = ggplot(fit$model[, 2:1], aes_string(regressor, response)) + |
621 | ! |
geom_boxplot(), |
622 | ! |
env = list(regressor = regression_var()$regressor, response = regression_var()$response) |
623 |
) |
|
624 | ! |
if (input$show_outlier) { |
625 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
626 |
} |
|
627 |
} |
|
628 | ||
629 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
630 | ! |
teal.widgets::resolve_ggplot2_args( |
631 | ! |
user_plot = ggplot2_args[["Response vs Regressor"]], |
632 | ! |
user_default = ggplot2_args$default, |
633 | ! |
module_plot = teal.widgets::ggplot2_args( |
634 | ! |
labs = list( |
635 | ! |
title = "Response vs Regressor", |
636 | ! |
x = varname_w_label(regression_var()$regressor, ANL), |
637 | ! |
y = varname_w_label(regression_var()$response, ANL) |
638 |
), |
|
639 | ! |
theme = list() |
640 |
) |
|
641 |
), |
|
642 | ! |
ggtheme = input$ggtheme |
643 |
) |
|
644 | ||
645 | ! |
teal.code::eval_code( |
646 | ! |
fit_r(), |
647 | ! |
substitute( |
648 | ! |
expr = { |
649 | ! |
class(fit$residuals) <- NULL |
650 | ! |
data <- fortify(fit) |
651 | ! |
plot <- graph |
652 |
}, |
|
653 | ! |
env = list( |
654 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
655 |
) |
|
656 |
) |
|
657 |
) |
|
658 |
}) |
|
659 | ||
660 | ! |
output_plot_1 <- reactive({ |
661 | ! |
plot_base <- output_plot_base() |
662 | ! |
shinyjs::show("size") |
663 | ! |
shinyjs::show("alpha") |
664 | ! |
plot <- substitute( |
665 | ! |
expr = ggplot(data = data, aes(.fitted, .resid)) + |
666 | ! |
geom_point(size = size, alpha = alpha) + |
667 | ! |
geom_hline(yintercept = 0, linetype = "dashed", size = 1) + |
668 | ! |
geom_line(data = smoothy, mapping = smoothy_aes), |
669 | ! |
env = list(size = input$size, alpha = input$alpha) |
670 |
) |
|
671 | ! |
if (input$show_outlier) { |
672 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
673 |
} |
|
674 | ||
675 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
676 | ! |
teal.widgets::resolve_ggplot2_args( |
677 | ! |
user_plot = ggplot2_args[["Residuals vs Fitted"]], |
678 | ! |
user_default = ggplot2_args$default, |
679 | ! |
module_plot = teal.widgets::ggplot2_args( |
680 | ! |
labs = list( |
681 | ! |
x = quote(paste0("Fitted values\nlm(", reg_form, ")")), |
682 | ! |
y = "Residuals", |
683 | ! |
title = "Residuals vs Fitted" |
684 |
) |
|
685 |
) |
|
686 |
), |
|
687 | ! |
ggtheme = input$ggtheme |
688 |
) |
|
689 | ||
690 | ! |
teal.code::eval_code( |
691 | ! |
plot_base, |
692 | ! |
substitute( |
693 | ! |
expr = { |
694 | ! |
smoothy <- smooth(data$.fitted, data$.resid) |
695 | ! |
plot <- graph |
696 |
}, |
|
697 | ! |
env = list( |
698 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
699 |
) |
|
700 |
) |
|
701 |
) |
|
702 |
}) |
|
703 | ||
704 | ! |
output_plot_2 <- reactive({ |
705 | ! |
shinyjs::show("size") |
706 | ! |
shinyjs::show("alpha") |
707 | ! |
plot_base <- output_plot_base() |
708 | ! |
plot <- substitute( |
709 | ! |
expr = ggplot(data = data, aes(sample = .stdresid)) + |
710 | ! |
stat_qq(size = size, alpha = alpha) + |
711 | ! |
geom_abline(linetype = "dashed"), |
712 | ! |
env = list(size = input$size, alpha = input$alpha) |
713 |
) |
|
714 | ! |
if (input$show_outlier) { |
715 | ! |
plot <- substitute( |
716 | ! |
expr = plot + |
717 | ! |
stat_qq( |
718 | ! |
geom = ggrepel::GeomTextRepel, |
719 | ! |
label = label_col %>% |
720 | ! |
data.frame(label = .) %>% |
721 | ! |
dplyr::filter(label != "cooksd == NaN") %>% |
722 | ! |
unlist(), |
723 | ! |
color = "red", |
724 | ! |
hjust = 0, |
725 | ! |
vjust = 0, |
726 | ! |
max.overlaps = Inf, |
727 | ! |
min.segment.length = label_min_segment, |
728 | ! |
segment.alpha = .5, |
729 | ! |
seed = 123 |
730 |
), |
|
731 | ! |
env = list(plot = plot, label_col = label_col(), label_min_segment = label_min_segment()) |
732 |
) |
|
733 |
} |
|
734 | ||
735 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
736 | ! |
teal.widgets::resolve_ggplot2_args( |
737 | ! |
user_plot = ggplot2_args[["Normal Q-Q"]], |
738 | ! |
user_default = ggplot2_args$default, |
739 | ! |
module_plot = teal.widgets::ggplot2_args( |
740 | ! |
labs = list( |
741 | ! |
x = quote(paste0("Theoretical Quantiles\nlm(", reg_form, ")")), |
742 | ! |
y = "Standardized residuals", |
743 | ! |
title = "Normal Q-Q" |
744 |
) |
|
745 |
) |
|
746 |
), |
|
747 | ! |
ggtheme = input$ggtheme |
748 |
) |
|
749 | ||
750 | ! |
teal.code::eval_code( |
751 | ! |
plot_base, |
752 | ! |
substitute( |
753 | ! |
expr = { |
754 | ! |
plot <- graph |
755 |
}, |
|
756 | ! |
env = list( |
757 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
758 |
) |
|
759 |
) |
|
760 |
) |
|
761 |
}) |
|
762 | ||
763 | ! |
output_plot_3 <- reactive({ |
764 | ! |
shinyjs::show("size") |
765 | ! |
shinyjs::show("alpha") |
766 | ! |
plot_base <- output_plot_base() |
767 | ! |
plot <- substitute( |
768 | ! |
expr = ggplot(data = data, aes(.fitted, sqrt(abs(.stdresid)))) + |
769 | ! |
geom_point(size = size, alpha = alpha) + |
770 | ! |
geom_line(data = smoothy, mapping = smoothy_aes), |
771 | ! |
env = list(size = input$size, alpha = input$alpha) |
772 |
) |
|
773 | ! |
if (input$show_outlier) { |
774 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
775 |
} |
|
776 | ||
777 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
778 | ! |
teal.widgets::resolve_ggplot2_args( |
779 | ! |
user_plot = ggplot2_args[["Scale-Location"]], |
780 | ! |
user_default = ggplot2_args$default, |
781 | ! |
module_plot = teal.widgets::ggplot2_args( |
782 | ! |
labs = list( |
783 | ! |
x = quote(paste0("Fitted values\nlm(", reg_form, ")")), |
784 | ! |
y = quote(expression(sqrt(abs(`Standardized residuals`)))), |
785 | ! |
title = "Scale-Location" |
786 |
) |
|
787 |
) |
|
788 |
), |
|
789 | ! |
ggtheme = input$ggtheme |
790 |
) |
|
791 | ||
792 | ! |
teal.code::eval_code( |
793 | ! |
plot_base, |
794 | ! |
substitute( |
795 | ! |
expr = { |
796 | ! |
smoothy <- smooth(data$.fitted, sqrt(abs(data$.stdresid))) |
797 | ! |
plot <- graph |
798 |
}, |
|
799 | ! |
env = list( |
800 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
801 |
) |
|
802 |
) |
|
803 |
) |
|
804 |
}) |
|
805 | ||
806 | ! |
output_plot_4 <- reactive({ |
807 | ! |
shinyjs::hide("size") |
808 | ! |
shinyjs::show("alpha") |
809 | ! |
plot_base <- output_plot_base() |
810 | ! |
plot <- substitute( |
811 | ! |
expr = ggplot(data = data, aes(seq_along(.cooksd), .cooksd)) + |
812 | ! |
geom_col(alpha = alpha), |
813 | ! |
env = list(alpha = input$alpha) |
814 |
) |
|
815 | ! |
if (input$show_outlier) { |
816 | ! |
plot <- substitute( |
817 | ! |
expr = plot + |
818 | ! |
geom_hline( |
819 | ! |
yintercept = c( |
820 | ! |
outlier * mean(data$.cooksd, na.rm = TRUE), |
821 | ! |
mean(data$.cooksd, na.rm = TRUE) |
822 |
), |
|
823 | ! |
color = "red", |
824 | ! |
linetype = "dashed" |
825 |
) + |
|
826 | ! |
geom_text( |
827 | ! |
aes( |
828 | ! |
x = 0, |
829 | ! |
y = mean(data$.cooksd, na.rm = TRUE), |
830 | ! |
label = paste("mu", "=", round(mean(data$.cooksd, na.rm = TRUE), 4)), |
831 | ! |
vjust = -1, |
832 | ! |
hjust = 0, |
833 | ! |
color = "red", |
834 | ! |
angle = 90 |
835 |
), |
|
836 | ! |
parse = TRUE, |
837 | ! |
show.legend = FALSE |
838 |
) + |
|
839 | ! |
outlier_label, |
840 | ! |
env = list(plot = plot, outlier = input$outlier, outlier_label = outlier_label()) |
841 |
) |
|
842 |
} |
|
843 | ||
844 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
845 | ! |
teal.widgets::resolve_ggplot2_args( |
846 | ! |
user_plot = ggplot2_args[["Cook's distance"]], |
847 | ! |
user_default = ggplot2_args$default, |
848 | ! |
module_plot = teal.widgets::ggplot2_args( |
849 | ! |
labs = list( |
850 | ! |
x = quote(paste0("Obs. number\nlm(", reg_form, ")")), |
851 | ! |
y = "Cook's distance", |
852 | ! |
title = "Cook's distance" |
853 |
) |
|
854 |
) |
|
855 |
), |
|
856 | ! |
ggtheme = input$ggtheme |
857 |
) |
|
858 | ||
859 | ! |
teal.code::eval_code( |
860 | ! |
plot_base, |
861 | ! |
substitute( |
862 | ! |
expr = { |
863 | ! |
plot <- graph |
864 |
}, |
|
865 | ! |
env = list( |
866 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
867 |
) |
|
868 |
) |
|
869 |
) |
|
870 |
}) |
|
871 | ||
872 | ! |
output_plot_5 <- reactive({ |
873 | ! |
shinyjs::show("size") |
874 | ! |
shinyjs::show("alpha") |
875 | ! |
plot_base <- output_plot_base() |
876 | ! |
plot <- substitute( |
877 | ! |
expr = ggplot(data = data, aes(.hat, .stdresid)) + |
878 | ! |
geom_vline( |
879 | ! |
size = 1, |
880 | ! |
colour = "black", |
881 | ! |
linetype = "dashed", |
882 | ! |
xintercept = 0 |
883 |
) + |
|
884 | ! |
geom_hline( |
885 | ! |
size = 1, |
886 | ! |
colour = "black", |
887 | ! |
linetype = "dashed", |
888 | ! |
yintercept = 0 |
889 |
) + |
|
890 | ! |
geom_point(size = size, alpha = alpha) + |
891 | ! |
geom_line(data = smoothy, mapping = smoothy_aes), |
892 | ! |
env = list(size = input$size, alpha = input$alpha) |
893 |
) |
|
894 | ! |
if (input$show_outlier) { |
895 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
896 |
} |
|
897 | ||
898 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
899 | ! |
teal.widgets::resolve_ggplot2_args( |
900 | ! |
user_plot = ggplot2_args[["Residuals vs Leverage"]], |
901 | ! |
user_default = ggplot2_args$default, |
902 | ! |
module_plot = teal.widgets::ggplot2_args( |
903 | ! |
labs = list( |
904 | ! |
x = quote(paste0("Standardized residuals\nlm(", reg_form, ")")), |
905 | ! |
y = "Leverage", |
906 | ! |
title = "Residuals vs Leverage" |
907 |
) |
|
908 |
) |
|
909 |
), |
|
910 | ! |
ggtheme = input$ggtheme |
911 |
) |
|
912 | ||
913 | ! |
teal.code::eval_code( |
914 | ! |
plot_base, |
915 | ! |
substitute( |
916 | ! |
expr = { |
917 | ! |
smoothy <- smooth(data$.hat, data$.stdresid) |
918 | ! |
plot <- graph |
919 |
}, |
|
920 | ! |
env = list( |
921 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
922 |
) |
|
923 |
) |
|
924 |
) |
|
925 |
}) |
|
926 | ||
927 | ! |
output_plot_6 <- reactive({ |
928 | ! |
shinyjs::show("size") |
929 | ! |
shinyjs::show("alpha") |
930 | ! |
plot_base <- output_plot_base() |
931 | ! |
plot <- substitute( |
932 | ! |
expr = ggplot(data = data, aes(.hat, .cooksd)) + |
933 | ! |
geom_vline(xintercept = 0, colour = NA) + |
934 | ! |
geom_abline( |
935 | ! |
slope = seq(0, 3, by = 0.5), |
936 | ! |
colour = "black", |
937 | ! |
linetype = "dashed", |
938 | ! |
size = 1 |
939 |
) + |
|
940 | ! |
geom_line(data = smoothy, mapping = smoothy_aes) + |
941 | ! |
geom_point(size = size, alpha = alpha), |
942 | ! |
env = list(size = input$size, alpha = input$alpha) |
943 |
) |
|
944 | ! |
if (input$show_outlier) { |
945 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
946 |
} |
|
947 | ||
948 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
949 | ! |
teal.widgets::resolve_ggplot2_args( |
950 | ! |
user_plot = ggplot2_args[["Cook's dist vs Leverage"]], |
951 | ! |
user_default = ggplot2_args$default, |
952 | ! |
module_plot = teal.widgets::ggplot2_args( |
953 | ! |
labs = list( |
954 | ! |
x = quote(paste0("Leverage\nlm(", reg_form, ")")), |
955 | ! |
y = "Cooks's distance", |
956 | ! |
title = "Cook's dist vs Leverage" |
957 |
) |
|
958 |
) |
|
959 |
), |
|
960 | ! |
ggtheme = input$ggtheme |
961 |
) |
|
962 | ||
963 | ! |
teal.code::eval_code( |
964 | ! |
plot_base, |
965 | ! |
substitute( |
966 | ! |
expr = { |
967 | ! |
smoothy <- smooth(data$.hat, data$.cooksd) |
968 | ! |
plot <- graph |
969 |
}, |
|
970 | ! |
env = list( |
971 | ! |
graph = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
972 |
) |
|
973 |
) |
|
974 |
) |
|
975 |
}) |
|
976 | ||
977 | ! |
output_q <- reactive({ |
978 | ! |
teal::validate_inputs(iv_r()) |
979 | ! |
switch(input$plot_type, |
980 | ! |
"Response vs Regressor" = output_plot_0(), |
981 | ! |
"Residuals vs Fitted" = output_plot_1(), |
982 | ! |
"Normal Q-Q" = output_plot_2(), |
983 | ! |
"Scale-Location" = output_plot_3(), |
984 | ! |
"Cook's distance" = output_plot_4(), |
985 | ! |
"Residuals vs Leverage" = output_plot_5(), |
986 | ! |
"Cook's dist vs Leverage" = output_plot_6() |
987 |
) |
|
988 |
}) |
|
989 | ||
990 | ! |
decorated_output_q <- srv_decorate_teal_data( |
991 | ! |
"decorator", |
992 | ! |
data = output_q, |
993 | ! |
decorators = select_decorators(decorators, "plot"), |
994 | ! |
expr = print(plot) |
995 |
) |
|
996 | ||
997 | ! |
fitted <- reactive({ |
998 | ! |
req(output_q()) |
999 | ! |
decorated_output_q()[["fit"]] |
1000 |
}) |
|
1001 | ! |
plot_r <- reactive({ |
1002 | ! |
req(output_q()) |
1003 | ! |
decorated_output_q()[["plot"]] |
1004 |
}) |
|
1005 | ||
1006 |
# Insert the plot into a plot_with_settings module from teal.widgets |
|
1007 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
1008 | ! |
id = "myplot", |
1009 | ! |
plot_r = plot_r, |
1010 | ! |
height = plot_height, |
1011 | ! |
width = plot_width |
1012 |
) |
|
1013 | ||
1014 | ! |
output$text <- renderText({ |
1015 | ! |
req(iv_r()$is_valid()) |
1016 | ! |
req(iv_out$is_valid()) |
1017 | ! |
paste(utils::capture.output(summary(teal.code::dev_suppress(fitted())))[-1], |
1018 | ! |
collapse = "\n" |
1019 |
) |
|
1020 |
}) |
|
1021 | ||
1022 |
# Render R code. |
|
1023 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_output_q()))) |
1024 | ||
1025 | ! |
teal.widgets::verbatim_popup_srv( |
1026 | ! |
id = "rcode", |
1027 | ! |
verbatim_content = source_code_r, |
1028 | ! |
title = "R code for the regression plot", |
1029 |
) |
|
1030 | ||
1031 |
### REPORTER |
|
1032 | ! |
if (with_reporter) { |
1033 | ! |
card_fun <- function(comment, label) { |
1034 | ! |
card <- teal::report_card_template( |
1035 | ! |
title = "Linear Regression Plot", |
1036 | ! |
label = label, |
1037 | ! |
with_filter = with_filter, |
1038 | ! |
filter_panel_api = filter_panel_api |
1039 |
) |
|
1040 | ! |
card$append_text("Plot", "header3") |
1041 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
1042 | ! |
if (!comment == "") { |
1043 | ! |
card$append_text("Comment", "header3") |
1044 | ! |
card$append_text(comment) |
1045 |
} |
|
1046 | ! |
card$append_src(source_code_r()) |
1047 | ! |
card |
1048 |
} |
|
1049 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
1050 |
} |
|
1051 |
### |
|
1052 |
}) |
|
1053 |
} |
1 |
#' Shared parameters documentation |
|
2 |
#' |
|
3 |
#' Defines common arguments shared across multiple functions in the package |
|
4 |
#' to avoid repetition by using `inheritParams`. |
|
5 |
#' |
|
6 |
#' @param plot_height (`numeric`) optional, specifies the plot height as a three-element vector of |
|
7 |
#' `value`, `min`, and `max` intended for use with a slider UI element. |
|
8 |
#' @param plot_width (`numeric`) optional, specifies the plot width as a three-element vector of |
|
9 |
#' `value`, `min`, and `max` for a slider encoding the plot width. |
|
10 |
#' @param rotate_xaxis_labels (`logical`) optional, whether to rotate plot X axis labels. Does not |
|
11 |
#' rotate by default (`FALSE`). |
|
12 |
#' @param ggtheme (`character`) optional, `ggplot2` theme to be used by default. Defaults to `"gray"`. |
|
13 |
#' @param ggplot2_args (`ggplot2_args`) object created by [teal.widgets::ggplot2_args()] |
|
14 |
#' with settings for the module plot. |
|
15 |
#' The argument is merged with options variable `teal.ggplot2_args` and default module setup. |
|
16 |
#' |
|
17 |
#' For more details see the vignette: `vignette("custom-ggplot2-arguments", package = "teal.widgets")` |
|
18 |
#' @param basic_table_args (`basic_table_args`) object created by [teal.widgets::basic_table_args()] |
|
19 |
#' with settings for the module table. |
|
20 |
#' The argument is merged with options variable `teal.basic_table_args` and default module setup. |
|
21 |
#' |
|
22 |
#' For more details see the vignette: `vignette("custom-basic-table-arguments", package = "teal.widgets")` |
|
23 |
#' @param pre_output (`shiny.tag`) optional, text or UI element to be displayed before the module's output, |
|
24 |
#' providing context or a title. |
|
25 |
#' with text placed before the output to put the output into context. For example a title. |
|
26 |
#' @param post_output (`shiny.tag`) optional, text or UI element to be displayed after the module's output, |
|
27 |
#' adding context or further instructions. Elements like `shiny::helpText()` are useful. |
|
28 |
#' @param alpha (`integer(1)` or `integer(3)`) optional, specifies point opacity. |
|
29 |
#' - When the length of `alpha` is one: the plot points will have a fixed opacity. |
|
30 |
#' - When the length of `alpha` is three: the plot points opacity are dynamically adjusted based on |
|
31 |
#' vector of `value`, `min`, and `max`. |
|
32 |
#' @param size (`integer(1)` or `integer(3)`) optional, specifies point size. |
|
33 |
#' - When the length of `size` is one: the plot point sizes will have a fixed size. |
|
34 |
#' - When the length of `size` is three: the plot points size are dynamically adjusted based on |
|
35 |
#' vector of `value`, `min`, and `max`. |
|
36 |
#' @param decorators `r lifecycle::badge("experimental")` |
|
37 |
#' (`list` of `teal_transform_module`, named `list` of `teal_transform_module`) optional, |
|
38 |
#' decorator for tables or plots included in the module output reported. |
|
39 |
#' When a named list of `teal_transform_module`, the decorators are applied to the respective output objects. |
|
40 |
#' |
|
41 |
#' Otherwise, the decorators are applied to all objects, which is equivalent as using the name `default`. |
|
42 |
#' |
|
43 |
#' See section "Decorating Module" below for more details. |
|
44 |
#' |
|
45 |
#' @return Object of class `teal_module` to be used in `teal` applications. |
|
46 |
#' |
|
47 |
#' @name shared_params |
|
48 |
#' @keywords internal |
|
49 |
NULL |
|
50 | ||
51 |
#' Add labels for facets to a `ggplot2` object |
|
52 |
#' |
|
53 |
#' Enhances a `ggplot2` plot by adding labels that describe |
|
54 |
#' the faceting variables along the x and y axes. |
|
55 |
#' |
|
56 |
#' @param p (`ggplot2`) object to which facet labels will be added. |
|
57 |
#' @param xfacet_label (`character`) Label for the facet along the x-axis. |
|
58 |
#' If `NULL`, no label is added. If a vector, labels are joined with " & ". |
|
59 |
#' @param yfacet_label (`character`) Label for the facet along the y-axis. |
|
60 |
#' Similar behavior to `xfacet_label`. |
|
61 |
#' |
|
62 |
#' @return Returns `grid` or `grob` object (to be drawn with `grid.draw`) |
|
63 |
#' |
|
64 |
#' @examples |
|
65 |
#' library(ggplot2) |
|
66 |
#' library(grid) |
|
67 |
#' |
|
68 |
#' p <- ggplot(mtcars) + |
|
69 |
#' aes(x = mpg, y = disp) + |
|
70 |
#' geom_point() + |
|
71 |
#' facet_grid(gear ~ cyl) |
|
72 |
#' |
|
73 |
#' xfacet_label <- "cylinders" |
|
74 |
#' yfacet_label <- "gear" |
|
75 |
#' res <- add_facet_labels(p, xfacet_label, yfacet_label) |
|
76 |
#' grid.newpage() |
|
77 |
#' grid.draw(res) |
|
78 |
#' |
|
79 |
#' grid.newpage() |
|
80 |
#' grid.draw(add_facet_labels(p, xfacet_label = NULL, yfacet_label)) |
|
81 |
#' grid.newpage() |
|
82 |
#' grid.draw(add_facet_labels(p, xfacet_label, yfacet_label = NULL)) |
|
83 |
#' grid.newpage() |
|
84 |
#' grid.draw(add_facet_labels(p, xfacet_label = NULL, yfacet_label = NULL)) |
|
85 |
#' |
|
86 |
#' @export |
|
87 |
#' |
|
88 |
add_facet_labels <- function(p, xfacet_label = NULL, yfacet_label = NULL) { |
|
89 | ! |
checkmate::assert_class(p, classes = "ggplot") |
90 | ! |
checkmate::assert_character(xfacet_label, null.ok = TRUE, min.len = 1) |
91 | ! |
checkmate::assert_character(yfacet_label, null.ok = TRUE, min.len = 1) |
92 | ! |
if (is.null(xfacet_label) && is.null(yfacet_label)) { |
93 | ! |
return(ggplotGrob(p)) |
94 |
} |
|
95 | ! |
grid::grid.grabExpr({ |
96 | ! |
g <- ggplotGrob(p) |
97 | ||
98 |
# we are going to replace these, so we make sure they have nothing in them |
|
99 | ! |
checkmate::assert_class(g$grobs[[grep("xlab-t", g$layout$name, fixed = TRUE)]], "zeroGrob") |
100 | ! |
checkmate::assert_class(g$grobs[[grep("ylab-r", g$layout$name, fixed = TRUE)]], "zeroGrob") |
101 | ||
102 | ! |
xaxis_label_grob <- g$grobs[[grep("xlab-b", g$layout$name, fixed = TRUE)]] |
103 | ! |
xaxis_label_grob$children[[1]]$label <- paste(xfacet_label, collapse = " & ") |
104 | ! |
yaxis_label_grob <- g$grobs[[grep("ylab-l", g$layout$name, fixed = TRUE)]] |
105 | ! |
yaxis_label_grob$children[[1]]$label <- paste(yfacet_label, collapse = " & ") |
106 | ! |
yaxis_label_grob$children[[1]]$rot <- 270 |
107 | ||
108 | ! |
top_height <- if (is.null(xfacet_label)) 0 else grid::unit(2, "line") |
109 | ! |
right_width <- if (is.null(yfacet_label)) 0 else grid::unit(2, "line") |
110 | ||
111 | ! |
grid::grid.newpage() |
112 | ! |
grid::pushViewport(grid::plotViewport(margins = c(0, 0, top_height, right_width), name = "ggplot")) |
113 | ! |
grid::grid.draw(g) |
114 | ! |
grid::upViewport(1) |
115 | ||
116 |
# draw x facet |
|
117 | ! |
if (!is.null(xfacet_label)) { |
118 | ! |
grid::pushViewport(grid::viewport( |
119 | ! |
x = 0, y = grid::unit(1, "npc") - top_height, width = grid::unit(1, "npc"), |
120 | ! |
height = top_height, just = c("left", "bottom"), name = "topxaxis" |
121 |
)) |
|
122 | ! |
grid::grid.draw(xaxis_label_grob) |
123 | ! |
grid::upViewport(1) |
124 |
} |
|
125 | ||
126 |
# draw y facet |
|
127 | ! |
if (!is.null(yfacet_label)) { |
128 | ! |
grid::pushViewport(grid::viewport( |
129 | ! |
x = grid::unit(1, "npc") - grid::unit(as.numeric(right_width) / 2, "line"), y = 0, width = right_width, |
130 | ! |
height = grid::unit(1, "npc"), just = c("left", "bottom"), name = "rightyaxis" |
131 |
)) |
|
132 | ! |
grid::grid.draw(yaxis_label_grob) |
133 | ! |
grid::upViewport(1) |
134 |
} |
|
135 |
}) |
|
136 |
} |
|
137 | ||
138 |
#' Call a function with a character vector for the `...` argument |
|
139 |
#' |
|
140 |
#' @param fun (`character`) Name of a function where the `...` argument shall be replaced by values from `str_args`. |
|
141 |
#' @param str_args (`character`) A character vector that the function shall be executed with |
|
142 |
#' |
|
143 |
#' @return |
|
144 |
#' Value of call to `fun` with arguments specified in `str_args`. |
|
145 |
#' |
|
146 |
#' @keywords internal |
|
147 |
call_fun_dots <- function(fun, str_args) { |
|
148 | ! |
do.call("call", c(list(fun), lapply(str_args, as.name)), quote = TRUE) |
149 |
} |
|
150 | ||
151 |
#' Generate a string for a variable including its label |
|
152 |
#' |
|
153 |
#' @param var_names (`character`) Name of variable to extract labels from. |
|
154 |
#' @param dataset (`dataset`) Name of analysis dataset. |
|
155 |
#' @param prefix,suffix (`character`) String to paste to the beginning/end of the variable name with label. |
|
156 |
#' @param wrap_width (`numeric`) Number of characters to wrap original label to. Defaults to 80. |
|
157 |
#' |
|
158 |
#' @return (`character`) String with variable name and label. |
|
159 |
#' |
|
160 |
#' @keywords internal |
|
161 |
#' |
|
162 |
varname_w_label <- function(var_names, |
|
163 |
dataset, |
|
164 |
wrap_width = 80, |
|
165 |
prefix = NULL, |
|
166 |
suffix = NULL) { |
|
167 | ! |
add_label <- function(var_names) { |
168 | ! |
label <- vapply( |
169 | ! |
dataset[var_names], function(x) { |
170 | ! |
attr_label <- attr(x, "label") |
171 | ! |
`if`(is.null(attr_label), "", attr_label) |
172 |
}, |
|
173 | ! |
character(1) |
174 |
) |
|
175 | ||
176 | ! |
if (length(label) == 1 && !is.na(label) && !identical(label, "")) { |
177 | ! |
paste0(prefix, label, " [", var_names, "]", suffix) |
178 |
} else { |
|
179 | ! |
var_names |
180 |
} |
|
181 |
} |
|
182 | ||
183 | ! |
if (length(var_names) < 1) { |
184 | ! |
NULL |
185 | ! |
} else if (length(var_names) == 1) { |
186 | ! |
stringr::str_wrap(add_label(var_names), width = wrap_width) |
187 | ! |
} else if (length(var_names) > 1) { |
188 | ! |
stringr::str_wrap(vapply(var_names, add_label, character(1)), width = wrap_width) |
189 |
} |
|
190 |
} |
|
191 | ||
192 |
# see vignette("ggplot2-specs", package="ggplot2") |
|
193 |
shape_names <- c( |
|
194 |
"circle", paste("circle", c("open", "filled", "cross", "plus", "small")), "bullet", |
|
195 |
"square", paste("square", c("open", "filled", "cross", "plus", "triangle")), |
|
196 |
"diamond", paste("diamond", c("open", "filled", "plus")), |
|
197 |
"triangle", paste("triangle", c("open", "filled", "square")), |
|
198 |
paste("triangle down", c("open", "filled")), |
|
199 |
"plus", "cross", "asterisk" |
|
200 |
) |
|
201 | ||
202 |
#' Get icons to represent variable types in dataset |
|
203 |
#' |
|
204 |
#' @param var_type (`character`) of R internal types (classes). |
|
205 |
#' @return (`character`) vector of HTML icons corresponding to data type in each column. |
|
206 |
#' @keywords internal |
|
207 |
variable_type_icons <- function(var_type) { |
|
208 | ! |
checkmate::assert_character(var_type, any.missing = FALSE) |
209 | ||
210 | ! |
class_to_icon <- list( |
211 | ! |
numeric = "arrow-up-1-9", |
212 | ! |
integer = "arrow-up-1-9", |
213 | ! |
logical = "pause", |
214 | ! |
Date = "calendar", |
215 | ! |
POSIXct = "calendar", |
216 | ! |
POSIXlt = "calendar", |
217 | ! |
factor = "chart-bar", |
218 | ! |
character = "keyboard", |
219 | ! |
primary_key = "key", |
220 | ! |
unknown = "circle-question" |
221 |
) |
|
222 | ! |
class_to_icon <- lapply(class_to_icon, function(icon_name) toString(icon(icon_name, lib = "font-awesome"))) |
223 | ||
224 | ! |
unname(vapply( |
225 | ! |
var_type, |
226 | ! |
FUN.VALUE = character(1), |
227 | ! |
FUN = function(class) { |
228 | ! |
if (class == "") { |
229 | ! |
class |
230 | ! |
} else if (is.null(class_to_icon[[class]])) { |
231 | ! |
class_to_icon[["unknown"]] |
232 |
} else { |
|
233 | ! |
class_to_icon[[class]] |
234 |
} |
|
235 |
} |
|
236 |
)) |
|
237 |
} |
|
238 | ||
239 |
#' Include `CSS` files from `/inst/css/` package directory to application header |
|
240 |
#' |
|
241 |
#' `system.file` should not be used to access files in other packages, it does |
|
242 |
#' not work with `devtools`. Therefore, we redefine this method in each package |
|
243 |
#' as needed. Thus, we do not export this method |
|
244 |
#' |
|
245 |
#' @param pattern (`character`) optional, regular expression to match the file names to be included. |
|
246 |
#' |
|
247 |
#' @return HTML code that includes `CSS` files. |
|
248 |
#' @keywords internal |
|
249 |
#' |
|
250 |
include_css_files <- function(pattern = "*") { |
|
251 | ! |
css_files <- list.files( |
252 | ! |
system.file("css", package = "teal.modules.general", mustWork = TRUE), |
253 | ! |
pattern = pattern, full.names = TRUE |
254 |
) |
|
255 | ! |
if (length(css_files) == 0) { |
256 | ! |
return(NULL) |
257 |
} |
|
258 | ! |
singleton(tags$head(lapply(css_files, includeCSS))) |
259 |
} |
|
260 | ||
261 |
#' JavaScript condition to check if a specific tab is active |
|
262 |
#' |
|
263 |
#' @param id (`character(1)`) the id of the tab panel with tabs. |
|
264 |
#' @param name (`character(1)`) the name of the tab. |
|
265 |
#' @return JavaScript expression to be used in `shiny::conditionalPanel()` to determine |
|
266 |
#' if the specified tab is active. |
|
267 |
#' @keywords internal |
|
268 |
#' |
|
269 |
is_tab_active_js <- function(id, name) { |
|
270 |
# supporting the bs3 and higher version at the same time |
|
271 | ! |
sprintf( |
272 | ! |
"$(\"#%1$s > li.active\").text().trim() == '%2$s' || $(\"#%1$s > li a.active\").text().trim() == '%2$s'", |
273 | ! |
id, name |
274 |
) |
|
275 |
} |
|
276 | ||
277 |
#' Assert single selection on `data_extract_spec` object |
|
278 |
#' Helper to reduce code in assertions |
|
279 |
#' @noRd |
|
280 |
#' |
|
281 |
assert_single_selection <- function(x, |
|
282 |
.var.name = checkmate::vname(x)) { # nolint: object_name. |
|
283 | 104x |
if (any(vapply(x, function(.x) .x$select$multiple, logical(1)))) { |
284 | 4x |
stop("'", .var.name, "' should not allow multiple selection") |
285 |
} |
|
286 | 100x |
invisible(TRUE) |
287 |
} |
|
288 | ||
289 |
#' Wrappers around `srv_transform_teal_data` that allows to decorate the data |
|
290 |
#' @inheritParams teal::srv_transform_teal_data |
|
291 |
#' @param expr (`expression` or `reactive`) to evaluate on the output of the decoration. |
|
292 |
#' When an expression it must be inline code. See [within()] |
|
293 |
#' Default is `NULL` which won't evaluate any appending code. |
|
294 |
#' @param expr_is_reactive (`logical(1)`) whether `expr` is a reactive expression |
|
295 |
#' that skips defusing the argument. |
|
296 |
#' @details |
|
297 |
#' `srv_decorate_teal_data` is a wrapper around `srv_transform_teal_data` that |
|
298 |
#' allows to decorate the data with additional expressions. |
|
299 |
#' When original `teal_data` object is in error state, it will show that error |
|
300 |
#' first. |
|
301 |
#' |
|
302 |
#' @keywords internal |
|
303 |
srv_decorate_teal_data <- function(id, data, decorators, expr, expr_is_reactive = FALSE) { |
|
304 | ! |
checkmate::assert_class(data, classes = "reactive") |
305 | ! |
checkmate::assert_list(decorators, "teal_transform_module") |
306 | ! |
checkmate::assert_flag(expr_is_reactive) |
307 | ||
308 | ! |
missing_expr <- missing(expr) |
309 | ! |
if (!missing_expr && !expr_is_reactive) { |
310 | ! |
expr <- dplyr::enexpr(expr) # Using dplyr re-export to avoid adding rlang to Imports |
311 |
} |
|
312 | ||
313 | ! |
moduleServer(id, function(input, output, session) { |
314 | ! |
decorated_output <- srv_transform_teal_data("inner", data = data, transformators = decorators) |
315 | ||
316 | ! |
reactive({ |
317 | ! |
data_out <- try(data(), silent = TRUE) |
318 | ! |
if (inherits(data_out, "qenv.error")) { |
319 | ! |
data() |
320 |
} else { |
|
321 |
# ensure original errors are displayed and `eval_code` is never executed with NULL |
|
322 | ! |
req(data(), decorated_output()) |
323 | ! |
if (missing_expr) { |
324 | ! |
decorated_output() |
325 | ! |
} else if (expr_is_reactive) { |
326 | ! |
teal.code::eval_code(decorated_output(), expr()) |
327 |
} else { |
|
328 | ! |
teal.code::eval_code(decorated_output(), expr) |
329 |
} |
|
330 |
} |
|
331 |
}) |
|
332 |
}) |
|
333 |
} |
|
334 | ||
335 |
#' @rdname srv_decorate_teal_data |
|
336 |
#' @details |
|
337 |
#' `ui_decorate_teal_data` is a wrapper around `ui_transform_teal_data`. |
|
338 |
#' @keywords internal |
|
339 |
ui_decorate_teal_data <- function(id, decorators, ...) { |
|
340 | ! |
teal::ui_transform_teal_data(NS(id, "inner"), transformators = decorators, ...) |
341 |
} |
|
342 | ||
343 |
#' Internal function to check if decorators is a valid object |
|
344 |
#' @noRd |
|
345 |
check_decorators <- function(x, names = NULL) { # nolint: object_name. |
|
346 | ||
347 | 5x |
check_message <- checkmate::check_list(x, names = "named") |
348 | ||
349 | 5x |
if (!is.null(names)) { |
350 | 5x |
if (isTRUE(check_message)) { |
351 | 5x |
if (length(names(x)) != length(unique(names(x)))) { |
352 | ! |
check_message <- sprintf( |
353 | ! |
"The `decorators` must contain unique names from these names: %s.", |
354 | ! |
paste(names, collapse = ", ") |
355 |
) |
|
356 |
} |
|
357 |
} else { |
|
358 | ! |
check_message <- sprintf( |
359 | ! |
"The `decorators` must be a named list from these names: %s.", |
360 | ! |
paste(names, collapse = ", ") |
361 |
) |
|
362 |
} |
|
363 |
} |
|
364 | ||
365 | 5x |
if (!isTRUE(check_message)) { |
366 | ! |
return(check_message) |
367 |
} |
|
368 | ||
369 | 5x |
valid_elements <- vapply( |
370 | 5x |
x, |
371 | 5x |
checkmate::test_class, |
372 | 5x |
classes = "teal_transform_module", |
373 | 5x |
FUN.VALUE = logical(1L) |
374 |
) |
|
375 | ||
376 | 5x |
if (all(valid_elements)) { |
377 | 5x |
return(TRUE) |
378 |
} |
|
379 | ||
380 | ! |
"Make sure that the named list contains 'teal_transform_module' objects created using `teal_transform_module()`." |
381 |
} |
|
382 |
#' Internal assertion on decorators |
|
383 |
#' @noRd |
|
384 |
assert_decorators <- checkmate::makeAssertionFunction(check_decorators) |
|
385 | ||
386 |
#' Subset decorators based on the scope |
|
387 |
#' |
|
388 |
#' @param scope (`character`) a character vector of decorator names to include. |
|
389 |
#' @param decorators (named `list`) of list decorators to subset. |
|
390 |
#' |
|
391 |
#' @return Subsetted list with all decorators to include. |
|
392 |
#' It can be an empty list if none of the scope exists in `decorators` argument. |
|
393 |
#' @keywords internal |
|
394 |
select_decorators <- function(decorators, scope) { |
|
395 | ! |
checkmate::assert_character(scope, null.ok = TRUE) |
396 | ! |
if (scope %in% names(decorators)) { |
397 | ! |
decorators[scope] |
398 |
} else { |
|
399 | ! |
list() |
400 |
} |
|
401 |
} |
1 |
#' `teal` module: Data table viewer |
|
2 |
#' |
|
3 |
#' Module provides a dynamic and interactive way to view `data.frame`s in a `teal` application. |
|
4 |
#' It uses the `DT` package to display data tables in a paginated, searchable, and sortable format, |
|
5 |
#' which helps to enhance data exploration and analysis. |
|
6 |
#' |
|
7 |
#' The `DT` package has an option `DT.TOJSON_ARGS` to show `Inf` and `NA` in data tables. |
|
8 |
#' Configure the `DT.TOJSON_ARGS` option via |
|
9 |
#' `options(DT.TOJSON_ARGS = list(na = "string"))` before running the module. |
|
10 |
#' Note though that sorting of numeric columns with `NA`/`Inf` will be lexicographic not numerical. |
|
11 |
#' |
|
12 |
#' @inheritParams teal::module |
|
13 |
#' @inheritParams shared_params |
|
14 |
#' @param variables_selected (`named list`) Character vectors of the variables (i.e. columns) |
|
15 |
#' which should be initially shown for each dataset. |
|
16 |
#' Names of list elements should correspond to the names of the datasets available in the app. |
|
17 |
#' If no entry is specified for a dataset, the first six variables from that |
|
18 |
#' dataset will initially be shown. |
|
19 |
#' @param datasets_selected (`character`) `r lifecycle::badge("deprecated")` A vector of datasets which should be |
|
20 |
#' shown and in what order. Use `datanames` instead. |
|
21 |
#' @param dt_args (`named list`) Additional arguments to be passed to [DT::datatable()] |
|
22 |
#' (must not include `data` or `options`). |
|
23 |
#' @param dt_options (`named list`) The `options` argument to `DT::datatable`. By default |
|
24 |
#' `list(searching = FALSE, pageLength = 30, lengthMenu = c(5, 15, 30, 100), scrollX = TRUE)` |
|
25 |
#' @param server_rendering (`logical`) should the data table be rendered server side |
|
26 |
#' (see `server` argument of [DT::renderDataTable()]) |
|
27 |
#' |
|
28 |
#' @inherit shared_params return |
|
29 |
#' |
|
30 |
#' @examplesShinylive |
|
31 |
#' library(teal.modules.general) |
|
32 |
#' interactive <- function() TRUE |
|
33 |
#' {{ next_example }} |
|
34 |
#' @examples |
|
35 |
#' # general data example |
|
36 |
#' data <- teal_data() |
|
37 |
#' data <- within(data, { |
|
38 |
#' require(nestcolor) |
|
39 |
#' iris <- iris |
|
40 |
#' }) |
|
41 |
#' |
|
42 |
#' app <- init( |
|
43 |
#' data = data, |
|
44 |
#' modules = modules( |
|
45 |
#' tm_data_table( |
|
46 |
#' variables_selected = list( |
|
47 |
#' iris = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species") |
|
48 |
#' ), |
|
49 |
#' dt_args = list(caption = "IRIS Table Caption") |
|
50 |
#' ) |
|
51 |
#' ) |
|
52 |
#' ) |
|
53 |
#' if (interactive()) { |
|
54 |
#' shinyApp(app$ui, app$server) |
|
55 |
#' } |
|
56 |
#' |
|
57 |
#' @examplesShinylive |
|
58 |
#' library(teal.modules.general) |
|
59 |
#' interactive <- function() TRUE |
|
60 |
#' {{ next_example }} |
|
61 |
#' @examples |
|
62 |
#' # CDISC data example |
|
63 |
#' data <- teal_data() |
|
64 |
#' data <- within(data, { |
|
65 |
#' require(nestcolor) |
|
66 |
#' ADSL <- teal.data::rADSL |
|
67 |
#' }) |
|
68 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
69 |
#' |
|
70 |
#' app <- init( |
|
71 |
#' data = data, |
|
72 |
#' modules = modules( |
|
73 |
#' tm_data_table( |
|
74 |
#' variables_selected = list(ADSL = c("STUDYID", "USUBJID", "SUBJID", "SITEID", "AGE", "SEX")), |
|
75 |
#' dt_args = list(caption = "ADSL Table Caption") |
|
76 |
#' ) |
|
77 |
#' ) |
|
78 |
#' ) |
|
79 |
#' if (interactive()) { |
|
80 |
#' shinyApp(app$ui, app$server) |
|
81 |
#' } |
|
82 |
#' |
|
83 |
#' @export |
|
84 |
#' |
|
85 |
tm_data_table <- function(label = "Data Table", |
|
86 |
variables_selected = list(), |
|
87 |
datasets_selected = deprecated(), |
|
88 |
datanames = if (missing(datasets_selected)) "all" else datasets_selected, |
|
89 |
dt_args = list(), |
|
90 |
dt_options = list( |
|
91 |
searching = FALSE, |
|
92 |
pageLength = 30, |
|
93 |
lengthMenu = c(5, 15, 30, 100), |
|
94 |
scrollX = TRUE |
|
95 |
), |
|
96 |
server_rendering = FALSE, |
|
97 |
pre_output = NULL, |
|
98 |
post_output = NULL, |
|
99 |
transformators = list()) { |
|
100 | ! |
message("Initializing tm_data_table") |
101 | ||
102 |
# Start of assertions |
|
103 | ! |
checkmate::assert_string(label) |
104 | ||
105 | ! |
checkmate::assert_list(variables_selected, min.len = 0, types = "character", names = "named") |
106 | ! |
if (length(variables_selected) > 0) { |
107 | ! |
lapply(seq_along(variables_selected), function(i) { |
108 | ! |
checkmate::assert_character(variables_selected[[i]], min.chars = 1, min.len = 1) |
109 | ! |
if (!is.null(names(variables_selected[[i]]))) { |
110 | ! |
checkmate::assert_names(names(variables_selected[[i]])) |
111 |
} |
|
112 |
}) |
|
113 |
} |
|
114 | ! |
if (!missing(datasets_selected)) { |
115 | ! |
lifecycle::deprecate_soft( |
116 | ! |
when = "0.4.0", |
117 | ! |
what = "tm_data_table(datasets_selected)", |
118 | ! |
with = "tm_data_table(datanames)", |
119 | ! |
details = 'Use tm_data_table(datanames = "all") to keep the previous behavior and avoid this warning.', |
120 |
) |
|
121 |
} |
|
122 | ! |
checkmate::assert_character(datanames, min.len = 0, min.chars = 1, null.ok = TRUE) |
123 | ! |
checkmate::assert( |
124 | ! |
checkmate::check_list(dt_args, len = 0), |
125 | ! |
checkmate::check_subset(names(dt_args), choices = names(formals(DT::datatable))) |
126 |
) |
|
127 | ! |
checkmate::assert_list(dt_options, names = "named") |
128 | ! |
checkmate::assert_flag(server_rendering) |
129 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
130 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
131 | ||
132 |
# End of assertions |
|
133 | ||
134 | ! |
ans <- module( |
135 | ! |
label, |
136 | ! |
server = srv_page_data_table, |
137 | ! |
ui = ui_page_data_table, |
138 | ! |
datanames = datanames, |
139 | ! |
server_args = list( |
140 | ! |
datanames = if (is.null(datanames)) "all" else datanames, |
141 | ! |
variables_selected = variables_selected, |
142 | ! |
dt_args = dt_args, |
143 | ! |
dt_options = dt_options, |
144 | ! |
server_rendering = server_rendering |
145 |
), |
|
146 | ! |
ui_args = list( |
147 | ! |
pre_output = pre_output, |
148 | ! |
post_output = post_output |
149 |
), |
|
150 | ! |
transformators = transformators |
151 |
) |
|
152 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
153 | ! |
ans |
154 |
} |
|
155 | ||
156 |
# UI page module |
|
157 |
ui_page_data_table <- function(id, pre_output = NULL, post_output = NULL) { |
|
158 | ! |
ns <- NS(id) |
159 | ||
160 | ! |
tagList( |
161 | ! |
include_css_files("custom"), |
162 | ! |
teal.widgets::standard_layout( |
163 | ! |
output = teal.widgets::white_small_well( |
164 | ! |
fluidRow( |
165 | ! |
column( |
166 | ! |
width = 12, |
167 | ! |
checkboxInput( |
168 | ! |
ns("if_distinct"), |
169 | ! |
"Show only distinct rows:", |
170 | ! |
value = FALSE |
171 |
) |
|
172 |
) |
|
173 |
), |
|
174 | ! |
fluidRow( |
175 | ! |
class = "mb-8", |
176 | ! |
column( |
177 | ! |
width = 12, |
178 | ! |
uiOutput(ns("dataset_table")) |
179 |
) |
|
180 |
) |
|
181 |
), |
|
182 | ! |
pre_output = pre_output, |
183 | ! |
post_output = post_output |
184 |
) |
|
185 |
) |
|
186 |
} |
|
187 | ||
188 |
# Server page module |
|
189 |
srv_page_data_table <- function(id, |
|
190 |
data, |
|
191 |
datanames, |
|
192 |
variables_selected, |
|
193 |
dt_args, |
|
194 |
dt_options, |
|
195 |
server_rendering) { |
|
196 | ! |
checkmate::assert_class(data, "reactive") |
197 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
198 | ! |
moduleServer(id, function(input, output, session) { |
199 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
200 | ||
201 | ! |
if_filtered <- reactive(as.logical(input$if_filtered)) |
202 | ! |
if_distinct <- reactive(as.logical(input$if_distinct)) |
203 | ||
204 | ! |
datanames <- Filter(function(name) { |
205 | ! |
is.data.frame(isolate(data())[[name]]) |
206 | ! |
}, if (identical(datanames, "all")) names(isolate(data())) else datanames) |
207 | ||
208 | ||
209 | ! |
output$dataset_table <- renderUI({ |
210 | ! |
do.call( |
211 | ! |
tabsetPanel, |
212 | ! |
c( |
213 | ! |
list(id = session$ns("dataname_tab")), |
214 | ! |
lapply( |
215 | ! |
datanames, |
216 | ! |
function(x) { |
217 | ! |
dataset <- isolate(data()[[x]]) |
218 | ! |
choices <- names(dataset) |
219 | ! |
labels <- vapply( |
220 | ! |
dataset, |
221 | ! |
function(x) ifelse(is.null(attr(x, "label")), "", attr(x, "label")), |
222 | ! |
character(1) |
223 |
) |
|
224 | ! |
names(choices) <- ifelse( |
225 | ! |
is.na(labels) | labels == "", |
226 | ! |
choices, |
227 | ! |
paste(choices, labels, sep = ": ") |
228 |
) |
|
229 | ! |
variables_selected <- if (!is.null(variables_selected[[x]])) { |
230 | ! |
variables_selected[[x]] |
231 |
} else { |
|
232 | ! |
utils::head(choices) |
233 |
} |
|
234 | ! |
tabPanel( |
235 | ! |
title = x, |
236 | ! |
column( |
237 | ! |
width = 12, |
238 | ! |
div( |
239 | ! |
class = "mt-4", |
240 | ! |
ui_data_table( |
241 | ! |
id = session$ns(x), |
242 | ! |
choices = choices, |
243 | ! |
selected = variables_selected |
244 |
) |
|
245 |
) |
|
246 |
) |
|
247 |
) |
|
248 |
} |
|
249 |
) |
|
250 |
) |
|
251 |
) |
|
252 |
}) |
|
253 | ||
254 | ! |
lapply( |
255 | ! |
datanames, |
256 | ! |
function(x) { |
257 | ! |
srv_data_table( |
258 | ! |
id = x, |
259 | ! |
data = data, |
260 | ! |
dataname = x, |
261 | ! |
if_filtered = if_filtered, |
262 | ! |
if_distinct = if_distinct, |
263 | ! |
dt_args = dt_args, |
264 | ! |
dt_options = dt_options, |
265 | ! |
server_rendering = server_rendering |
266 |
) |
|
267 |
} |
|
268 |
) |
|
269 |
}) |
|
270 |
} |
|
271 | ||
272 |
# UI function for the data_table module |
|
273 |
ui_data_table <- function(id, choices, selected) { |
|
274 | ! |
ns <- NS(id) |
275 | ||
276 | ! |
if (!is.null(selected)) { |
277 | ! |
all_choices <- choices |
278 | ! |
choices <- c(selected, setdiff(choices, selected)) |
279 | ! |
names(choices) <- names(all_choices)[match(choices, all_choices)] |
280 |
} |
|
281 | ||
282 | ! |
tagList( |
283 | ! |
teal.widgets::get_dt_rows(ns("data_table"), ns("dt_rows")), |
284 | ! |
fluidRow( |
285 | ! |
teal.widgets::optionalSelectInput( |
286 | ! |
ns("variables"), |
287 | ! |
"Select variables:", |
288 | ! |
choices = choices, |
289 | ! |
selected = selected, |
290 | ! |
multiple = TRUE, |
291 | ! |
width = "100%" |
292 |
) |
|
293 |
), |
|
294 | ! |
fluidRow( |
295 | ! |
DT::dataTableOutput(ns("data_table"), width = "100%") |
296 |
) |
|
297 |
) |
|
298 |
} |
|
299 | ||
300 |
# Server function for the data_table module |
|
301 |
srv_data_table <- function(id, |
|
302 |
data, |
|
303 |
dataname, |
|
304 |
if_filtered, |
|
305 |
if_distinct, |
|
306 |
dt_args, |
|
307 |
dt_options, |
|
308 |
server_rendering) { |
|
309 | ! |
moduleServer(id, function(input, output, session) { |
310 | ! |
iv <- shinyvalidate::InputValidator$new() |
311 | ! |
iv$add_rule("variables", shinyvalidate::sv_required("Please select valid variable names")) |
312 | ! |
iv$add_rule("variables", shinyvalidate::sv_in_set( |
313 | ! |
set = names(isolate(data())[[dataname]]), message_fmt = "Not all selected variables exist in the data" |
314 |
)) |
|
315 | ! |
iv$enable() |
316 | ||
317 | ! |
data_table_data <- reactive({ |
318 | ! |
df <- data()[[dataname]] |
319 | ||
320 | ! |
teal::validate_has_data(df, min_nrow = 1L, msg = paste("data", dataname, "is empty")) |
321 | ||
322 | ! |
teal.code::eval_code( |
323 | ! |
data(), |
324 | ! |
substitute( |
325 | ! |
expr = { |
326 | ! |
variables <- vars |
327 | ! |
dataframe_selected <- if (if_distinct) { |
328 | ! |
dplyr::count(dataname, dplyr::across(dplyr::all_of(variables))) |
329 |
} else { |
|
330 | ! |
dataname[variables] |
331 |
} |
|
332 | ! |
dt_args <- args |
333 | ! |
dt_args$options <- dt_options |
334 | ! |
if (!is.null(dt_rows)) { |
335 | ! |
dt_args$options$pageLength <- dt_rows |
336 |
} |
|
337 | ! |
dt_args$data <- dataframe_selected |
338 | ! |
table <- do.call(DT::datatable, dt_args) |
339 |
}, |
|
340 | ! |
env = list( |
341 | ! |
dataname = as.name(dataname), |
342 | ! |
if_distinct = if_distinct(), |
343 | ! |
vars = input$variables, |
344 | ! |
args = dt_args, |
345 | ! |
dt_options = dt_options, |
346 | ! |
dt_rows = input$dt_rows |
347 |
) |
|
348 |
) |
|
349 |
) |
|
350 |
}) |
|
351 | ||
352 | ! |
output$data_table <- DT::renderDataTable(server = server_rendering, { |
353 | ! |
teal::validate_inputs(iv) |
354 | ! |
req(data_table_data())[["table"]] |
355 |
}) |
|
356 |
}) |
|
357 |
} |
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 |
#' |
|
23 |
#' @note For more examples, please see the vignette "Using cross table" via |
|
24 |
#' `vignette("using-cross-table", package = "teal.modules.general")`. |
|
25 |
#' |
|
26 |
#' @inherit shared_params return |
|
27 |
#' |
|
28 |
#' @section Decorating Module: |
|
29 |
#' |
|
30 |
#' This module generates the following objects, which can be modified in place using decorators: |
|
31 |
#' - `table` (`ElementaryTable` - output of `rtables::build_table`) |
|
32 |
#' |
|
33 |
#' A Decorator is applied to the specific output using a named list of `teal_transform_module` objects. |
|
34 |
#' The name of this list corresponds to the name of the output to which the decorator is applied. |
|
35 |
#' See code snippet below: |
|
36 |
#' |
|
37 |
#' ``` |
|
38 |
#' tm_t_crosstable( |
|
39 |
#' ..., # arguments for module |
|
40 |
#' decorators = list( |
|
41 |
#' table = teal_transform_module(...) # applied to the `table` output |
|
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 |
#' # general data example |
|
54 |
#' data <- teal_data() |
|
55 |
#' data <- within(data, { |
|
56 |
#' mtcars <- mtcars |
|
57 |
#' for (v in c("cyl", "vs", "am", "gear")) { |
|
58 |
#' mtcars[[v]] <- as.factor(mtcars[[v]]) |
|
59 |
#' } |
|
60 |
#' mtcars[["primary_key"]] <- seq_len(nrow(mtcars)) |
|
61 |
#' }) |
|
62 |
#' join_keys(data) <- join_keys(join_key("mtcars", "mtcars", "primary_key")) |
|
63 |
#' |
|
64 |
#' app <- init( |
|
65 |
#' data = data, |
|
66 |
#' modules = modules( |
|
67 |
#' tm_t_crosstable( |
|
68 |
#' label = "Cross Table", |
|
69 |
#' x = 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 = c("cyl", "gear"), |
|
75 |
#' multiple = TRUE, |
|
76 |
#' ordered = TRUE, |
|
77 |
#' fixed = FALSE |
|
78 |
#' ) |
|
79 |
#' ), |
|
80 |
#' y = data_extract_spec( |
|
81 |
#' dataname = "mtcars", |
|
82 |
#' select = select_spec( |
|
83 |
#' label = "Select variable:", |
|
84 |
#' choices = variable_choices(data[["mtcars"]], c("cyl", "vs", "am", "gear")), |
|
85 |
#' selected = "vs", |
|
86 |
#' multiple = FALSE, |
|
87 |
#' fixed = FALSE |
|
88 |
#' ) |
|
89 |
#' ) |
|
90 |
#' ) |
|
91 |
#' ) |
|
92 |
#' ) |
|
93 |
#' if (interactive()) { |
|
94 |
#' shinyApp(app$ui, app$server) |
|
95 |
#' } |
|
96 |
#' |
|
97 |
#' @examplesShinylive |
|
98 |
#' library(teal.modules.general) |
|
99 |
#' interactive <- function() TRUE |
|
100 |
#' {{ next_example }} |
|
101 |
#' @examples |
|
102 |
#' # CDISC data example |
|
103 |
#' data <- teal_data() |
|
104 |
#' data <- within(data, { |
|
105 |
#' ADSL <- teal.data::rADSL |
|
106 |
#' }) |
|
107 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
108 |
#' |
|
109 |
#' app <- init( |
|
110 |
#' data = data, |
|
111 |
#' modules = modules( |
|
112 |
#' tm_t_crosstable( |
|
113 |
#' label = "Cross Table", |
|
114 |
#' x = data_extract_spec( |
|
115 |
#' dataname = "ADSL", |
|
116 |
#' select = select_spec( |
|
117 |
#' label = "Select variable:", |
|
118 |
#' choices = variable_choices(data[["ADSL"]], subset = function(data) { |
|
119 |
#' idx <- !vapply(data, inherits, logical(1), c("Date", "POSIXct", "POSIXlt")) |
|
120 |
#' return(names(data)[idx]) |
|
121 |
#' }), |
|
122 |
#' selected = "COUNTRY", |
|
123 |
#' multiple = TRUE, |
|
124 |
#' ordered = TRUE, |
|
125 |
#' fixed = FALSE |
|
126 |
#' ) |
|
127 |
#' ), |
|
128 |
#' y = data_extract_spec( |
|
129 |
#' dataname = "ADSL", |
|
130 |
#' select = select_spec( |
|
131 |
#' label = "Select variable:", |
|
132 |
#' choices = variable_choices(data[["ADSL"]], subset = function(data) { |
|
133 |
#' idx <- vapply(data, is.factor, logical(1)) |
|
134 |
#' return(names(data)[idx]) |
|
135 |
#' }), |
|
136 |
#' selected = "SEX", |
|
137 |
#' multiple = FALSE, |
|
138 |
#' fixed = FALSE |
|
139 |
#' ) |
|
140 |
#' ) |
|
141 |
#' ) |
|
142 |
#' ) |
|
143 |
#' ) |
|
144 |
#' if (interactive()) { |
|
145 |
#' shinyApp(app$ui, app$server) |
|
146 |
#' } |
|
147 |
#' |
|
148 |
#' @export |
|
149 |
#' |
|
150 |
tm_t_crosstable <- function(label = "Cross Table", |
|
151 |
x, |
|
152 |
y, |
|
153 |
show_percentage = TRUE, |
|
154 |
show_total = TRUE, |
|
155 |
pre_output = NULL, |
|
156 |
post_output = NULL, |
|
157 |
basic_table_args = teal.widgets::basic_table_args(), |
|
158 |
transformators = list(), |
|
159 |
decorators = list()) { |
|
160 | ! |
message("Initializing tm_t_crosstable") |
161 | ||
162 |
# Normalize the parameters |
|
163 | ! |
if (inherits(x, "data_extract_spec")) x <- list(x) |
164 | ! |
if (inherits(y, "data_extract_spec")) y <- list(y) |
165 | ||
166 |
# Start of assertions |
|
167 | ! |
checkmate::assert_string(label) |
168 | ! |
checkmate::assert_list(x, types = "data_extract_spec") |
169 | ||
170 | ! |
checkmate::assert_list(y, types = "data_extract_spec") |
171 | ! |
assert_single_selection(y) |
172 | ||
173 | ! |
checkmate::assert_flag(show_percentage) |
174 | ! |
checkmate::assert_flag(show_total) |
175 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
176 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
177 | ! |
checkmate::assert_class(basic_table_args, classes = "basic_table_args") |
178 | ||
179 | ! |
assert_decorators(decorators, "table") |
180 |
# End of assertions |
|
181 | ||
182 |
# Make UI args |
|
183 | ! |
ui_args <- as.list(environment()) |
184 | ||
185 | ! |
server_args <- list( |
186 | ! |
label = label, |
187 | ! |
x = x, |
188 | ! |
y = y, |
189 | ! |
basic_table_args = basic_table_args, |
190 | ! |
decorators = decorators |
191 |
) |
|
192 | ||
193 | ! |
ans <- module( |
194 | ! |
label = label, |
195 | ! |
server = srv_t_crosstable, |
196 | ! |
ui = ui_t_crosstable, |
197 | ! |
ui_args = ui_args, |
198 | ! |
server_args = server_args, |
199 | ! |
transformators = transformators, |
200 | ! |
datanames = teal.transform::get_extract_datanames(list(x = x, y = y)) |
201 |
) |
|
202 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
203 | ! |
ans |
204 |
} |
|
205 | ||
206 |
# UI function for the cross-table module |
|
207 |
ui_t_crosstable <- function(id, x, y, show_percentage, show_total, pre_output, post_output, ...) { |
|
208 | ! |
args <- list(...) |
209 | ! |
ns <- NS(id) |
210 | ! |
is_single_dataset <- teal.transform::is_single_dataset(x, y) |
211 | ||
212 | ! |
join_default_options <- c( |
213 | ! |
"Full Join" = "dplyr::full_join", |
214 | ! |
"Inner Join" = "dplyr::inner_join", |
215 | ! |
"Left Join" = "dplyr::left_join", |
216 | ! |
"Right Join" = "dplyr::right_join" |
217 |
) |
|
218 | ||
219 | ! |
teal.widgets::standard_layout( |
220 | ! |
output = teal.widgets::white_small_well( |
221 | ! |
textOutput(ns("title")), |
222 | ! |
teal.widgets::table_with_settings_ui(ns("table")) |
223 |
), |
|
224 | ! |
encoding = tags$div( |
225 |
### Reporter |
|
226 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
227 |
### |
|
228 | ! |
tags$label("Encodings", class = "text-primary"), |
229 | ! |
teal.transform::datanames_input(list(x, y)), |
230 | ! |
teal.transform::data_extract_ui(ns("x"), label = "Row values", x, is_single_dataset = is_single_dataset), |
231 | ! |
teal.transform::data_extract_ui(ns("y"), label = "Column values", y, is_single_dataset = is_single_dataset), |
232 | ! |
teal.widgets::optionalSelectInput( |
233 | ! |
ns("join_fun"), |
234 | ! |
label = "Row to Column type of join", |
235 | ! |
choices = join_default_options, |
236 | ! |
selected = join_default_options[1], |
237 | ! |
multiple = FALSE |
238 |
), |
|
239 | ! |
tags$hr(), |
240 | ! |
teal.widgets::panel_group( |
241 | ! |
teal.widgets::panel_item( |
242 | ! |
title = "Table settings", |
243 | ! |
checkboxInput(ns("show_percentage"), "Show column percentage", value = show_percentage), |
244 | ! |
checkboxInput(ns("show_total"), "Show total column", value = show_total) |
245 |
) |
|
246 |
), |
|
247 | ! |
ui_decorate_teal_data(ns("decorator"), decorators = select_decorators(args$decorators, "table")) |
248 |
), |
|
249 | ! |
forms = tagList( |
250 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
251 |
), |
|
252 | ! |
pre_output = pre_output, |
253 | ! |
post_output = post_output |
254 |
) |
|
255 |
} |
|
256 | ||
257 |
# Server function for the cross-table module |
|
258 |
srv_t_crosstable <- function(id, data, reporter, filter_panel_api, label, x, y, basic_table_args, decorators) { |
|
259 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
260 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
261 | ! |
checkmate::assert_class(data, "reactive") |
262 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
263 | ! |
moduleServer(id, function(input, output, session) { |
264 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
265 | ||
266 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
267 | ! |
data_extract = list(x = x, y = y), |
268 | ! |
datasets = data, |
269 | ! |
select_validation_rule = list( |
270 | ! |
x = shinyvalidate::sv_required("Please define column for row variable."), |
271 | ! |
y = shinyvalidate::sv_required("Please define column for column variable.") |
272 |
) |
|
273 |
) |
|
274 | ||
275 | ! |
iv_r <- reactive({ |
276 | ! |
iv <- shinyvalidate::InputValidator$new() |
277 | ! |
iv$add_rule("join_fun", function(value) { |
278 | ! |
if (!identical(selector_list()$x()$dataname, selector_list()$y()$dataname)) { |
279 | ! |
if (!shinyvalidate::input_provided(value)) { |
280 | ! |
"Please select a joining function." |
281 |
} |
|
282 |
} |
|
283 |
}) |
|
284 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
285 |
}) |
|
286 | ||
287 | ! |
observeEvent( |
288 | ! |
eventExpr = { |
289 | ! |
req(!is.null(selector_list()$x()) && !is.null(selector_list()$y())) |
290 | ! |
list(selector_list()$x(), selector_list()$y()) |
291 |
}, |
|
292 | ! |
handlerExpr = { |
293 | ! |
if (identical(selector_list()$x()$dataname, selector_list()$y()$dataname)) { |
294 | ! |
shinyjs::hide("join_fun") |
295 |
} else { |
|
296 | ! |
shinyjs::show("join_fun") |
297 |
} |
|
298 |
} |
|
299 |
) |
|
300 | ||
301 | ! |
merge_function <- reactive({ |
302 | ! |
if (is.null(input$join_fun)) { |
303 | ! |
"dplyr::full_join" |
304 |
} else { |
|
305 | ! |
input$join_fun |
306 |
} |
|
307 |
}) |
|
308 | ||
309 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
310 | ! |
datasets = data, |
311 | ! |
selector_list = selector_list, |
312 | ! |
merge_function = merge_function |
313 |
) |
|
314 | ||
315 | ! |
anl_merged_q <- reactive({ |
316 | ! |
req(anl_merged_input()) |
317 | ! |
data() %>% |
318 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
319 |
}) |
|
320 | ||
321 | ! |
merged <- list( |
322 | ! |
anl_input_r = anl_merged_input, |
323 | ! |
anl_q_r = anl_merged_q |
324 |
) |
|
325 | ||
326 | ! |
output_q <- reactive({ |
327 | ! |
teal::validate_inputs(iv_r()) |
328 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
329 | ||
330 |
# As this is a summary |
|
331 | ! |
x_name <- as.vector(merged$anl_input_r()$columns_source$x) |
332 | ! |
y_name <- as.vector(merged$anl_input_r()$columns_source$y) |
333 | ||
334 | ! |
teal::validate_has_data(ANL, 3) |
335 | ! |
teal::validate_has_data(ANL[, c(x_name, y_name)], 3, complete = TRUE, allow_inf = FALSE) |
336 | ||
337 | ! |
is_allowed_class <- function(x) is.numeric(x) || is.factor(x) || is.character(x) || is.logical(x) |
338 | ! |
validate(need( |
339 | ! |
all(vapply(ANL[x_name], is_allowed_class, logical(1))), |
340 | ! |
"Selected row variable has an unsupported data type." |
341 |
)) |
|
342 | ! |
validate(need( |
343 | ! |
is_allowed_class(ANL[[y_name]]), |
344 | ! |
"Selected column variable has an unsupported data type." |
345 |
)) |
|
346 | ||
347 | ! |
show_percentage <- input$show_percentage |
348 | ! |
show_total <- input$show_total |
349 | ||
350 | ! |
plot_title <- paste( |
351 | ! |
"Cross-Table of", |
352 | ! |
paste0(varname_w_label(x_name, ANL), collapse = ", "), |
353 | ! |
"(rows)", "vs.", |
354 | ! |
varname_w_label(y_name, ANL), |
355 | ! |
"(columns)" |
356 |
) |
|
357 | ||
358 | ! |
labels_vec <- vapply( |
359 | ! |
x_name, |
360 | ! |
varname_w_label, |
361 | ! |
character(1), |
362 | ! |
ANL |
363 |
) |
|
364 | ||
365 | ! |
teal.code::eval_code( |
366 | ! |
merged$anl_q_r(), |
367 | ! |
substitute( |
368 | ! |
expr = { |
369 | ! |
title <- plot_title |
370 |
}, |
|
371 | ! |
env = list(plot_title = plot_title) |
372 |
) |
|
373 |
) %>% |
|
374 | ! |
teal.code::eval_code( |
375 | ! |
substitute( |
376 | ! |
expr = { |
377 | ! |
table <- basic_tables %>% |
378 | ! |
split_call %>% # styler: off |
379 | ! |
rtables::add_colcounts() %>% |
380 | ! |
tern::analyze_vars( |
381 | ! |
vars = x_name, |
382 | ! |
var_labels = labels_vec, |
383 | ! |
na.rm = FALSE, |
384 | ! |
denom = "N_col", |
385 | ! |
.stats = c("mean_sd", "median", "range", count_value) |
386 |
) |
|
387 |
}, |
|
388 | ! |
env = list( |
389 | ! |
basic_tables = teal.widgets::parse_basic_table_args( |
390 | ! |
basic_table_args = teal.widgets::resolve_basic_table_args(basic_table_args) |
391 |
), |
|
392 | ! |
split_call = if (show_total) { |
393 | ! |
substitute( |
394 | ! |
expr = rtables::split_cols_by( |
395 | ! |
y_name, |
396 | ! |
split_fun = rtables::add_overall_level(label = "Total", first = FALSE) |
397 |
), |
|
398 | ! |
env = list(y_name = y_name) |
399 |
) |
|
400 |
} else { |
|
401 | ! |
substitute(rtables::split_cols_by(y_name), env = list(y_name = y_name)) |
402 |
}, |
|
403 | ! |
x_name = x_name, |
404 | ! |
labels_vec = labels_vec, |
405 | ! |
count_value = ifelse(show_percentage, "count_fraction", "count") |
406 |
) |
|
407 |
) |
|
408 |
) %>% |
|
409 | ! |
teal.code::eval_code( |
410 | ! |
substitute( |
411 | ! |
expr = { |
412 | ! |
ANL <- tern::df_explicit_na(ANL) |
413 | ! |
table <- rtables::build_table(lyt = table, df = ANL[order(ANL[[y_name]]), ]) |
414 |
}, |
|
415 | ! |
env = list(y_name = y_name) |
416 |
) |
|
417 |
) |
|
418 |
}) |
|
419 | ||
420 | ! |
decorated_output_q <- srv_decorate_teal_data( |
421 | ! |
id = "decorator", |
422 | ! |
data = output_q, |
423 | ! |
decorators = select_decorators(decorators, "table"), |
424 | ! |
expr = table |
425 |
) |
|
426 | ||
427 | ! |
output$title <- renderText(req(decorated_output_q())[["title"]]) |
428 | ||
429 | ! |
table_r <- reactive({ |
430 | ! |
req(iv_r()$is_valid()) |
431 | ! |
req(decorated_output_q())[["table"]] |
432 |
}) |
|
433 | ||
434 | ! |
teal.widgets::table_with_settings_srv( |
435 | ! |
id = "table", |
436 | ! |
table_r = table_r |
437 |
) |
|
438 | ||
439 |
# Render R code. |
|
440 | ! |
source_code_r <- reactive(teal.code::get_code(req(decorated_output_q()))) |
441 | ||
442 | ! |
teal.widgets::verbatim_popup_srv( |
443 | ! |
id = "rcode", |
444 | ! |
verbatim_content = source_code_r, |
445 | ! |
title = "Show R Code for Cross-Table" |
446 |
) |
|
447 | ||
448 |
### REPORTER |
|
449 | ! |
if (with_reporter) { |
450 | ! |
card_fun <- function(comment, label) { |
451 | ! |
card <- teal::report_card_template( |
452 | ! |
title = "Cross Table", |
453 | ! |
label = label, |
454 | ! |
with_filter = with_filter, |
455 | ! |
filter_panel_api = filter_panel_api |
456 |
) |
|
457 | ! |
card$append_text("Table", "header3") |
458 | ! |
card$append_table(table_r()) |
459 | ! |
if (!comment == "") { |
460 | ! |
card$append_text("Comment", "header3") |
461 | ! |
card$append_text(comment) |
462 |
} |
|
463 | ! |
card$append_src(source_code_r()) |
464 | ! |
card |
465 |
} |
|
466 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
467 |
} |
|
468 |
### |
|
469 |
}) |
|
470 |
} |
1 |
.onLoad <- function(libname, pkgname) { |
|
2 | ! |
teal.logger::register_logger(namespace = "teal.modules.general") |
3 | ! |
teal.logger::register_handlers("teal.modules.general") |
4 |
} |
|
5 | ||
6 |
### global variables |
|
7 |
ggplot_themes <- c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void") |
|
8 | ||
9 |
#' @importFrom lifecycle deprecated |
|
10 |
interactive <- NULL |