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 |
#' @examplesShinylive |
|
34 |
#' library(teal.modules.general) |
|
35 |
#' interactive <- function() TRUE |
|
36 |
#' {{ next_example }} |
|
37 |
# nolint start: line_length_linter. |
|
38 |
#' @examplesIf require("ggpmisc", quietly = TRUE) && require("ggExtra", quietly = TRUE) && require("colourpicker", quietly = TRUE) |
|
39 |
# nolint end: line_length_linter. |
|
40 |
#' # general data example |
|
41 |
#' data <- teal_data() |
|
42 |
#' data <- within(data, { |
|
43 |
#' require(nestcolor) |
|
44 |
#' CO2 <- CO2 |
|
45 |
#' }) |
|
46 |
#' |
|
47 |
#' app <- init( |
|
48 |
#' data = data, |
|
49 |
#' modules = modules( |
|
50 |
#' tm_g_scatterplot( |
|
51 |
#' label = "Scatterplot Choices", |
|
52 |
#' x = data_extract_spec( |
|
53 |
#' dataname = "CO2", |
|
54 |
#' select = select_spec( |
|
55 |
#' label = "Select variable:", |
|
56 |
#' choices = variable_choices(data[["CO2"]], c("conc", "uptake")), |
|
57 |
#' selected = "conc", |
|
58 |
#' multiple = FALSE, |
|
59 |
#' fixed = FALSE |
|
60 |
#' ) |
|
61 |
#' ), |
|
62 |
#' y = data_extract_spec( |
|
63 |
#' dataname = "CO2", |
|
64 |
#' select = select_spec( |
|
65 |
#' label = "Select variable:", |
|
66 |
#' choices = variable_choices(data[["CO2"]], c("conc", "uptake")), |
|
67 |
#' selected = "uptake", |
|
68 |
#' multiple = FALSE, |
|
69 |
#' fixed = FALSE |
|
70 |
#' ) |
|
71 |
#' ), |
|
72 |
#' color_by = data_extract_spec( |
|
73 |
#' dataname = "CO2", |
|
74 |
#' select = select_spec( |
|
75 |
#' label = "Select variable:", |
|
76 |
#' choices = variable_choices( |
|
77 |
#' data[["CO2"]], |
|
78 |
#' c("Plant", "Type", "Treatment", "conc", "uptake") |
|
79 |
#' ), |
|
80 |
#' selected = NULL, |
|
81 |
#' multiple = FALSE, |
|
82 |
#' fixed = FALSE |
|
83 |
#' ) |
|
84 |
#' ), |
|
85 |
#' size_by = data_extract_spec( |
|
86 |
#' dataname = "CO2", |
|
87 |
#' select = select_spec( |
|
88 |
#' label = "Select variable:", |
|
89 |
#' choices = variable_choices(data[["CO2"]], c("conc", "uptake")), |
|
90 |
#' selected = "uptake", |
|
91 |
#' multiple = FALSE, |
|
92 |
#' fixed = FALSE |
|
93 |
#' ) |
|
94 |
#' ), |
|
95 |
#' row_facet = data_extract_spec( |
|
96 |
#' dataname = "CO2", |
|
97 |
#' select = select_spec( |
|
98 |
#' label = "Select variable:", |
|
99 |
#' choices = variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment")), |
|
100 |
#' selected = NULL, |
|
101 |
#' multiple = FALSE, |
|
102 |
#' fixed = FALSE |
|
103 |
#' ) |
|
104 |
#' ), |
|
105 |
#' col_facet = data_extract_spec( |
|
106 |
#' dataname = "CO2", |
|
107 |
#' select = select_spec( |
|
108 |
#' label = "Select variable:", |
|
109 |
#' choices = variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment")), |
|
110 |
#' selected = NULL, |
|
111 |
#' multiple = FALSE, |
|
112 |
#' fixed = FALSE |
|
113 |
#' ) |
|
114 |
#' ) |
|
115 |
#' ) |
|
116 |
#' ) |
|
117 |
#' ) |
|
118 |
#' if (interactive()) { |
|
119 |
#' shinyApp(app$ui, app$server) |
|
120 |
#' } |
|
121 |
#' |
|
122 |
#' @examplesShinylive |
|
123 |
#' library(teal.modules.general) |
|
124 |
#' interactive <- function() TRUE |
|
125 |
#' {{ next_example }} |
|
126 |
# nolint start: line_length_linter. |
|
127 |
#' @examplesIf require("ggpmisc", quietly = TRUE) && require("ggExtra", quietly = TRUE) && require("colourpicker", quietly = TRUE) |
|
128 |
# nolint end: line_length_linter. |
|
129 |
#' # CDISC data example |
|
130 |
#' data <- teal_data() |
|
131 |
#' data <- within(data, { |
|
132 |
#' require(nestcolor) |
|
133 |
#' ADSL <- rADSL |
|
134 |
#' }) |
|
135 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
136 |
#' |
|
137 |
#' app <- init( |
|
138 |
#' data = data, |
|
139 |
#' modules = modules( |
|
140 |
#' tm_g_scatterplot( |
|
141 |
#' label = "Scatterplot Choices", |
|
142 |
#' x = data_extract_spec( |
|
143 |
#' dataname = "ADSL", |
|
144 |
#' select = select_spec( |
|
145 |
#' label = "Select variable:", |
|
146 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1", "BMRKR2")), |
|
147 |
#' selected = "AGE", |
|
148 |
#' multiple = FALSE, |
|
149 |
#' fixed = FALSE |
|
150 |
#' ) |
|
151 |
#' ), |
|
152 |
#' y = data_extract_spec( |
|
153 |
#' dataname = "ADSL", |
|
154 |
#' select = select_spec( |
|
155 |
#' label = "Select variable:", |
|
156 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1", "BMRKR2")), |
|
157 |
#' selected = "BMRKR1", |
|
158 |
#' multiple = FALSE, |
|
159 |
#' fixed = FALSE |
|
160 |
#' ) |
|
161 |
#' ), |
|
162 |
#' color_by = data_extract_spec( |
|
163 |
#' dataname = "ADSL", |
|
164 |
#' select = select_spec( |
|
165 |
#' label = "Select variable:", |
|
166 |
#' choices = variable_choices( |
|
167 |
#' data[["ADSL"]], |
|
168 |
#' c("AGE", "BMRKR1", "BMRKR2", "RACE", "REGION1") |
|
169 |
#' ), |
|
170 |
#' selected = NULL, |
|
171 |
#' multiple = FALSE, |
|
172 |
#' fixed = FALSE |
|
173 |
#' ) |
|
174 |
#' ), |
|
175 |
#' size_by = data_extract_spec( |
|
176 |
#' dataname = "ADSL", |
|
177 |
#' select = select_spec( |
|
178 |
#' label = "Select variable:", |
|
179 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1")), |
|
180 |
#' selected = "AGE", |
|
181 |
#' multiple = FALSE, |
|
182 |
#' fixed = FALSE |
|
183 |
#' ) |
|
184 |
#' ), |
|
185 |
#' row_facet = data_extract_spec( |
|
186 |
#' dataname = "ADSL", |
|
187 |
#' select = select_spec( |
|
188 |
#' label = "Select variable:", |
|
189 |
#' choices = variable_choices(data[["ADSL"]], c("BMRKR2", "RACE", "REGION1")), |
|
190 |
#' selected = NULL, |
|
191 |
#' multiple = FALSE, |
|
192 |
#' fixed = FALSE |
|
193 |
#' ) |
|
194 |
#' ), |
|
195 |
#' col_facet = data_extract_spec( |
|
196 |
#' dataname = "ADSL", |
|
197 |
#' select = select_spec( |
|
198 |
#' label = "Select variable:", |
|
199 |
#' choices = variable_choices(data[["ADSL"]], c("BMRKR2", "RACE", "REGION1")), |
|
200 |
#' selected = NULL, |
|
201 |
#' multiple = FALSE, |
|
202 |
#' fixed = FALSE |
|
203 |
#' ) |
|
204 |
#' ) |
|
205 |
#' ) |
|
206 |
#' ) |
|
207 |
#' ) |
|
208 |
#' if (interactive()) { |
|
209 |
#' shinyApp(app$ui, app$server) |
|
210 |
#' } |
|
211 |
#' |
|
212 |
#' @export |
|
213 |
#' |
|
214 |
tm_g_scatterplot <- function(label = "Scatterplot", |
|
215 |
x, |
|
216 |
y, |
|
217 |
color_by = NULL, |
|
218 |
size_by = NULL, |
|
219 |
row_facet = NULL, |
|
220 |
col_facet = NULL, |
|
221 |
plot_height = c(600, 200, 2000), |
|
222 |
plot_width = NULL, |
|
223 |
alpha = c(1, 0, 1), |
|
224 |
shape = shape_names, |
|
225 |
size = c(5, 1, 15), |
|
226 |
max_deg = 5L, |
|
227 |
rotate_xaxis_labels = FALSE, |
|
228 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
229 |
pre_output = NULL, |
|
230 |
post_output = NULL, |
|
231 |
table_dec = 4, |
|
232 |
ggplot2_args = teal.widgets::ggplot2_args()) { |
|
233 | ! |
message("Initializing tm_g_scatterplot") |
234 | ||
235 |
# Requires Suggested packages |
|
236 | ! |
extra_packages <- c("ggpmisc", "ggExtra", "colourpicker") |
237 | ! |
missing_packages <- Filter(function(x) !requireNamespace(x, quietly = TRUE), extra_packages) |
238 | ! |
if (length(missing_packages) > 0L) { |
239 | ! |
stop(sprintf( |
240 | ! |
"Cannot load package(s): %s.\nInstall or restart your session.", |
241 | ! |
toString(missing_packages) |
242 |
)) |
|
243 |
} |
|
244 | ||
245 |
# Normalize the parameters |
|
246 | ! |
if (inherits(x, "data_extract_spec")) x <- list(x) |
247 | ! |
if (inherits(y, "data_extract_spec")) y <- list(y) |
248 | ! |
if (inherits(color_by, "data_extract_spec")) color_by <- list(color_by) |
249 | ! |
if (inherits(size_by, "data_extract_spec")) size_by <- list(size_by) |
250 | ! |
if (inherits(row_facet, "data_extract_spec")) row_facet <- list(row_facet) |
251 | ! |
if (inherits(col_facet, "data_extract_spec")) col_facet <- list(col_facet) |
252 | ! |
if (is.double(max_deg)) max_deg <- as.integer(max_deg) |
253 | ||
254 |
# Start of assertions |
|
255 | ! |
checkmate::assert_string(label) |
256 | ! |
checkmate::assert_list(x, types = "data_extract_spec") |
257 | ! |
checkmate::assert_list(y, types = "data_extract_spec") |
258 | ! |
checkmate::assert_list(color_by, types = "data_extract_spec", null.ok = TRUE) |
259 | ! |
checkmate::assert_list(size_by, types = "data_extract_spec", null.ok = TRUE) |
260 | ||
261 | ! |
checkmate::assert_list(row_facet, types = "data_extract_spec", null.ok = TRUE) |
262 | ! |
assert_single_selection(row_facet) |
263 | ||
264 | ! |
checkmate::assert_list(col_facet, types = "data_extract_spec", null.ok = TRUE) |
265 | ! |
assert_single_selection(col_facet) |
266 | ||
267 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
268 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
269 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
270 | ! |
checkmate::assert_numeric( |
271 | ! |
plot_width[1], |
272 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
273 |
) |
|
274 | ||
275 | ! |
if (length(alpha) == 1) { |
276 | ! |
checkmate::assert_numeric(alpha, any.missing = FALSE, finite = TRUE) |
277 |
} else { |
|
278 | ! |
checkmate::assert_numeric(alpha, len = 3, any.missing = FALSE, finite = TRUE) |
279 | ! |
checkmate::assert_numeric(alpha[1], lower = alpha[2], upper = alpha[3], .var.name = "alpha") |
280 |
} |
|
281 | ||
282 | ! |
checkmate::assert_character(shape) |
283 | ||
284 | ! |
if (length(size) == 1) { |
285 | ! |
checkmate::assert_numeric(size, any.missing = FALSE, finite = TRUE) |
286 |
} else { |
|
287 | ! |
checkmate::assert_numeric(size, len = 3, any.missing = FALSE, finite = TRUE) |
288 | ! |
checkmate::assert_numeric(size[1], lower = size[2], upper = size[3], .var.name = "size") |
289 |
} |
|
290 | ||
291 | ! |
checkmate::assert_int(max_deg, lower = 1L) |
292 | ! |
checkmate::assert_flag(rotate_xaxis_labels) |
293 | ! |
ggtheme <- match.arg(ggtheme) |
294 | ||
295 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
296 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
297 | ||
298 | ! |
checkmate::assert_scalar(table_dec) |
299 | ! |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
300 |
# End of assertions |
|
301 | ||
302 |
# Make UI args |
|
303 | ! |
args <- as.list(environment()) |
304 | ||
305 | ! |
data_extract_list <- list( |
306 | ! |
x = x, |
307 | ! |
y = y, |
308 | ! |
color_by = color_by, |
309 | ! |
size_by = size_by, |
310 | ! |
row_facet = row_facet, |
311 | ! |
col_facet = col_facet |
312 |
) |
|
313 | ||
314 | ! |
ans <- module( |
315 | ! |
label = label, |
316 | ! |
server = srv_g_scatterplot, |
317 | ! |
ui = ui_g_scatterplot, |
318 | ! |
ui_args = args, |
319 | ! |
server_args = c( |
320 | ! |
data_extract_list, |
321 | ! |
list(plot_height = plot_height, plot_width = plot_width, table_dec = table_dec, ggplot2_args = ggplot2_args) |
322 |
), |
|
323 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
324 |
) |
|
325 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
326 | ! |
ans |
327 |
} |
|
328 | ||
329 |
# UI function for the scatterplot module |
|
330 |
ui_g_scatterplot <- function(id, ...) { |
|
331 | ! |
args <- list(...) |
332 | ! |
ns <- NS(id) |
333 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset( |
334 | ! |
args$x, args$y, args$color_by, args$size_by, args$row_facet, args$col_facet |
335 |
) |
|
336 | ||
337 | ! |
tagList( |
338 | ! |
include_css_files("custom"), |
339 | ! |
teal.widgets::standard_layout( |
340 | ! |
output = teal.widgets::white_small_well( |
341 | ! |
teal.widgets::plot_with_settings_ui(id = ns("scatter_plot")), |
342 | ! |
tags$h1(tags$strong("Selected points:"), class = "text-center font-150p"), |
343 | ! |
teal.widgets::get_dt_rows(ns("data_table"), ns("data_table_rows")), |
344 | ! |
DT::dataTableOutput(ns("data_table"), width = "100%") |
345 |
), |
|
346 | ! |
encoding = tags$div( |
347 |
### Reporter |
|
348 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
349 |
### |
|
350 | ! |
tags$label("Encodings", class = "text-primary"), |
351 | ! |
teal.transform::datanames_input(args[c("x", "y", "color_by", "size_by", "row_facet", "col_facet")]), |
352 | ! |
teal.transform::data_extract_ui( |
353 | ! |
id = ns("x"), |
354 | ! |
label = "X variable", |
355 | ! |
data_extract_spec = args$x, |
356 | ! |
is_single_dataset = is_single_dataset_value |
357 |
), |
|
358 | ! |
checkboxInput(ns("log_x"), "Use log transformation", value = FALSE), |
359 | ! |
conditionalPanel( |
360 | ! |
condition = paste0("input['", ns("log_x"), "'] == true"), |
361 | ! |
radioButtons( |
362 | ! |
ns("log_x_base"), |
363 | ! |
label = NULL, |
364 | ! |
inline = TRUE, |
365 | ! |
choices = c("Natural" = "log", "Base 10" = "log10", "Base 2" = "log2") |
366 |
) |
|
367 |
), |
|
368 | ! |
teal.transform::data_extract_ui( |
369 | ! |
id = ns("y"), |
370 | ! |
label = "Y variable", |
371 | ! |
data_extract_spec = args$y, |
372 | ! |
is_single_dataset = is_single_dataset_value |
373 |
), |
|
374 | ! |
checkboxInput(ns("log_y"), "Use log transformation", value = FALSE), |
375 | ! |
conditionalPanel( |
376 | ! |
condition = paste0("input['", ns("log_y"), "'] == true"), |
377 | ! |
radioButtons( |
378 | ! |
ns("log_y_base"), |
379 | ! |
label = NULL, |
380 | ! |
inline = TRUE, |
381 | ! |
choices = c("Natural" = "log", "Base 10" = "log10", "Base 2" = "log2") |
382 |
) |
|
383 |
), |
|
384 | ! |
if (!is.null(args$color_by)) { |
385 | ! |
teal.transform::data_extract_ui( |
386 | ! |
id = ns("color_by"), |
387 | ! |
label = "Color by variable", |
388 | ! |
data_extract_spec = args$color_by, |
389 | ! |
is_single_dataset = is_single_dataset_value |
390 |
) |
|
391 |
}, |
|
392 | ! |
if (!is.null(args$size_by)) { |
393 | ! |
teal.transform::data_extract_ui( |
394 | ! |
id = ns("size_by"), |
395 | ! |
label = "Size by variable", |
396 | ! |
data_extract_spec = args$size_by, |
397 | ! |
is_single_dataset = is_single_dataset_value |
398 |
) |
|
399 |
}, |
|
400 | ! |
if (!is.null(args$row_facet)) { |
401 | ! |
teal.transform::data_extract_ui( |
402 | ! |
id = ns("row_facet"), |
403 | ! |
label = "Row facetting", |
404 | ! |
data_extract_spec = args$row_facet, |
405 | ! |
is_single_dataset = is_single_dataset_value |
406 |
) |
|
407 |
}, |
|
408 | ! |
if (!is.null(args$col_facet)) { |
409 | ! |
teal.transform::data_extract_ui( |
410 | ! |
id = ns("col_facet"), |
411 | ! |
label = "Column facetting", |
412 | ! |
data_extract_spec = args$col_facet, |
413 | ! |
is_single_dataset = is_single_dataset_value |
414 |
) |
|
415 |
}, |
|
416 | ! |
teal.widgets::panel_group( |
417 | ! |
teal.widgets::panel_item( |
418 | ! |
title = "Plot settings", |
419 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("alpha"), "Opacity:", args$alpha, ticks = FALSE), |
420 | ! |
teal.widgets::optionalSelectInput( |
421 | ! |
inputId = ns("shape"), |
422 | ! |
label = "Points shape:", |
423 | ! |
choices = args$shape, |
424 | ! |
selected = args$shape[1], |
425 | ! |
multiple = FALSE |
426 |
), |
|
427 | ! |
colourpicker::colourInput(ns("color"), "Points color:", "black"), |
428 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("size"), "Points size:", args$size, ticks = FALSE, step = .1), |
429 | ! |
checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = args$rotate_xaxis_labels), |
430 | ! |
checkboxInput(ns("add_density"), "Add marginal density", value = FALSE), |
431 | ! |
checkboxInput(ns("rug_plot"), "Include rug plot", value = FALSE), |
432 | ! |
checkboxInput(ns("show_count"), "Show N (number of observations)", value = FALSE), |
433 | ! |
shinyjs::hidden(helpText(id = ns("line_msg"), "Trendline needs numeric X and Y variables")), |
434 | ! |
teal.widgets::optionalSelectInput(ns("smoothing_degree"), "Smoothing degree", seq_len(args$max_deg)), |
435 | ! |
shinyjs::hidden(teal.widgets::optionalSelectInput(ns("color_sub"), label = "", multiple = TRUE)), |
436 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("ci"), "Confidence", c(.95, .8, .99), ticks = FALSE), |
437 | ! |
shinyjs::hidden(checkboxInput(ns("show_form"), "Show formula", value = TRUE)), |
438 | ! |
shinyjs::hidden(checkboxInput(ns("show_r2"), "Show adj-R Squared", value = TRUE)), |
439 | ! |
uiOutput(ns("num_na_removed")), |
440 | ! |
tags$div( |
441 | ! |
id = ns("label_pos"), |
442 | ! |
tags$div(tags$strong("Stats position")), |
443 | ! |
tags$div(class = "inline-block w-10", helpText("Left")), |
444 | ! |
tags$div( |
445 | ! |
class = "inline-block w-70", |
446 | ! |
teal.widgets::optionalSliderInput( |
447 | ! |
ns("pos"), |
448 | ! |
label = NULL, |
449 | ! |
min = 0, max = 1, value = .99, ticks = FALSE, step = .01 |
450 |
) |
|
451 |
), |
|
452 | ! |
tags$div(class = "inline-block w-10", helpText("Right")) |
453 |
), |
|
454 | ! |
teal.widgets::optionalSliderInput( |
455 | ! |
ns("label_size"), "Stats font size", |
456 | ! |
min = 3, max = 10, value = 5, ticks = FALSE, step = .1 |
457 |
), |
|
458 | ! |
if (!is.null(args$row_facet) || !is.null(args$col_facet)) { |
459 | ! |
checkboxInput(ns("free_scales"), "Free scales", value = FALSE) |
460 |
}, |
|
461 | ! |
selectInput( |
462 | ! |
inputId = ns("ggtheme"), |
463 | ! |
label = "Theme (by ggplot):", |
464 | ! |
choices = ggplot_themes, |
465 | ! |
selected = args$ggtheme, |
466 | ! |
multiple = FALSE |
467 |
) |
|
468 |
) |
|
469 |
) |
|
470 |
), |
|
471 | ! |
forms = tagList( |
472 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
473 |
), |
|
474 | ! |
pre_output = args$pre_output, |
475 | ! |
post_output = args$post_output |
476 |
) |
|
477 |
) |
|
478 |
} |
|
479 | ||
480 |
# Server function for the scatterplot module |
|
481 |
srv_g_scatterplot <- function(id, |
|
482 |
data, |
|
483 |
reporter, |
|
484 |
filter_panel_api, |
|
485 |
x, |
|
486 |
y, |
|
487 |
color_by, |
|
488 |
size_by, |
|
489 |
row_facet, |
|
490 |
col_facet, |
|
491 |
plot_height, |
|
492 |
plot_width, |
|
493 |
table_dec, |
|
494 |
ggplot2_args) { |
|
495 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
496 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
497 | ! |
checkmate::assert_class(data, "reactive") |
498 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
499 | ! |
moduleServer(id, function(input, output, session) { |
500 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
501 | ||
502 | ! |
data_extract <- list( |
503 | ! |
x = x, |
504 | ! |
y = y, |
505 | ! |
color_by = color_by, |
506 | ! |
size_by = size_by, |
507 | ! |
row_facet = row_facet, |
508 | ! |
col_facet = col_facet |
509 |
) |
|
510 | ||
511 | ! |
rule_diff <- function(other) { |
512 | ! |
function(value) { |
513 | ! |
othervalue <- selector_list()[[other]]()[["select"]] |
514 | ! |
if (!is.null(othervalue)) { |
515 | ! |
if (identical(value, othervalue)) { |
516 | ! |
"Row and column facetting variables must be different." |
517 |
} |
|
518 |
} |
|
519 |
} |
|
520 |
} |
|
521 | ||
522 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
523 | ! |
data_extract = data_extract, |
524 | ! |
datasets = data, |
525 | ! |
select_validation_rule = list( |
526 | ! |
x = ~ if (length(.) != 1) "Please select exactly one x var.", |
527 | ! |
y = ~ if (length(.) != 1) "Please select exactly one y var.", |
528 | ! |
color_by = ~ if (length(.) > 1) "There cannot be more than 1 color variable.", |
529 | ! |
size_by = ~ if (length(.) > 1) "There cannot be more than 1 size variable.", |
530 | ! |
row_facet = shinyvalidate::compose_rules( |
531 | ! |
shinyvalidate::sv_optional(), |
532 | ! |
rule_diff("col_facet") |
533 |
), |
|
534 | ! |
col_facet = shinyvalidate::compose_rules( |
535 | ! |
shinyvalidate::sv_optional(), |
536 | ! |
rule_diff("row_facet") |
537 |
) |
|
538 |
) |
|
539 |
) |
|
540 | ||
541 | ! |
iv_r <- reactive({ |
542 | ! |
iv_facet <- shinyvalidate::InputValidator$new() |
543 | ! |
iv <- shinyvalidate::InputValidator$new() |
544 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
545 |
}) |
|
546 | ! |
iv_facet <- shinyvalidate::InputValidator$new() |
547 | ! |
iv_facet$add_rule("add_density", ~ if ( |
548 | ! |
isTRUE(.) && |
549 |
( |
|
550 | ! |
length(selector_list()$row_facet()$select) > 0L || |
551 | ! |
length(selector_list()$col_facet()$select) > 0L |
552 |
) |
|
553 |
) { |
|
554 | ! |
"Cannot add marginal density when Row or Column facetting has been selected" |
555 |
}) |
|
556 | ! |
iv_facet$enable() |
557 | ||
558 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
559 | ! |
selector_list = selector_list, |
560 | ! |
datasets = data, |
561 | ! |
merge_function = "dplyr::inner_join" |
562 |
) |
|
563 | ||
564 | ! |
anl_merged_q <- reactive({ |
565 | ! |
req(anl_merged_input()) |
566 | ! |
data() %>% |
567 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) %>% |
568 | ! |
teal.code::eval_code(quote(ANL)) # used to display table when running show-r-code code |
569 |
}) |
|
570 | ||
571 | ! |
merged <- list( |
572 | ! |
anl_input_r = anl_merged_input, |
573 | ! |
anl_q_r = anl_merged_q |
574 |
) |
|
575 | ||
576 | ! |
trend_line_is_applicable <- reactive({ |
577 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
578 | ! |
x_var <- as.vector(merged$anl_input_r()$columns_source$x) |
579 | ! |
y_var <- as.vector(merged$anl_input_r()$columns_source$y) |
580 | ! |
length(x_var) > 0 && length(y_var) > 0 && is.numeric(ANL[[x_var]]) && is.numeric(ANL[[y_var]]) |
581 |
}) |
|
582 | ||
583 | ! |
add_trend_line <- reactive({ |
584 | ! |
smoothing_degree <- as.integer(input$smoothing_degree) |
585 | ! |
trend_line_is_applicable() && length(smoothing_degree) > 0 |
586 |
}) |
|
587 | ||
588 | ! |
if (!is.null(color_by)) { |
589 | ! |
observeEvent( |
590 | ! |
eventExpr = merged$anl_input_r()$columns_source$color_by, |
591 | ! |
handlerExpr = { |
592 | ! |
color_by_var <- as.vector(merged$anl_input_r()$columns_source$color_by) |
593 | ! |
if (length(color_by_var) > 0) { |
594 | ! |
shinyjs::hide("color") |
595 |
} else { |
|
596 | ! |
shinyjs::show("color") |
597 |
} |
|
598 |
} |
|
599 |
) |
|
600 |
} |
|
601 | ||
602 | ! |
output$num_na_removed <- renderUI({ |
603 | ! |
if (add_trend_line()) { |
604 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
605 | ! |
x_var <- as.vector(merged$anl_input_r()$columns_source$x) |
606 | ! |
y_var <- as.vector(merged$anl_input_r()$columns_source$y) |
607 | ! |
if ((num_total_na <- nrow(ANL) - nrow(stats::na.omit(ANL[, c(x_var, y_var)]))) > 0) { |
608 | ! |
tags$div(paste(num_total_na, "row(s) with missing values were removed"), tags$hr()) |
609 |
} |
|
610 |
} |
|
611 |
}) |
|
612 | ||
613 | ! |
observeEvent( |
614 | ! |
eventExpr = merged$anl_input_r()$columns_source[c("col_facet", "row_facet")], |
615 | ! |
handlerExpr = { |
616 | ! |
if ( |
617 | ! |
length(merged$anl_input_r()$columns_source$col_facet) == 0 && |
618 | ! |
length(merged$anl_input_r()$columns_source$row_facet) == 0 |
619 |
) { |
|
620 | ! |
shinyjs::hide("free_scales") |
621 |
} else { |
|
622 | ! |
shinyjs::show("free_scales") |
623 |
} |
|
624 |
} |
|
625 |
) |
|
626 | ||
627 | ! |
output_q <- reactive({ |
628 | ! |
teal::validate_inputs(iv_r(), iv_facet) |
629 | ||
630 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
631 | ||
632 | ! |
x_var <- as.vector(merged$anl_input_r()$columns_source$x) |
633 | ! |
y_var <- as.vector(merged$anl_input_r()$columns_source$y) |
634 | ! |
color_by_var <- as.vector(merged$anl_input_r()$columns_source$color_by) |
635 | ! |
size_by_var <- as.vector(merged$anl_input_r()$columns_source$size_by) |
636 | ! |
row_facet_name <- if (length(merged$anl_input_r()$columns_source$row_facet) == 0) { |
637 | ! |
character(0) |
638 |
} else { |
|
639 | ! |
as.vector(merged$anl_input_r()$columns_source$row_facet) |
640 |
} |
|
641 | ! |
col_facet_name <- if (length(merged$anl_input_r()$columns_source$col_facet) == 0) { |
642 | ! |
character(0) |
643 |
} else { |
|
644 | ! |
as.vector(merged$anl_input_r()$columns_source$col_facet) |
645 |
} |
|
646 | ! |
alpha <- input$alpha |
647 | ! |
size <- input$size |
648 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
649 | ! |
add_density <- input$add_density |
650 | ! |
ggtheme <- input$ggtheme |
651 | ! |
rug_plot <- input$rug_plot |
652 | ! |
color <- input$color |
653 | ! |
shape <- `if`(is.null(input$shape) || identical(input$shape, ""), "circle", input$shape) |
654 | ! |
smoothing_degree <- as.integer(input$smoothing_degree) |
655 | ! |
ci <- input$ci |
656 | ||
657 | ! |
log_x <- input$log_x |
658 | ! |
log_y <- input$log_y |
659 | ||
660 | ! |
validate(need( |
661 | ! |
length(row_facet_name) == 0 || inherits(ANL[[row_facet_name]], c("character", "factor", "Date", "integer")), |
662 | ! |
"`Row facetting` variable must be of class `character`, `factor`, `Date`, or `integer`" |
663 |
)) |
|
664 | ! |
validate(need( |
665 | ! |
length(col_facet_name) == 0 || inherits(ANL[[col_facet_name]], c("character", "factor", "Date", "integer")), |
666 | ! |
"`Column facetting` variable must be of class `character`, `factor`, `Date`, or `integer`" |
667 |
)) |
|
668 | ||
669 | ! |
if (add_density && length(color_by_var) > 0) { |
670 | ! |
validate(need( |
671 | ! |
!is.numeric(ANL[[color_by_var]]), |
672 | ! |
"Marginal plots cannot be produced when the points are colored by numeric variables. |
673 | ! |
\n Uncheck the 'Add marginal density' checkbox to display the plot." |
674 |
)) |
|
675 | ! |
validate(need( |
676 |
!( |
|
677 | ! |
inherits(ANL[[color_by_var]], "Date") || |
678 | ! |
inherits(ANL[[color_by_var]], "POSIXct") || |
679 | ! |
inherits(ANL[[color_by_var]], "POSIXlt") |
680 |
), |
|
681 | ! |
"Marginal plots cannot be produced when the points are colored by Date or POSIX variables. |
682 | ! |
\n Uncheck the 'Add marginal density' checkbox to display the plot." |
683 |
)) |
|
684 |
} |
|
685 | ||
686 | ! |
teal::validate_has_data(ANL[, c(x_var, y_var)], 10, complete = TRUE, allow_inf = FALSE) |
687 | ||
688 | ! |
if (log_x) { |
689 | ! |
validate( |
690 | ! |
need( |
691 | ! |
is.numeric(ANL[[x_var]]) && all( |
692 | ! |
ANL[[x_var]] > 0 | is.na(ANL[[x_var]]) |
693 |
), |
|
694 | ! |
"X variable can only be log transformed if variable is numeric and all values are positive." |
695 |
) |
|
696 |
) |
|
697 |
} |
|
698 | ! |
if (log_y) { |
699 | ! |
validate( |
700 | ! |
need( |
701 | ! |
is.numeric(ANL[[y_var]]) && all( |
702 | ! |
ANL[[y_var]] > 0 | is.na(ANL[[y_var]]) |
703 |
), |
|
704 | ! |
"Y variable can only be log transformed if variable is numeric and all values are positive." |
705 |
) |
|
706 |
) |
|
707 |
} |
|
708 | ||
709 | ! |
facet_cl <- facet_ggplot_call( |
710 | ! |
row_facet_name, |
711 | ! |
col_facet_name, |
712 | ! |
free_x_scales = isTRUE(input$free_scales), |
713 | ! |
free_y_scales = isTRUE(input$free_scales) |
714 |
) |
|
715 | ||
716 | ! |
point_sizes <- if (length(size_by_var) > 0) { |
717 | ! |
validate(need(is.numeric(ANL[[size_by_var]]), "Variable to size by must be numeric")) |
718 | ! |
substitute( |
719 | ! |
expr = size * ANL[[size_by_var]] / max(ANL[[size_by_var]], na.rm = TRUE), |
720 | ! |
env = list(size = size, size_by_var = size_by_var) |
721 |
) |
|
722 |
} else { |
|
723 | ! |
size |
724 |
} |
|
725 | ||
726 | ! |
plot_q <- merged$anl_q_r() |
727 | ||
728 | ! |
if (log_x) { |
729 | ! |
log_x_fn <- input$log_x_base |
730 | ! |
plot_q <- teal.code::eval_code( |
731 | ! |
object = plot_q, |
732 | ! |
code = substitute( |
733 | ! |
expr = ANL[, log_x_var] <- log_x_fn(ANL[, x_var]), |
734 | ! |
env = list( |
735 | ! |
x_var = x_var, |
736 | ! |
log_x_fn = as.name(log_x_fn), |
737 | ! |
log_x_var = paste0(log_x_fn, "_", x_var) |
738 |
) |
|
739 |
) |
|
740 |
) |
|
741 |
} |
|
742 | ||
743 | ! |
if (log_y) { |
744 | ! |
log_y_fn <- input$log_y_base |
745 | ! |
plot_q <- teal.code::eval_code( |
746 | ! |
object = plot_q, |
747 | ! |
code = substitute( |
748 | ! |
expr = ANL[, log_y_var] <- log_y_fn(ANL[, y_var]), |
749 | ! |
env = list( |
750 | ! |
y_var = y_var, |
751 | ! |
log_y_fn = as.name(log_y_fn), |
752 | ! |
log_y_var = paste0(log_y_fn, "_", y_var) |
753 |
) |
|
754 |
) |
|
755 |
) |
|
756 |
} |
|
757 | ||
758 | ! |
pre_pro_anl <- if (input$show_count) { |
759 | ! |
paste0( |
760 | ! |
"ANL %>% dplyr::group_by(", |
761 | ! |
paste( |
762 | ! |
c( |
763 | ! |
if (length(color_by_var) > 0 && inherits(ANL[[color_by_var]], c("factor", "character"))) color_by_var, |
764 | ! |
row_facet_name, |
765 | ! |
col_facet_name |
766 |
), |
|
767 | ! |
collapse = ", " |
768 |
), |
|
769 | ! |
") %>% dplyr::mutate(n = dplyr::n()) %>% dplyr::ungroup()" |
770 |
) |
|
771 |
} else { |
|
772 | ! |
"ANL" |
773 |
} |
|
774 | ||
775 | ! |
plot_call <- substitute(expr = pre_pro_anl %>% ggplot(), env = list(pre_pro_anl = str2lang(pre_pro_anl))) |
776 | ||
777 | ! |
plot_call <- if (length(color_by_var) == 0) { |
778 | ! |
substitute( |
779 | ! |
expr = plot_call + |
780 | ! |
ggplot2::aes(x = x_name, y = y_name) + |
781 | ! |
ggplot2::geom_point(alpha = alpha_value, size = point_sizes, shape = shape_value, color = color_value), |
782 | ! |
env = list( |
783 | ! |
plot_call = plot_call, |
784 | ! |
x_name = if (log_x) as.name(paste0(log_x_fn, "_", x_var)) else as.name(x_var), |
785 | ! |
y_name = if (log_y) as.name(paste0(log_y_fn, "_", y_var)) else as.name(y_var), |
786 | ! |
alpha_value = alpha, |
787 | ! |
point_sizes = point_sizes, |
788 | ! |
shape_value = shape, |
789 | ! |
color_value = color |
790 |
) |
|
791 |
) |
|
792 |
} else { |
|
793 | ! |
substitute( |
794 | ! |
expr = plot_call + |
795 | ! |
ggplot2::aes(x = x_name, y = y_name, color = color_by_var_name) + |
796 | ! |
ggplot2::geom_point(alpha = alpha_value, size = point_sizes, shape = shape_value), |
797 | ! |
env = list( |
798 | ! |
plot_call = plot_call, |
799 | ! |
x_name = if (log_x) as.name(paste0(log_x_fn, "_", x_var)) else as.name(x_var), |
800 | ! |
y_name = if (log_y) as.name(paste0(log_y_fn, "_", y_var)) else as.name(y_var), |
801 | ! |
color_by_var_name = as.name(color_by_var), |
802 | ! |
alpha_value = alpha, |
803 | ! |
point_sizes = point_sizes, |
804 | ! |
shape_value = shape |
805 |
) |
|
806 |
) |
|
807 |
} |
|
808 | ||
809 | ! |
if (rug_plot) plot_call <- substitute(expr = plot_call + geom_rug(), env = list(plot_call = plot_call)) |
810 | ||
811 | ! |
plot_label_generator <- function(rhs_formula = quote(y ~ 1), |
812 | ! |
show_form = input$show_form, |
813 | ! |
show_r2 = input$show_r2, |
814 | ! |
show_count = input$show_count, |
815 | ! |
pos = input$pos, |
816 | ! |
label_size = input$label_size) { |
817 | ! |
stopifnot(sum(show_form, show_r2, show_count) >= 1) |
818 | ! |
aes_label <- paste0( |
819 | ! |
"aes(", |
820 | ! |
if (show_count) "n = n, ", |
821 | ! |
"label = ", |
822 | ! |
if (sum(show_form, show_r2, show_count) > 1) "paste(", |
823 | ! |
paste( |
824 | ! |
c( |
825 | ! |
if (show_form) "stat(eq.label)", |
826 | ! |
if (show_r2) "stat(adj.rr.label)", |
827 | ! |
if (show_count) "paste('N ~`=`~', n)" |
828 |
), |
|
829 | ! |
collapse = ", " |
830 |
), |
|
831 | ! |
if (sum(show_form, show_r2, show_count) > 1) ", sep = '*\", \"*'))" else ")" |
832 |
) |
|
833 | ! |
label_geom <- substitute( |
834 | ! |
expr = ggpmisc::stat_poly_eq( |
835 | ! |
mapping = aes_label, |
836 | ! |
formula = rhs_formula, |
837 | ! |
parse = TRUE, |
838 | ! |
label.x = pos, |
839 | ! |
size = label_size |
840 |
), |
|
841 | ! |
env = list( |
842 | ! |
rhs_formula = rhs_formula, |
843 | ! |
pos = pos, |
844 | ! |
aes_label = str2lang(aes_label), |
845 | ! |
label_size = label_size |
846 |
) |
|
847 |
) |
|
848 | ! |
substitute( |
849 | ! |
expr = plot_call + label_geom, |
850 | ! |
env = list( |
851 | ! |
plot_call = plot_call, |
852 | ! |
label_geom = label_geom |
853 |
) |
|
854 |
) |
|
855 |
} |
|
856 | ||
857 | ! |
if (trend_line_is_applicable()) { |
858 | ! |
shinyjs::hide("line_msg") |
859 | ! |
shinyjs::show("smoothing_degree") |
860 | ! |
if (!add_trend_line()) { |
861 | ! |
shinyjs::hide("ci") |
862 | ! |
shinyjs::hide("color_sub") |
863 | ! |
shinyjs::hide("show_form") |
864 | ! |
shinyjs::hide("show_r2") |
865 | ! |
if (input$show_count) { |
866 | ! |
plot_call <- plot_label_generator(show_form = FALSE, show_r2 = FALSE) |
867 | ! |
shinyjs::show("label_pos") |
868 | ! |
shinyjs::show("label_size") |
869 |
} else { |
|
870 | ! |
shinyjs::hide("label_pos") |
871 | ! |
shinyjs::hide("label_size") |
872 |
} |
|
873 |
} else { |
|
874 | ! |
shinyjs::show("ci") |
875 | ! |
shinyjs::show("show_form") |
876 | ! |
shinyjs::show("show_r2") |
877 | ! |
if (nrow(ANL) - nrow(stats::na.omit(ANL[, c(x_var, y_var)])) > 0) { |
878 | ! |
plot_q <- teal.code::eval_code( |
879 | ! |
plot_q, |
880 | ! |
substitute( |
881 | ! |
expr = ANL <- dplyr::filter(ANL, !is.na(x_var) & !is.na(y_var)), |
882 | ! |
env = list(x_var = as.name(x_var), y_var = as.name(y_var)) |
883 |
) |
|
884 |
) |
|
885 |
} |
|
886 | ! |
rhs_formula <- substitute( |
887 | ! |
expr = y ~ poly(x, smoothing_degree, raw = TRUE), |
888 | ! |
env = list(smoothing_degree = smoothing_degree) |
889 |
) |
|
890 | ! |
if (input$show_form || input$show_r2 || input$show_count) { |
891 | ! |
plot_call <- plot_label_generator(rhs_formula = rhs_formula) |
892 | ! |
shinyjs::show("label_pos") |
893 | ! |
shinyjs::show("label_size") |
894 |
} else { |
|
895 | ! |
shinyjs::hide("label_pos") |
896 | ! |
shinyjs::hide("label_size") |
897 |
} |
|
898 | ! |
plot_call <- substitute( |
899 | ! |
expr = plot_call + ggplot2::geom_smooth(formula = rhs_formula, se = TRUE, level = ci, method = "lm"), |
900 | ! |
env = list(plot_call = plot_call, rhs_formula = rhs_formula, ci = ci) |
901 |
) |
|
902 |
} |
|
903 |
} else { |
|
904 | ! |
shinyjs::hide("smoothing_degree") |
905 | ! |
shinyjs::hide("ci") |
906 | ! |
shinyjs::hide("color_sub") |
907 | ! |
shinyjs::hide("show_form") |
908 | ! |
shinyjs::hide("show_r2") |
909 | ! |
if (input$show_count) { |
910 | ! |
plot_call <- plot_label_generator(show_form = FALSE, show_r2 = FALSE) |
911 | ! |
shinyjs::show("label_pos") |
912 | ! |
shinyjs::show("label_size") |
913 |
} else { |
|
914 | ! |
shinyjs::hide("label_pos") |
915 | ! |
shinyjs::hide("label_size") |
916 |
} |
|
917 | ! |
shinyjs::show("line_msg") |
918 |
} |
|
919 | ||
920 | ! |
if (!is.null(facet_cl)) { |
921 | ! |
plot_call <- substitute(expr = plot_call + facet_cl, env = list(plot_call = plot_call, facet_cl = facet_cl)) |
922 |
} |
|
923 | ||
924 | ! |
y_label <- varname_w_label( |
925 | ! |
y_var, |
926 | ! |
ANL, |
927 | ! |
prefix = if (log_y) paste(log_y_fn, "(") else NULL, |
928 | ! |
suffix = if (log_y) ")" else NULL |
929 |
) |
|
930 | ! |
x_label <- varname_w_label( |
931 | ! |
x_var, |
932 | ! |
ANL, |
933 | ! |
prefix = if (log_x) paste(log_x_fn, "(") else NULL, |
934 | ! |
suffix = if (log_x) ")" else NULL |
935 |
) |
|
936 | ||
937 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
938 | ! |
labs = list(y = y_label, x = x_label), |
939 | ! |
theme = list(legend.position = "bottom") |
940 |
) |
|
941 | ||
942 | ! |
if (rotate_xaxis_labels) { |
943 | ! |
dev_ggplot2_args$theme[["axis.text.x"]] <- quote(element_text(angle = 45, hjust = 1)) |
944 |
} |
|
945 | ||
946 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
947 | ! |
user_plot = ggplot2_args, |
948 | ! |
module_plot = dev_ggplot2_args |
949 |
) |
|
950 | ||
951 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args(all_ggplot2_args, ggtheme = ggtheme) |
952 | ||
953 | ||
954 | ! |
if (add_density) { |
955 | ! |
plot_call <- substitute( |
956 | ! |
expr = ggExtra::ggMarginal( |
957 | ! |
plot_call + labs + ggthemes + themes, |
958 | ! |
type = "density", |
959 | ! |
groupColour = group_colour |
960 |
), |
|
961 | ! |
env = list( |
962 | ! |
plot_call = plot_call, |
963 | ! |
group_colour = if (length(color_by_var) > 0) TRUE else FALSE, |
964 | ! |
labs = parsed_ggplot2_args$labs, |
965 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
966 | ! |
themes = parsed_ggplot2_args$theme |
967 |
) |
|
968 |
) |
|
969 |
} else { |
|
970 | ! |
plot_call <- substitute( |
971 | ! |
expr = plot_call + |
972 | ! |
labs + |
973 | ! |
ggthemes + |
974 | ! |
themes, |
975 | ! |
env = list( |
976 | ! |
plot_call = plot_call, |
977 | ! |
labs = parsed_ggplot2_args$labs, |
978 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
979 | ! |
themes = parsed_ggplot2_args$theme |
980 |
) |
|
981 |
) |
|
982 |
} |
|
983 | ||
984 | ! |
plot_call <- substitute(expr = p <- plot_call, env = list(plot_call = plot_call)) |
985 | ||
986 | ! |
teal.code::eval_code(plot_q, plot_call) %>% |
987 | ! |
teal.code::eval_code(quote(print(p))) |
988 |
}) |
|
989 | ||
990 | ! |
plot_r <- reactive(output_q()[["p"]]) |
991 | ||
992 |
# Insert the plot into a plot_with_settings module from teal.widgets |
|
993 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
994 | ! |
id = "scatter_plot", |
995 | ! |
plot_r = plot_r, |
996 | ! |
height = plot_height, |
997 | ! |
width = plot_width, |
998 | ! |
brushing = TRUE |
999 |
) |
|
1000 | ||
1001 | ! |
output$data_table <- DT::renderDataTable({ |
1002 | ! |
plot_brush <- pws$brush() |
1003 | ||
1004 | ! |
if (!is.null(plot_brush)) { |
1005 | ! |
validate(need(!input$add_density, "Brushing feature is currently not supported when plot has marginal density")) |
1006 |
} |
|
1007 | ||
1008 | ! |
merged_data <- isolate(teal.code::dev_suppress(output_q()[["ANL"]])) |
1009 | ||
1010 | ! |
brushed_df <- teal.widgets::clean_brushedPoints(merged_data, plot_brush) |
1011 | ! |
numeric_cols <- names(brushed_df)[ |
1012 | ! |
vapply(brushed_df, function(x) is.numeric(x) && !is.integer(x), FUN.VALUE = logical(1)) |
1013 |
] |
|
1014 | ||
1015 | ! |
if (length(numeric_cols) > 0) { |
1016 | ! |
DT::formatRound( |
1017 | ! |
DT::datatable(brushed_df, |
1018 | ! |
rownames = FALSE, |
1019 | ! |
options = list(scrollX = TRUE, pageLength = input$data_table_rows) |
1020 |
), |
|
1021 | ! |
numeric_cols, |
1022 | ! |
table_dec |
1023 |
) |
|
1024 |
} else { |
|
1025 | ! |
DT::datatable(brushed_df, rownames = FALSE, options = list(scrollX = TRUE, pageLength = input$data_table_rows)) |
1026 |
} |
|
1027 |
}) |
|
1028 | ||
1029 | ! |
teal.widgets::verbatim_popup_srv( |
1030 | ! |
id = "rcode", |
1031 | ! |
verbatim_content = reactive(teal.code::get_code(output_q())), |
1032 | ! |
title = "R Code for scatterplot" |
1033 |
) |
|
1034 | ||
1035 |
### REPORTER |
|
1036 | ! |
if (with_reporter) { |
1037 | ! |
card_fun <- function(comment, label) { |
1038 | ! |
card <- teal::report_card_template( |
1039 | ! |
title = "Scatter Plot", |
1040 | ! |
label = label, |
1041 | ! |
with_filter = with_filter, |
1042 | ! |
filter_panel_api = filter_panel_api |
1043 |
) |
|
1044 | ! |
card$append_text("Plot", "header3") |
1045 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
1046 | ! |
if (!comment == "") { |
1047 | ! |
card$append_text("Comment", "header3") |
1048 | ! |
card$append_text(comment) |
1049 |
} |
|
1050 | ! |
card$append_src(teal.code::get_code(output_q())) |
1051 | ! |
card |
1052 |
} |
|
1053 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
1054 |
} |
|
1055 |
### |
|
1056 |
}) |
|
1057 |
} |
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 |
#' @param ggtheme (`character`) optional, specifies the default `ggplot2` theme for plots. Defaults to `classic`. |
|
14 |
#' |
|
15 |
#' @templateVar ggnames "Summary Obs", "Summary Patients", "Combinations Main", "Combinations Hist", "By Subject" |
|
16 |
#' @template ggplot2_args_multi |
|
17 |
#' |
|
18 |
#' @inherit shared_params return |
|
19 |
#' |
|
20 |
#' @examplesShinylive |
|
21 |
#' library(teal.modules.general) |
|
22 |
#' interactive <- function() TRUE |
|
23 |
#' {{ next_example }} |
|
24 |
#' @examplesIf require("gridExtra", quietly = TRUE) && require("rlang", quietly = TRUE) |
|
25 |
#' # general example data |
|
26 |
#' data <- teal_data() |
|
27 |
#' data <- within(data, { |
|
28 |
#' require(nestcolor) |
|
29 |
#' |
|
30 |
#' add_nas <- function(x) { |
|
31 |
#' x[sample(seq_along(x), floor(length(x) * runif(1, .05, .17)))] <- NA |
|
32 |
#' x |
|
33 |
#' } |
|
34 |
#' |
|
35 |
#' iris <- iris |
|
36 |
#' mtcars <- mtcars |
|
37 |
#' |
|
38 |
#' iris[] <- lapply(iris, add_nas) |
|
39 |
#' mtcars[] <- lapply(mtcars, add_nas) |
|
40 |
#' mtcars[["cyl"]] <- as.factor(mtcars[["cyl"]]) |
|
41 |
#' mtcars[["gear"]] <- as.factor(mtcars[["gear"]]) |
|
42 |
#' }) |
|
43 |
#' |
|
44 |
#' app <- init( |
|
45 |
#' data = data, |
|
46 |
#' modules = modules( |
|
47 |
#' tm_missing_data() |
|
48 |
#' ) |
|
49 |
#' ) |
|
50 |
#' if (interactive()) { |
|
51 |
#' shinyApp(app$ui, app$server) |
|
52 |
#' } |
|
53 |
#' |
|
54 |
#' @examplesShinylive |
|
55 |
#' library(teal.modules.general) |
|
56 |
#' interactive <- function() TRUE |
|
57 |
#' {{ next_example }} |
|
58 |
#' @examplesIf require("gridExtra", quietly = TRUE) && require("rlang", quietly = TRUE) |
|
59 |
#' # CDISC example data |
|
60 |
#' data <- teal_data() |
|
61 |
#' data <- within(data, { |
|
62 |
#' require(nestcolor) |
|
63 |
#' ADSL <- rADSL |
|
64 |
#' ADRS <- rADRS |
|
65 |
#' }) |
|
66 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
67 |
#' |
|
68 |
#' app <- init( |
|
69 |
#' data = data, |
|
70 |
#' modules = modules( |
|
71 |
#' tm_missing_data() |
|
72 |
#' ) |
|
73 |
#' ) |
|
74 |
#' if (interactive()) { |
|
75 |
#' shinyApp(app$ui, app$server) |
|
76 |
#' } |
|
77 |
#' |
|
78 |
#' @export |
|
79 |
#' |
|
80 |
tm_missing_data <- function(label = "Missing data", |
|
81 |
plot_height = c(600, 400, 5000), |
|
82 |
plot_width = NULL, |
|
83 |
parent_dataname = "ADSL", |
|
84 |
ggtheme = c("classic", "gray", "bw", "linedraw", "light", "dark", "minimal", "void"), |
|
85 |
ggplot2_args = list( |
|
86 |
"Combinations Hist" = teal.widgets::ggplot2_args(labs = list(caption = NULL)), |
|
87 |
"Combinations Main" = teal.widgets::ggplot2_args(labs = list(title = NULL)) |
|
88 |
), |
|
89 |
pre_output = NULL, |
|
90 |
post_output = NULL) { |
|
91 | ! |
message("Initializing tm_missing_data") |
92 | ||
93 |
# Requires Suggested packages |
|
94 | ! |
if (!requireNamespace("gridExtra", quietly = TRUE)) { |
95 | ! |
stop("Cannot load gridExtra - please install the package or restart your session.") |
96 |
} |
|
97 | ! |
if (!requireNamespace("rlang", quietly = TRUE)) { |
98 | ! |
stop("Cannot load rlang - please install the package or restart your session.") |
99 |
} |
|
100 | ||
101 |
# Normalize the parameters |
|
102 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
103 | ||
104 |
# Start of assertions |
|
105 | ! |
checkmate::assert_string(label) |
106 | ||
107 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
108 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
109 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
110 | ! |
checkmate::assert_numeric( |
111 | ! |
plot_width[1], |
112 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
113 |
) |
|
114 | ||
115 | ! |
checkmate::assert_character(parent_dataname, min.len = 0, max.len = 1) |
116 | ! |
ggtheme <- match.arg(ggtheme) |
117 | ||
118 | ! |
plot_choices <- c("Summary Obs", "Summary Patients", "Combinations Main", "Combinations Hist", "By Subject") |
119 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
120 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
121 | ||
122 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
123 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
124 |
# End of assertions |
|
125 | ||
126 | ! |
ans <- module( |
127 | ! |
label, |
128 | ! |
server = srv_page_missing_data, |
129 | ! |
server_args = list( |
130 | ! |
parent_dataname = parent_dataname, plot_height = plot_height, |
131 | ! |
plot_width = plot_width, ggplot2_args = ggplot2_args, ggtheme = ggtheme |
132 |
), |
|
133 | ! |
ui = ui_page_missing_data, |
134 | ! |
datanames = "all", |
135 | ! |
ui_args = list(pre_output = pre_output, post_output = post_output) |
136 |
) |
|
137 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
138 | ! |
ans |
139 |
} |
|
140 | ||
141 |
# UI function for the missing data module (all datasets) |
|
142 |
ui_page_missing_data <- function(id, pre_output = NULL, post_output = NULL) { |
|
143 | ! |
ns <- NS(id) |
144 | ! |
tagList( |
145 | ! |
include_css_files("custom"), |
146 | ! |
teal.widgets::standard_layout( |
147 | ! |
output = teal.widgets::white_small_well( |
148 | ! |
tags$div( |
149 | ! |
class = "flex", |
150 | ! |
column( |
151 | ! |
width = 12, |
152 | ! |
uiOutput(ns("dataset_tabs")) |
153 |
) |
|
154 |
) |
|
155 |
), |
|
156 | ! |
encoding = tags$div( |
157 | ! |
uiOutput(ns("dataset_encodings")) |
158 |
), |
|
159 | ! |
uiOutput(ns("dataset_reporter")), |
160 | ! |
pre_output = pre_output, |
161 | ! |
post_output = post_output |
162 |
) |
|
163 |
) |
|
164 |
} |
|
165 | ||
166 |
# Server function for the missing data module (all datasets) |
|
167 |
srv_page_missing_data <- function(id, data, reporter, filter_panel_api, parent_dataname, |
|
168 |
plot_height, plot_width, ggplot2_args, ggtheme) { |
|
169 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
170 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
171 | ! |
moduleServer(id, function(input, output, session) { |
172 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
173 | ||
174 | ! |
datanames <- isolate(names(data())) |
175 | ! |
datanames <- Filter( |
176 | ! |
function(name) is.data.frame(isolate(data())[[name]]), |
177 | ! |
datanames |
178 |
) |
|
179 | ! |
if_subject_plot <- length(parent_dataname) > 0 && parent_dataname %in% datanames |
180 | ||
181 | ! |
ns <- session$ns |
182 | ||
183 | ! |
output$dataset_tabs <- renderUI({ |
184 | ! |
do.call( |
185 | ! |
tabsetPanel, |
186 | ! |
c( |
187 | ! |
id = ns("dataname_tab"), |
188 | ! |
lapply( |
189 | ! |
datanames, |
190 | ! |
function(x) { |
191 | ! |
tabPanel( |
192 | ! |
title = x, |
193 | ! |
column( |
194 | ! |
width = 12, |
195 | ! |
tags$div( |
196 | ! |
class = "mt-4", |
197 | ! |
ui_missing_data(id = ns(x), by_subject_plot = if_subject_plot) |
198 |
) |
|
199 |
) |
|
200 |
) |
|
201 |
} |
|
202 |
) |
|
203 |
) |
|
204 |
) |
|
205 |
}) |
|
206 | ||
207 | ! |
output$dataset_encodings <- renderUI({ |
208 | ! |
tagList( |
209 | ! |
lapply( |
210 | ! |
datanames, |
211 | ! |
function(x) { |
212 | ! |
conditionalPanel( |
213 | ! |
is_tab_active_js(ns("dataname_tab"), x), |
214 | ! |
encoding_missing_data( |
215 | ! |
id = ns(x), |
216 | ! |
summary_per_patient = if_subject_plot, |
217 | ! |
ggtheme = ggtheme, |
218 | ! |
datanames = datanames |
219 |
) |
|
220 |
) |
|
221 |
} |
|
222 |
) |
|
223 |
) |
|
224 |
}) |
|
225 | ||
226 | ! |
output$dataset_reporter <- renderUI({ |
227 | ! |
lapply(datanames, function(x) { |
228 | ! |
dataname_ns <- NS(ns(x)) |
229 | ||
230 | ! |
conditionalPanel( |
231 | ! |
is_tab_active_js(ns("dataname_tab"), x), |
232 | ! |
tagList( |
233 | ! |
teal.widgets::verbatim_popup_ui(dataname_ns("rcode"), "Show R code") |
234 |
) |
|
235 |
) |
|
236 |
}) |
|
237 |
}) |
|
238 | ||
239 | ! |
lapply( |
240 | ! |
datanames, |
241 | ! |
function(x) { |
242 | ! |
srv_missing_data( |
243 | ! |
id = x, |
244 | ! |
data = data, |
245 | ! |
reporter = if (with_reporter) reporter, |
246 | ! |
filter_panel_api = if (with_filter) filter_panel_api, |
247 | ! |
dataname = x, |
248 | ! |
parent_dataname = parent_dataname, |
249 | ! |
plot_height = plot_height, |
250 | ! |
plot_width = plot_width, |
251 | ! |
ggplot2_args = ggplot2_args |
252 |
) |
|
253 |
} |
|
254 |
) |
|
255 |
}) |
|
256 |
} |
|
257 | ||
258 |
# UI function for the missing data module (single dataset) |
|
259 |
ui_missing_data <- function(id, by_subject_plot = FALSE) { |
|
260 | ! |
ns <- NS(id) |
261 | ||
262 | ! |
tab_list <- list( |
263 | ! |
tabPanel( |
264 | ! |
"Summary", |
265 | ! |
teal.widgets::plot_with_settings_ui(id = ns("summary_plot")), |
266 | ! |
helpText( |
267 | ! |
tags$p(paste( |
268 | ! |
'The "Summary" graph shows the number of missing values per variable (both absolute and percentage),', |
269 | ! |
"sorted by magnitude." |
270 |
)), |
|
271 | ! |
tags$p( |
272 | ! |
'The "summary per patients" graph is showing how many subjects have at least one missing observation', |
273 | ! |
"for each variable. It will be most useful for panel datasets." |
274 |
) |
|
275 |
) |
|
276 |
), |
|
277 | ! |
tabPanel( |
278 | ! |
"Combinations", |
279 | ! |
teal.widgets::plot_with_settings_ui(id = ns("combination_plot")), |
280 | ! |
helpText( |
281 | ! |
tags$p(paste( |
282 | ! |
'The "Combinations" graph is used to explore the relationship between the missing data within', |
283 | ! |
"different columns of the dataset.", |
284 | ! |
"It shows the different patterns of missingness in the rows of the data.", |
285 | ! |
'For example, suppose that 70 rows of the data have exactly columns "A" and "B" missing.', |
286 | ! |
"In this case there would be a bar of height 70 in the top graph and", |
287 | ! |
'the column below this in the second graph would have rows "A" and "B" cells shaded red.' |
288 |
)), |
|
289 | ! |
tags$p(paste( |
290 | ! |
"Due to the large number of missing data patterns possible, only those with a large set of observations", |
291 | ! |
'are shown in the graph and the "Combination cut-off" slider can be used to adjust the number shown.' |
292 |
)) |
|
293 |
) |
|
294 |
), |
|
295 | ! |
tabPanel( |
296 | ! |
"By Variable Levels", |
297 | ! |
teal.widgets::get_dt_rows(ns("levels_table"), ns("levels_table_rows")), |
298 | ! |
DT::dataTableOutput(ns("levels_table")) |
299 |
) |
|
300 |
) |
|
301 | ! |
if (isTRUE(by_subject_plot)) { |
302 | ! |
tab_list <- append( |
303 | ! |
tab_list, |
304 | ! |
list(tabPanel( |
305 | ! |
"Grouped by Subject", |
306 | ! |
teal.widgets::plot_with_settings_ui(id = ns("by_subject_plot")), |
307 | ! |
helpText( |
308 | ! |
tags$p(paste( |
309 | ! |
"This graph shows the missingness with respect to subjects rather than individual rows of the", |
310 | ! |
"dataset. Each row represents one dataset variable and each column a single subject. Only subjects", |
311 | ! |
"with at least one record in this dataset are shown. For a given subject, if they have any missing", |
312 | ! |
"values of a specific variable then the appropriate cell in the graph is marked as missing." |
313 |
)) |
|
314 |
) |
|
315 |
)) |
|
316 |
) |
|
317 |
} |
|
318 | ||
319 | ! |
do.call( |
320 | ! |
tabsetPanel, |
321 | ! |
c( |
322 | ! |
id = ns("summary_type"), |
323 | ! |
tab_list |
324 |
) |
|
325 |
) |
|
326 |
} |
|
327 | ||
328 |
# UI encoding for the missing data module (all datasets) |
|
329 |
encoding_missing_data <- function(id, summary_per_patient = FALSE, ggtheme, datanames) { |
|
330 | ! |
ns <- NS(id) |
331 | ||
332 | ! |
tagList( |
333 |
### Reporter |
|
334 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
335 |
### |
|
336 | ! |
tags$label("Encodings", class = "text-primary"), |
337 | ! |
helpText( |
338 | ! |
paste0("Dataset", `if`(length(datanames) > 1, "s", ""), ":"), |
339 | ! |
tags$code(paste(datanames, collapse = ", ")) |
340 |
), |
|
341 | ! |
uiOutput(ns("variables")), |
342 | ! |
actionButton( |
343 | ! |
ns("filter_na"), |
344 | ! |
tags$span("Select only vars with missings", class = "whitespace-normal"), |
345 | ! |
width = "100%", |
346 | ! |
class = "mb-4" |
347 |
), |
|
348 | ! |
conditionalPanel( |
349 | ! |
is_tab_active_js(ns("summary_type"), "Summary"), |
350 | ! |
checkboxInput( |
351 | ! |
ns("any_na"), |
352 | ! |
tags$div( |
353 | ! |
class = "teal-tooltip", |
354 | ! |
tagList( |
355 | ! |
"Add **anyna** variable", |
356 | ! |
icon("circle-info"), |
357 | ! |
tags$span( |
358 | ! |
class = "tooltiptext", |
359 | ! |
"Describes the number of observations with at least one missing value in any variable." |
360 |
) |
|
361 |
) |
|
362 |
), |
|
363 | ! |
value = FALSE |
364 |
), |
|
365 | ! |
if (summary_per_patient) { |
366 | ! |
checkboxInput( |
367 | ! |
ns("if_patients_plot"), |
368 | ! |
tags$div( |
369 | ! |
class = "teal-tooltip", |
370 | ! |
tagList( |
371 | ! |
"Add summary per patients", |
372 | ! |
icon("circle-info"), |
373 | ! |
tags$span( |
374 | ! |
class = "tooltiptext", |
375 | ! |
paste( |
376 | ! |
"Displays the number of missing values per observation,", |
377 | ! |
"where the x-axis is sorted by observation appearance in the table." |
378 |
) |
|
379 |
) |
|
380 |
) |
|
381 |
), |
|
382 | ! |
value = FALSE |
383 |
) |
|
384 |
} |
|
385 |
), |
|
386 | ! |
conditionalPanel( |
387 | ! |
is_tab_active_js(ns("summary_type"), "Combinations"), |
388 | ! |
uiOutput(ns("cutoff")) |
389 |
), |
|
390 | ! |
conditionalPanel( |
391 | ! |
is_tab_active_js(ns("summary_type"), "By Variable Levels"), |
392 | ! |
tagList( |
393 | ! |
uiOutput(ns("group_by_var_ui")), |
394 | ! |
uiOutput(ns("group_by_vals_ui")), |
395 | ! |
radioButtons( |
396 | ! |
ns("count_type"), |
397 | ! |
label = "Display missing as", |
398 | ! |
choices = c("counts", "proportions"), |
399 | ! |
selected = "counts", |
400 | ! |
inline = TRUE |
401 |
) |
|
402 |
) |
|
403 |
), |
|
404 | ! |
teal.widgets::panel_item( |
405 | ! |
title = "Plot settings", |
406 | ! |
selectInput( |
407 | ! |
inputId = ns("ggtheme"), |
408 | ! |
label = "Theme (by ggplot):", |
409 | ! |
choices = ggplot_themes, |
410 | ! |
selected = ggtheme, |
411 | ! |
multiple = FALSE |
412 |
) |
|
413 |
) |
|
414 |
) |
|
415 |
} |
|
416 | ||
417 |
# Server function for the missing data (single dataset) |
|
418 |
srv_missing_data <- function(id, data, reporter, filter_panel_api, dataname, parent_dataname, |
|
419 |
plot_height, plot_width, ggplot2_args) { |
|
420 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
421 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
422 | ! |
checkmate::assert_class(data, "reactive") |
423 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
424 | ! |
moduleServer(id, function(input, output, session) { |
425 | ! |
ns <- session$ns |
426 | ||
427 | ! |
prev_group_by_var <- reactiveVal("") |
428 | ! |
data_r <- reactive(data()[[dataname]]) |
429 | ! |
data_keys <- reactive(unlist(teal.data::join_keys(data())[[dataname]])) |
430 | ||
431 | ! |
iv_r <- reactive({ |
432 | ! |
iv <- shinyvalidate::InputValidator$new() |
433 | ! |
iv$add_rule( |
434 | ! |
"variables_select", |
435 | ! |
shinyvalidate::sv_required("At least one reference variable needs to be selected.") |
436 |
) |
|
437 | ! |
iv$add_rule( |
438 | ! |
"variables_select", |
439 | ! |
~ if (length(setdiff((.), data_keys())) < 1) "Please also select non-key columns." |
440 |
) |
|
441 | ! |
iv_summary_table <- shinyvalidate::InputValidator$new() |
442 | ! |
iv_summary_table$condition(~ isTRUE(input$summary_type == "By Variable Levels")) |
443 | ! |
iv_summary_table$add_rule("count_type", shinyvalidate::sv_required("Please select type of counts")) |
444 | ! |
iv_summary_table$add_rule( |
445 | ! |
"group_by_vals", |
446 | ! |
shinyvalidate::sv_required("Please select both group-by variable and values") |
447 |
) |
|
448 | ! |
iv_summary_table$add_rule( |
449 | ! |
"group_by_var", |
450 | ! |
~ if (length(.) > 0 && length(input$variables_select) == 1 && (.) == input$variables_select) { |
451 | ! |
"If only one reference variable is selected it must not be the grouping variable." |
452 |
} |
|
453 |
) |
|
454 | ! |
iv_summary_table$add_rule( |
455 | ! |
"variables_select", |
456 | ! |
~ if (length(input$group_by_var) > 0 && length(.) == 1 && (.) == input$group_by_var) { |
457 | ! |
"If only one reference variable is selected it must not be the grouping variable." |
458 |
} |
|
459 |
) |
|
460 | ! |
iv$add_validator(iv_summary_table) |
461 | ! |
iv$enable() |
462 | ! |
iv |
463 |
}) |
|
464 | ||
465 | ||
466 | ! |
data_parent_keys <- reactive({ |
467 | ! |
if (length(parent_dataname) > 0 && parent_dataname %in% names(data())) { |
468 | ! |
keys <- teal.data::join_keys(data())[[dataname]] |
469 | ! |
if (parent_dataname %in% names(keys)) { |
470 | ! |
keys[[parent_dataname]] |
471 |
} else { |
|
472 | ! |
keys[[dataname]] |
473 |
} |
|
474 |
} else { |
|
475 | ! |
NULL |
476 |
} |
|
477 |
}) |
|
478 | ||
479 | ! |
common_code_q <- reactive({ |
480 | ! |
teal::validate_inputs(iv_r()) |
481 | ||
482 | ! |
group_var <- input$group_by_var |
483 | ! |
anl <- data_r() |
484 | ||
485 | ! |
qenv <- if (!is.null(selected_vars()) && length(selected_vars()) != ncol(anl)) { |
486 | ! |
teal.code::eval_code( |
487 | ! |
data(), |
488 | ! |
substitute( |
489 | ! |
expr = ANL <- anl_name[, selected_vars, drop = FALSE], |
490 | ! |
env = list(anl_name = as.name(dataname), selected_vars = selected_vars()) |
491 |
) |
|
492 |
) |
|
493 |
} else { |
|
494 | ! |
teal.code::eval_code( |
495 | ! |
data(), |
496 | ! |
substitute(expr = ANL <- anl_name, env = list(anl_name = as.name(dataname))) |
497 |
) |
|
498 |
} |
|
499 | ||
500 | ! |
if (input$summary_type == "By Variable Levels" && !is.null(group_var) && !(group_var %in% selected_vars())) { |
501 | ! |
qenv <- teal.code::eval_code( |
502 | ! |
qenv, |
503 | ! |
substitute( |
504 | ! |
expr = ANL[[group_var]] <- anl_name[[group_var]], |
505 | ! |
env = list(group_var = group_var, anl_name = as.name(dataname)) |
506 |
) |
|
507 |
) |
|
508 |
} |
|
509 | ||
510 | ! |
new_col_name <- "**anyna**" |
511 | ||
512 | ! |
qenv <- teal.code::eval_code( |
513 | ! |
qenv, |
514 | ! |
substitute( |
515 | ! |
expr = |
516 | ! |
create_cols_labels <- function(cols, just_label = FALSE) { |
517 | ! |
column_labels <- column_labels_value |
518 | ! |
column_labels[is.na(column_labels) | length(column_labels) == 0] <- "" |
519 | ! |
if (just_label) { |
520 | ! |
labels <- column_labels[cols] |
521 |
} else { |
|
522 | ! |
labels <- ifelse(cols == new_col_name | cols == "", cols, paste0(column_labels[cols], " [", cols, "]")) |
523 |
} |
|
524 | ! |
labels |
525 |
}, |
|
526 | ! |
env = list( |
527 | ! |
new_col_name = new_col_name, |
528 | ! |
column_labels_value = c(teal.data::col_labels(data_r())[selected_vars()], |
529 | ! |
new_col_name = new_col_name |
530 |
) |
|
531 |
) |
|
532 |
) |
|
533 |
) |
|
534 | ! |
qenv |
535 |
}) |
|
536 | ||
537 | ! |
selected_vars <- reactive({ |
538 | ! |
req(input$variables_select) |
539 | ! |
keys <- data_keys() |
540 | ! |
vars <- unique(c(keys, input$variables_select)) |
541 | ! |
vars |
542 |
}) |
|
543 | ||
544 | ! |
vars_summary <- reactive({ |
545 | ! |
na_count <- data_r() %>% |
546 | ! |
sapply(function(x) mean(is.na(x)), USE.NAMES = TRUE) %>% |
547 | ! |
sort(decreasing = TRUE) |
548 | ||
549 | ! |
tibble::tibble( |
550 | ! |
key = names(na_count), |
551 | ! |
value = unname(na_count), |
552 | ! |
label = cut(na_count, breaks = seq(from = 0, to = 1, by = 0.1), include.lowest = TRUE) |
553 |
) |
|
554 |
}) |
|
555 | ||
556 | ! |
output$variables <- renderUI({ |
557 | ! |
choices <- split(x = vars_summary()$key, f = vars_summary()$label, drop = TRUE) %>% rev() |
558 | ! |
selected <- choices <- unname(unlist(choices)) |
559 | ||
560 | ! |
teal.widgets::optionalSelectInput( |
561 | ! |
ns("variables_select"), |
562 | ! |
label = "Select variables", |
563 | ! |
label_help = HTML(paste0("Dataset: ", tags$code(dataname))), |
564 | ! |
choices = teal.transform::variable_choices(data_r(), choices), |
565 | ! |
selected = selected, |
566 | ! |
multiple = TRUE |
567 |
) |
|
568 |
}) |
|
569 | ||
570 | ! |
observeEvent(input$filter_na, { |
571 | ! |
choices <- vars_summary() %>% |
572 | ! |
dplyr::select(!!as.name("key")) %>% |
573 | ! |
getElement(name = 1) |
574 | ||
575 | ! |
selected <- vars_summary() %>% |
576 | ! |
dplyr::filter(!!as.name("value") > 0) %>% |
577 | ! |
dplyr::select(!!as.name("key")) %>% |
578 | ! |
getElement(name = 1) |
579 | ||
580 | ! |
teal.widgets::updateOptionalSelectInput( |
581 | ! |
session = session, |
582 | ! |
inputId = "variables_select", |
583 | ! |
choices = teal.transform::variable_choices(data_r()), |
584 | ! |
selected = restoreInput(ns("variables_select"), selected) |
585 |
) |
|
586 |
}) |
|
587 | ||
588 | ! |
output$group_by_var_ui <- renderUI({ |
589 | ! |
all_choices <- teal.transform::variable_choices(data_r()) |
590 | ! |
cat_choices <- all_choices[!sapply(data_r(), function(x) is.numeric(x) || inherits(x, "POSIXct"))] |
591 | ! |
validate( |
592 | ! |
need(cat_choices, "Dataset does not have any non-numeric or non-datetime variables to use to group data with") |
593 |
) |
|
594 | ! |
teal.widgets::optionalSelectInput( |
595 | ! |
ns("group_by_var"), |
596 | ! |
label = "Group by variable", |
597 | ! |
choices = cat_choices, |
598 | ! |
selected = `if`( |
599 | ! |
is.null(isolate(input$group_by_var)), |
600 | ! |
cat_choices[1], |
601 | ! |
isolate(input$group_by_var) |
602 |
), |
|
603 | ! |
multiple = FALSE, |
604 | ! |
label_help = paste0("Dataset: ", dataname) |
605 |
) |
|
606 |
}) |
|
607 | ||
608 | ! |
output$group_by_vals_ui <- renderUI({ |
609 | ! |
req(input$group_by_var) |
610 | ||
611 | ! |
choices <- teal.transform::value_choices(data_r(), input$group_by_var, input$group_by_var) |
612 | ! |
prev_choices <- isolate(input$group_by_vals) |
613 | ||
614 |
# determine selected value based on filtered data |
|
615 |
# display those previously selected values that are still available |
|
616 | ! |
selected <- if (!is.null(prev_choices) && any(prev_choices %in% choices)) { |
617 | ! |
prev_choices[match(choices[choices %in% prev_choices], prev_choices)] |
618 | ! |
} else if ( |
619 | ! |
!is.null(prev_choices) && |
620 | ! |
!any(prev_choices %in% choices) && |
621 | ! |
isolate(prev_group_by_var()) == input$group_by_var |
622 |
) { |
|
623 |
# if not any previously selected value is available and the grouping variable is the same, |
|
624 |
# then display NULL |
|
625 | ! |
NULL |
626 |
} else { |
|
627 |
# if new grouping variable (i.e. not any previously selected value is available), |
|
628 |
# then display all choices |
|
629 | ! |
choices |
630 |
} |
|
631 | ||
632 | ! |
prev_group_by_var(input$group_by_var) # set current group_by_var |
633 | ! |
validate(need(length(choices) < 100, "Please select group-by variable with fewer than 100 unique values")) |
634 | ||
635 | ! |
teal.widgets::optionalSelectInput( |
636 | ! |
ns("group_by_vals"), |
637 | ! |
label = "Filter levels", |
638 | ! |
choices = choices, |
639 | ! |
selected = selected, |
640 | ! |
multiple = TRUE, |
641 | ! |
label_help = paste0("Dataset: ", dataname) |
642 |
) |
|
643 |
}) |
|
644 | ||
645 | ! |
summary_plot_q <- reactive({ |
646 | ! |
req(input$summary_type == "Summary") # needed to trigger show r code update on tab change |
647 | ! |
teal::validate_has_data(data_r(), 1) |
648 | ||
649 | ! |
qenv <- common_code_q() |
650 | ||
651 | ! |
if (input$any_na) { |
652 | ! |
new_col_name <- "**anyna**" |
653 | ! |
qenv <- teal.code::eval_code( |
654 | ! |
qenv, |
655 | ! |
substitute( |
656 | ! |
expr = ANL[[new_col_name]] <- ifelse(rowSums(is.na(ANL)) > 0, NA, FALSE), |
657 | ! |
env = list(new_col_name = new_col_name) |
658 |
) |
|
659 |
) |
|
660 |
} |
|
661 | ||
662 | ! |
qenv <- teal.code::eval_code( |
663 | ! |
qenv, |
664 | ! |
substitute( |
665 | ! |
expr = analysis_vars <- setdiff(colnames(ANL), data_keys), |
666 | ! |
env = list(data_keys = data_keys()) |
667 |
) |
|
668 |
) %>% |
|
669 | ! |
teal.code::eval_code( |
670 | ! |
substitute( |
671 | ! |
expr = summary_plot_obs <- data_frame_call[, analysis_vars] %>% |
672 | ! |
dplyr::summarise_all(list(function(x) sum(is.na(x)))) %>% |
673 | ! |
tidyr::pivot_longer(dplyr::everything(), names_to = "col", values_to = "n_na") %>% |
674 | ! |
dplyr::mutate(n_not_na = nrow(ANL) - n_na) %>% |
675 | ! |
tidyr::pivot_longer(-col, names_to = "isna", values_to = "n") %>% |
676 | ! |
dplyr::mutate(isna = isna == "n_na", n_pct = n / nrow(ANL) * 100), |
677 | ! |
env = list(data_frame_call = if (!inherits(data_r(), "tbl_df")) { |
678 | ! |
quote(tibble::as_tibble(ANL)) |
679 |
} else { |
|
680 | ! |
quote(ANL) |
681 |
}) |
|
682 |
) |
|
683 |
) %>% |
|
684 |
# x axis ordering according to number of missing values and alphabet |
|
685 | ! |
teal.code::eval_code( |
686 | ! |
quote( |
687 | ! |
expr = x_levels <- dplyr::filter(summary_plot_obs, isna) %>% |
688 | ! |
dplyr::arrange(n_pct, dplyr::desc(col)) %>% |
689 | ! |
dplyr::pull(col) %>% |
690 | ! |
create_cols_labels() |
691 |
) |
|
692 |
) |
|
693 | ||
694 |
# always set "**anyna**" level as the last one |
|
695 | ! |
if (isolate(input$any_na)) { |
696 | ! |
qenv <- teal.code::eval_code( |
697 | ! |
qenv, |
698 | ! |
quote(x_levels <- c(setdiff(x_levels, "**anyna**"), "**anyna**")) |
699 |
) |
|
700 |
} |
|
701 | ||
702 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
703 | ! |
labs = list(x = "Variable", y = "Missing observations"), |
704 | ! |
theme = list(legend.position = "bottom", axis.text.x = quote(element_text(angle = 45, hjust = 1))) |
705 |
) |
|
706 | ||
707 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
708 | ! |
user_plot = ggplot2_args[["Summary Obs"]], |
709 | ! |
user_default = ggplot2_args$default, |
710 | ! |
module_plot = dev_ggplot2_args |
711 |
) |
|
712 | ||
713 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
714 | ! |
all_ggplot2_args, |
715 | ! |
ggtheme = input$ggtheme |
716 |
) |
|
717 | ||
718 | ! |
qenv <- teal.code::eval_code( |
719 | ! |
qenv, |
720 | ! |
substitute( |
721 | ! |
p1 <- summary_plot_obs %>% |
722 | ! |
ggplot() + |
723 | ! |
aes( |
724 | ! |
x = factor(create_cols_labels(col), levels = x_levels), |
725 | ! |
y = n_pct, |
726 | ! |
fill = isna |
727 |
) + |
|
728 | ! |
geom_bar(position = "fill", stat = "identity") + |
729 | ! |
scale_fill_manual( |
730 | ! |
name = "", |
731 | ! |
values = c("grey90", c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]), |
732 | ! |
labels = c("Present", "Missing") |
733 |
) + |
|
734 | ! |
scale_y_continuous( |
735 | ! |
labels = scales::percent_format(), |
736 | ! |
breaks = seq(0, 1, by = 0.1), |
737 | ! |
expand = c(0, 0) |
738 |
) + |
|
739 | ! |
geom_text( |
740 | ! |
aes(label = ifelse(isna == TRUE, sprintf("%d [%.02f%%]", n, n_pct), ""), y = 1), |
741 | ! |
hjust = 1, |
742 | ! |
color = "black" |
743 |
) + |
|
744 | ! |
labs + |
745 | ! |
ggthemes + |
746 | ! |
themes + |
747 | ! |
coord_flip(), |
748 | ! |
env = list( |
749 | ! |
labs = parsed_ggplot2_args$labs, |
750 | ! |
themes = parsed_ggplot2_args$theme, |
751 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
752 |
) |
|
753 |
) |
|
754 |
) |
|
755 | ||
756 | ! |
if (isTRUE(input$if_patients_plot)) { |
757 | ! |
qenv <- teal.code::eval_code( |
758 | ! |
qenv, |
759 | ! |
substitute( |
760 | ! |
expr = parent_keys <- keys, |
761 | ! |
env = list(keys = data_parent_keys()) |
762 |
) |
|
763 |
) %>% |
|
764 | ! |
teal.code::eval_code(quote(ndistinct_subjects <- dplyr::n_distinct(ANL[, parent_keys]))) %>% |
765 | ! |
teal.code::eval_code( |
766 | ! |
quote( |
767 | ! |
summary_plot_patients <- ANL[, c(parent_keys, analysis_vars)] %>% |
768 | ! |
dplyr::group_by_at(parent_keys) %>% |
769 | ! |
dplyr::summarise_all(anyNA) %>% |
770 | ! |
tidyr::pivot_longer(cols = !dplyr::all_of(parent_keys), names_to = "col", values_to = "anyna") %>% |
771 | ! |
dplyr::group_by_at(c("col")) %>% |
772 | ! |
dplyr::summarise(count_na = sum(anyna)) %>% |
773 | ! |
dplyr::mutate(count_not_na = ndistinct_subjects - count_na) %>% |
774 | ! |
tidyr::pivot_longer(-c(col), names_to = "isna", values_to = "n") %>% |
775 | ! |
dplyr::mutate(isna = isna == "count_na", n_pct = n / ndistinct_subjects * 100) %>% |
776 | ! |
dplyr::arrange_at(c("isna", "n"), .funs = dplyr::desc) |
777 |
) |
|
778 |
) |
|
779 | ||
780 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
781 | ! |
labs = list(x = "", y = "Missing patients"), |
782 | ! |
theme = list( |
783 | ! |
legend.position = "bottom", |
784 | ! |
axis.text.x = quote(element_text(angle = 45, hjust = 1)), |
785 | ! |
axis.text.y = quote(element_blank()) |
786 |
) |
|
787 |
) |
|
788 | ||
789 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
790 | ! |
user_plot = ggplot2_args[["Summary Patients"]], |
791 | ! |
user_default = ggplot2_args$default, |
792 | ! |
module_plot = dev_ggplot2_args |
793 |
) |
|
794 | ||
795 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
796 | ! |
all_ggplot2_args, |
797 | ! |
ggtheme = input$ggtheme |
798 |
) |
|
799 | ||
800 | ! |
qenv <- teal.code::eval_code( |
801 | ! |
qenv, |
802 | ! |
substitute( |
803 | ! |
p2 <- summary_plot_patients %>% |
804 | ! |
ggplot() + |
805 | ! |
aes_( |
806 | ! |
x = ~ factor(create_cols_labels(col), levels = x_levels), |
807 | ! |
y = ~n_pct, |
808 | ! |
fill = ~isna |
809 |
) + |
|
810 | ! |
geom_bar(alpha = 1, stat = "identity", position = "fill") + |
811 | ! |
scale_y_continuous( |
812 | ! |
labels = scales::percent_format(), |
813 | ! |
breaks = seq(0, 1, by = 0.1), |
814 | ! |
expand = c(0, 0) |
815 |
) + |
|
816 | ! |
scale_fill_manual( |
817 | ! |
name = "", |
818 | ! |
values = c("grey90", c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]), |
819 | ! |
labels = c("Present", "Missing") |
820 |
) + |
|
821 | ! |
geom_text( |
822 | ! |
aes(label = ifelse(isna == TRUE, sprintf("%d [%.02f%%]", n, n_pct), ""), y = 1), |
823 | ! |
hjust = 1, |
824 | ! |
color = "black" |
825 |
) + |
|
826 | ! |
labs + |
827 | ! |
ggthemes + |
828 | ! |
themes + |
829 | ! |
coord_flip(), |
830 | ! |
env = list( |
831 | ! |
labs = parsed_ggplot2_args$labs, |
832 | ! |
themes = parsed_ggplot2_args$theme, |
833 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
834 |
) |
|
835 |
) |
|
836 |
) %>% |
|
837 | ! |
teal.code::eval_code( |
838 | ! |
quote({ |
839 | ! |
g1 <- ggplotGrob(p1) |
840 | ! |
g2 <- ggplotGrob(p2) |
841 | ! |
g <- gridExtra::gtable_cbind(g1, g2, size = "first") |
842 | ! |
g$heights <- grid::unit.pmax(g1$heights, g2$heights) |
843 | ! |
grid::grid.newpage() |
844 |
}) |
|
845 |
) |
|
846 |
} else { |
|
847 | ! |
qenv <- teal.code::eval_code( |
848 | ! |
qenv, |
849 | ! |
quote({ |
850 | ! |
g <- ggplotGrob(p1) |
851 | ! |
grid::grid.newpage() |
852 |
}) |
|
853 |
) |
|
854 |
} |
|
855 | ||
856 | ! |
teal.code::eval_code( |
857 | ! |
qenv, |
858 | ! |
quote(grid::grid.draw(g)) |
859 |
) |
|
860 |
}) |
|
861 | ||
862 | ! |
summary_plot_r <- reactive(summary_plot_q()[["g"]]) |
863 | ||
864 | ! |
combination_cutoff_q <- reactive({ |
865 | ! |
req(common_code_q()) |
866 | ! |
teal.code::eval_code( |
867 | ! |
common_code_q(), |
868 | ! |
quote( |
869 | ! |
combination_cutoff <- ANL %>% |
870 | ! |
dplyr::mutate_all(is.na) %>% |
871 | ! |
dplyr::group_by_all() %>% |
872 | ! |
dplyr::tally() %>% |
873 | ! |
dplyr::ungroup() |
874 |
) |
|
875 |
) |
|
876 |
}) |
|
877 | ||
878 | ! |
output$cutoff <- renderUI({ |
879 | ! |
x <- combination_cutoff_q()[["combination_cutoff"]]$n |
880 | ||
881 |
# select 10-th from the top |
|
882 | ! |
n <- length(x) |
883 | ! |
idx <- max(1, n - 10) |
884 | ! |
prev_value <- isolate(input$combination_cutoff) |
885 | ! |
value <- `if`( |
886 | ! |
is.null(prev_value) || prev_value > max(x) || prev_value < min(x), |
887 | ! |
sort(x, partial = idx)[idx], prev_value |
888 |
) |
|
889 | ||
890 | ! |
teal.widgets::optionalSliderInputValMinMax( |
891 | ! |
ns("combination_cutoff"), |
892 | ! |
"Combination cut-off", |
893 | ! |
c(value, range(x)) |
894 |
) |
|
895 |
}) |
|
896 | ||
897 | ! |
combination_plot_q <- reactive({ |
898 | ! |
req(input$summary_type == "Combinations", input$combination_cutoff, combination_cutoff_q()) |
899 | ! |
teal::validate_has_data(data_r(), 1) |
900 | ||
901 | ! |
qenv <- teal.code::eval_code( |
902 | ! |
combination_cutoff_q(), |
903 | ! |
substitute( |
904 | ! |
expr = data_combination_plot_cutoff <- combination_cutoff %>% |
905 | ! |
dplyr::filter(n >= combination_cutoff_value) %>% |
906 | ! |
dplyr::mutate(id = rank(-n, ties.method = "first")) %>% |
907 | ! |
tidyr::pivot_longer(-c(n, id), names_to = "key", values_to = "value") %>% |
908 | ! |
dplyr::arrange(n), |
909 | ! |
env = list(combination_cutoff_value = input$combination_cutoff) |
910 |
) |
|
911 |
) |
|
912 | ||
913 |
# find keys in dataset not selected in the UI and remove them from dataset |
|
914 | ! |
keys_not_selected <- setdiff(data_keys(), input$variables_select) |
915 | ! |
if (length(keys_not_selected) > 0) { |
916 | ! |
qenv <- teal.code::eval_code( |
917 | ! |
qenv, |
918 | ! |
substitute( |
919 | ! |
expr = data_combination_plot_cutoff <- data_combination_plot_cutoff %>% |
920 | ! |
dplyr::filter(!key %in% keys_not_selected), |
921 | ! |
env = list(keys_not_selected = keys_not_selected) |
922 |
) |
|
923 |
) |
|
924 |
} |
|
925 | ||
926 | ! |
qenv <- teal.code::eval_code( |
927 | ! |
qenv, |
928 | ! |
quote( |
929 | ! |
labels <- data_combination_plot_cutoff %>% |
930 | ! |
dplyr::filter(key == key[[1]]) %>% |
931 | ! |
getElement(name = 1) |
932 |
) |
|
933 |
) |
|
934 | ||
935 | ! |
dev_ggplot2_args1 <- teal.widgets::ggplot2_args( |
936 | ! |
labs = list(x = "", y = ""), |
937 | ! |
theme = list( |
938 | ! |
legend.position = "bottom", |
939 | ! |
axis.text.x = quote(element_blank()) |
940 |
) |
|
941 |
) |
|
942 | ||
943 | ! |
all_ggplot2_args1 <- teal.widgets::resolve_ggplot2_args( |
944 | ! |
user_plot = ggplot2_args[["Combinations Hist"]], |
945 | ! |
user_default = ggplot2_args$default, |
946 | ! |
module_plot = dev_ggplot2_args1 |
947 |
) |
|
948 | ||
949 | ! |
parsed_ggplot2_args1 <- teal.widgets::parse_ggplot2_args( |
950 | ! |
all_ggplot2_args1, |
951 | ! |
ggtheme = "void" |
952 |
) |
|
953 | ||
954 | ! |
dev_ggplot2_args2 <- teal.widgets::ggplot2_args( |
955 | ! |
labs = list(x = "", y = ""), |
956 | ! |
theme = list( |
957 | ! |
legend.position = "bottom", |
958 | ! |
axis.text.x = quote(element_blank()), |
959 | ! |
axis.ticks = quote(element_blank()), |
960 | ! |
panel.grid.major = quote(element_blank()) |
961 |
) |
|
962 |
) |
|
963 | ||
964 | ! |
all_ggplot2_args2 <- teal.widgets::resolve_ggplot2_args( |
965 | ! |
user_plot = ggplot2_args[["Combinations Main"]], |
966 | ! |
user_default = ggplot2_args$default, |
967 | ! |
module_plot = dev_ggplot2_args2 |
968 |
) |
|
969 | ||
970 | ! |
parsed_ggplot2_args2 <- teal.widgets::parse_ggplot2_args( |
971 | ! |
all_ggplot2_args2, |
972 | ! |
ggtheme = input$ggtheme |
973 |
) |
|
974 | ||
975 | ! |
teal.code::eval_code( |
976 | ! |
qenv, |
977 | ! |
substitute( |
978 | ! |
expr = { |
979 | ! |
p1 <- data_combination_plot_cutoff %>% |
980 | ! |
dplyr::select(id, n) %>% |
981 | ! |
dplyr::distinct() %>% |
982 | ! |
ggplot(aes(x = id, y = n)) + |
983 | ! |
geom_bar(stat = "identity", fill = c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]) + |
984 | ! |
geom_text( |
985 | ! |
aes(label = n), |
986 | ! |
position = position_dodge(width = 0.9), |
987 | ! |
vjust = -0.25 |
988 |
) + |
|
989 | ! |
ylim(c(0, max(data_combination_plot_cutoff$n) * 1.5)) + |
990 | ! |
labs1 + |
991 | ! |
ggthemes1 + |
992 | ! |
themes1 |
993 | ||
994 | ! |
graph_number_rows <- length(unique(data_combination_plot_cutoff$id)) |
995 | ! |
graph_number_cols <- nrow(data_combination_plot_cutoff) / graph_number_rows |
996 | ||
997 | ! |
p2 <- data_combination_plot_cutoff %>% ggplot() + |
998 | ! |
aes(x = create_cols_labels(key), y = id - 0.5, fill = value) + |
999 | ! |
geom_tile(alpha = 0.85, height = 0.95) + |
1000 | ! |
scale_fill_manual( |
1001 | ! |
name = "", |
1002 | ! |
values = c("grey90", c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]), |
1003 | ! |
labels = c("Present", "Missing") |
1004 |
) + |
|
1005 | ! |
geom_hline(yintercept = seq_len(1 + graph_number_rows) - 1) + |
1006 | ! |
geom_vline(xintercept = seq_len(1 + graph_number_cols) - 0.5, linetype = "dotted") + |
1007 | ! |
coord_flip() + |
1008 | ! |
labs2 + |
1009 | ! |
ggthemes2 + |
1010 | ! |
themes2 |
1011 | ||
1012 | ! |
g1 <- ggplotGrob(p1) |
1013 | ! |
g2 <- ggplotGrob(p2) |
1014 | ||
1015 | ! |
g <- gridExtra::gtable_rbind(g1, g2, size = "last") |
1016 | ! |
g$heights[7] <- grid::unit(0.2, "null") # rescale to get the bar chart smaller |
1017 | ! |
grid::grid.newpage() |
1018 | ! |
grid::grid.draw(g) |
1019 |
}, |
|
1020 | ! |
env = list( |
1021 | ! |
labs1 = parsed_ggplot2_args1$labs, |
1022 | ! |
themes1 = parsed_ggplot2_args1$theme, |
1023 | ! |
ggthemes1 = parsed_ggplot2_args1$ggtheme, |
1024 | ! |
labs2 = parsed_ggplot2_args2$labs, |
1025 | ! |
themes2 = parsed_ggplot2_args2$theme, |
1026 | ! |
ggthemes2 = parsed_ggplot2_args2$ggtheme |
1027 |
) |
|
1028 |
) |
|
1029 |
) |
|
1030 |
}) |
|
1031 | ||
1032 | ! |
combination_plot_r <- reactive(combination_plot_q()[["g"]]) |
1033 | ||
1034 | ! |
summary_table_q <- reactive({ |
1035 | ! |
req( |
1036 | ! |
input$summary_type == "By Variable Levels", # needed to trigger show r code update on tab change |
1037 | ! |
common_code_q() |
1038 |
) |
|
1039 | ! |
teal::validate_has_data(data_r(), 1) |
1040 | ||
1041 |
# extract the ANL dataset for use in further validation |
|
1042 | ! |
anl <- common_code_q()[["ANL"]] |
1043 | ||
1044 | ! |
group_var <- input$group_by_var |
1045 | ! |
validate( |
1046 | ! |
need( |
1047 | ! |
is.null(group_var) || |
1048 | ! |
length(unique(anl[[group_var]])) < 100, |
1049 | ! |
"Please select group-by variable with fewer than 100 unique values" |
1050 |
) |
|
1051 |
) |
|
1052 | ||
1053 | ! |
group_vals <- input$group_by_vals |
1054 | ! |
variables_select <- input$variables_select |
1055 | ! |
vars <- unique(variables_select, group_var) |
1056 | ! |
count_type <- input$count_type |
1057 | ||
1058 | ! |
if (!is.null(selected_vars()) && length(selected_vars()) != ncol(anl)) { |
1059 | ! |
variables <- selected_vars() |
1060 |
} else { |
|
1061 | ! |
variables <- colnames(anl) |
1062 |
} |
|
1063 | ||
1064 | ! |
summ_fn <- if (input$count_type == "counts") { |
1065 | ! |
function(x) sum(is.na(x)) |
1066 |
} else { |
|
1067 | ! |
function(x) round(sum(is.na(x)) / length(x), 4) |
1068 |
} |
|
1069 | ||
1070 | ! |
qenv <- common_code_q() |
1071 | ||
1072 | ! |
if (!is.null(group_var)) { |
1073 | ! |
qenv <- teal.code::eval_code( |
1074 | ! |
qenv, |
1075 | ! |
substitute( |
1076 | ! |
expr = { |
1077 | ! |
summary_data <- ANL %>% |
1078 | ! |
dplyr::mutate(group_var_name := forcats::fct_na_value_to_level(as.factor(group_var_name), "NA")) %>% |
1079 | ! |
dplyr::group_by_at(group_var) %>% |
1080 | ! |
dplyr::filter(group_var_name %in% group_vals) |
1081 | ||
1082 | ! |
count_data <- dplyr::summarise(summary_data, n = dplyr::n()) |
1083 | ||
1084 | ! |
summary_data <- dplyr::summarise_all(summary_data, summ_fn) %>% |
1085 | ! |
dplyr::mutate(group_var_name := paste0(group_var, ":", group_var_name, "(N=", count_data$n, ")")) %>% |
1086 | ! |
tidyr::pivot_longer(!dplyr::all_of(group_var), names_to = "Variable", values_to = "out") %>% |
1087 | ! |
tidyr::pivot_wider(names_from = group_var, values_from = "out") %>% |
1088 | ! |
dplyr::mutate(`Variable label` = create_cols_labels(Variable, just_label = TRUE), .after = Variable) |
1089 |
}, |
|
1090 | ! |
env = list( |
1091 | ! |
group_var = group_var, group_var_name = as.name(group_var), group_vals = group_vals, summ_fn = summ_fn |
1092 |
) |
|
1093 |
) |
|
1094 |
) |
|
1095 |
} else { |
|
1096 | ! |
qenv <- teal.code::eval_code( |
1097 | ! |
qenv, |
1098 | ! |
substitute( |
1099 | ! |
expr = summary_data <- ANL %>% |
1100 | ! |
dplyr::summarise_all(summ_fn) %>% |
1101 | ! |
tidyr::pivot_longer(dplyr::everything(), |
1102 | ! |
names_to = "Variable", |
1103 | ! |
values_to = paste0("Missing (N=", nrow(ANL), ")") |
1104 |
) %>% |
|
1105 | ! |
dplyr::mutate(`Variable label` = create_cols_labels(Variable), .after = Variable), |
1106 | ! |
env = list(summ_fn = summ_fn) |
1107 |
) |
|
1108 |
) |
|
1109 |
} |
|
1110 | ||
1111 | ! |
teal.code::eval_code(qenv, quote(summary_data)) |
1112 |
}) |
|
1113 | ||
1114 | ! |
summary_table_r <- reactive(summary_table_q()[["summary_data"]]) |
1115 | ||
1116 | ! |
by_subject_plot_q <- reactive({ |
1117 |
# needed to trigger show r code update on tab change |
|
1118 | ! |
req(input$summary_type == "Grouped by Subject", common_code_q()) |
1119 | ||
1120 | ! |
teal::validate_has_data(data_r(), 1) |
1121 | ||
1122 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
1123 | ! |
labs = list(x = "", y = ""), |
1124 | ! |
theme = list(legend.position = "bottom", axis.text.x = quote(element_blank())) |
1125 |
) |
|
1126 | ||
1127 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
1128 | ! |
user_plot = ggplot2_args[["By Subject"]], |
1129 | ! |
user_default = ggplot2_args$default, |
1130 | ! |
module_plot = dev_ggplot2_args |
1131 |
) |
|
1132 | ||
1133 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
1134 | ! |
all_ggplot2_args, |
1135 | ! |
ggtheme = input$ggtheme |
1136 |
) |
|
1137 | ||
1138 | ! |
teal.code::eval_code( |
1139 | ! |
common_code_q(), |
1140 | ! |
substitute( |
1141 | ! |
expr = parent_keys <- keys, |
1142 | ! |
env = list(keys = data_parent_keys()) |
1143 |
) |
|
1144 |
) %>% |
|
1145 | ! |
teal.code::eval_code( |
1146 | ! |
substitute( |
1147 | ! |
expr = analysis_vars <- setdiff(colnames(ANL), data_keys), |
1148 | ! |
env = list(data_keys = data_keys()) |
1149 |
) |
|
1150 |
) %>% |
|
1151 | ! |
teal.code::eval_code( |
1152 | ! |
quote({ |
1153 | ! |
summary_plot_patients <- ANL[, c(parent_keys, analysis_vars)] %>% |
1154 | ! |
dplyr::group_by_at(parent_keys) %>% |
1155 | ! |
dplyr::mutate(id = dplyr::cur_group_id()) %>% |
1156 | ! |
dplyr::ungroup() %>% |
1157 | ! |
dplyr::group_by_at(c(parent_keys, "id")) %>% |
1158 | ! |
dplyr::summarise_all(anyNA) %>% |
1159 | ! |
dplyr::ungroup() |
1160 | ||
1161 |
# order subjects by decreasing number of missing and then by |
|
1162 |
# missingness pattern (defined using sha1) |
|
1163 | ! |
order_subjects <- summary_plot_patients %>% |
1164 | ! |
dplyr::select(-"id", -dplyr::all_of(parent_keys)) %>% |
1165 | ! |
dplyr::transmute( |
1166 | ! |
id = dplyr::row_number(), |
1167 | ! |
number_NA = apply(., 1, sum), |
1168 | ! |
sha = apply(., 1, rlang::hash) |
1169 |
) %>% |
|
1170 | ! |
dplyr::arrange(dplyr::desc(number_NA), sha) %>% |
1171 | ! |
getElement(name = "id") |
1172 | ||
1173 |
# order columns by decreasing percent of missing values |
|
1174 | ! |
ordered_columns <- summary_plot_patients %>% |
1175 | ! |
dplyr::select(-"id", -dplyr::all_of(parent_keys)) %>% |
1176 | ! |
dplyr::summarise( |
1177 | ! |
column = create_cols_labels(colnames(.)), |
1178 | ! |
na_count = apply(., MARGIN = 2, FUN = sum), |
1179 | ! |
na_percent = na_count / nrow(.) * 100 |
1180 |
) %>% |
|
1181 | ! |
dplyr::arrange(na_percent, dplyr::desc(column)) |
1182 | ||
1183 | ! |
summary_plot_patients <- summary_plot_patients %>% |
1184 | ! |
tidyr::gather("col", "isna", -"id", -dplyr::all_of(parent_keys)) %>% |
1185 | ! |
dplyr::mutate(col = create_cols_labels(col)) |
1186 |
}) |
|
1187 |
) %>% |
|
1188 | ! |
teal.code::eval_code( |
1189 | ! |
substitute( |
1190 | ! |
expr = { |
1191 | ! |
g <- ggplot(summary_plot_patients, aes( |
1192 | ! |
x = factor(id, levels = order_subjects), |
1193 | ! |
y = factor(col, levels = ordered_columns[["column"]]), |
1194 | ! |
fill = isna |
1195 |
)) + |
|
1196 | ! |
geom_raster() + |
1197 | ! |
annotate( |
1198 | ! |
"text", |
1199 | ! |
x = length(order_subjects), |
1200 | ! |
y = seq_len(nrow(ordered_columns)), |
1201 | ! |
hjust = 1, |
1202 | ! |
label = sprintf("%d [%.02f%%]", ordered_columns[["na_count"]], ordered_columns[["na_percent"]]) |
1203 |
) + |
|
1204 | ! |
scale_fill_manual( |
1205 | ! |
name = "", |
1206 | ! |
values = c("grey90", c(getOption("ggplot2.discrete.colour")[2], "#ff2951ff")[1]), |
1207 | ! |
labels = c("Present", "Missing (at least one)") |
1208 |
) + |
|
1209 | ! |
labs + |
1210 | ! |
ggthemes + |
1211 | ! |
themes |
1212 | ! |
print(g) |
1213 |
}, |
|
1214 | ! |
env = list( |
1215 | ! |
labs = parsed_ggplot2_args$labs, |
1216 | ! |
themes = parsed_ggplot2_args$theme, |
1217 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
1218 |
) |
|
1219 |
) |
|
1220 |
) |
|
1221 |
}) |
|
1222 | ||
1223 | ! |
by_subject_plot_r <- reactive(by_subject_plot_q()[["g"]]) |
1224 | ||
1225 | ! |
output$levels_table <- DT::renderDataTable( |
1226 | ! |
expr = { |
1227 | ! |
if (length(input$variables_select) == 0) { |
1228 |
# so that zeroRecords message gets printed |
|
1229 |
# using tibble as it supports weird column names, such as " " |
|
1230 | ! |
tibble::tibble(` ` = logical(0)) |
1231 |
} else { |
|
1232 | ! |
summary_table_r() |
1233 |
} |
|
1234 |
}, |
|
1235 | ! |
options = list(language = list(zeroRecords = "No variable selected"), pageLength = input$levels_table_rows) |
1236 |
) |
|
1237 | ||
1238 | ! |
pws1 <- teal.widgets::plot_with_settings_srv( |
1239 | ! |
id = "summary_plot", |
1240 | ! |
plot_r = summary_plot_r, |
1241 | ! |
height = plot_height, |
1242 | ! |
width = plot_width |
1243 |
) |
|
1244 | ||
1245 | ! |
pws2 <- teal.widgets::plot_with_settings_srv( |
1246 | ! |
id = "combination_plot", |
1247 | ! |
plot_r = combination_plot_r, |
1248 | ! |
height = plot_height, |
1249 | ! |
width = plot_width |
1250 |
) |
|
1251 | ||
1252 | ! |
pws3 <- teal.widgets::plot_with_settings_srv( |
1253 | ! |
id = "by_subject_plot", |
1254 | ! |
plot_r = by_subject_plot_r, |
1255 | ! |
height = plot_height, |
1256 | ! |
width = plot_width |
1257 |
) |
|
1258 | ||
1259 | ! |
final_q <- reactive({ |
1260 | ! |
req(input$summary_type) |
1261 | ! |
sum_type <- input$summary_type |
1262 | ! |
if (sum_type == "Summary") { |
1263 | ! |
summary_plot_q() |
1264 | ! |
} else if (sum_type == "Combinations") { |
1265 | ! |
combination_plot_q() |
1266 | ! |
} else if (sum_type == "By Variable Levels") { |
1267 | ! |
summary_table_q() |
1268 | ! |
} else if (sum_type == "Grouped by Subject") { |
1269 | ! |
by_subject_plot_q() |
1270 |
} |
|
1271 |
}) |
|
1272 | ||
1273 | ! |
teal.widgets::verbatim_popup_srv( |
1274 | ! |
id = "rcode", |
1275 | ! |
verbatim_content = reactive(teal.code::get_code(final_q())), |
1276 | ! |
title = "Show R Code for Missing Data" |
1277 |
) |
|
1278 | ||
1279 |
### REPORTER |
|
1280 | ! |
if (with_reporter) { |
1281 | ! |
card_fun <- function(comment, label) { |
1282 | ! |
card <- teal::TealReportCard$new() |
1283 | ! |
sum_type <- input$summary_type |
1284 | ! |
title <- if (sum_type == "By Variable Levels") paste0(sum_type, " Table") else paste0(sum_type, " Plot") |
1285 | ! |
title_dataname <- paste(title, dataname, sep = " - ") |
1286 | ! |
label <- if (label == "") { |
1287 | ! |
paste("Missing Data", sum_type, dataname, sep = " - ") |
1288 |
} else { |
|
1289 | ! |
label |
1290 |
} |
|
1291 | ! |
card$set_name(label) |
1292 | ! |
card$append_text(title_dataname, "header2") |
1293 | ! |
if (with_filter) card$append_fs(filter_panel_api$get_filter_state()) |
1294 | ! |
if (sum_type == "Summary") { |
1295 | ! |
card$append_text("Plot", "header3") |
1296 | ! |
card$append_plot(summary_plot_r(), dim = pws1$dim()) |
1297 | ! |
} else if (sum_type == "Combinations") { |
1298 | ! |
card$append_text("Plot", "header3") |
1299 | ! |
card$append_plot(combination_plot_r(), dim = pws2$dim()) |
1300 | ! |
} else if (sum_type == "By Variable Levels") { |
1301 | ! |
card$append_text("Table", "header3") |
1302 | ! |
card$append_table(summary_table_r[["summary_data"]]) |
1303 | ! |
} else if (sum_type == "Grouped by Subject") { |
1304 | ! |
card$append_text("Plot", "header3") |
1305 | ! |
card$append_plot(by_subject_plot_r(), dim = pws3$dim()) |
1306 |
} |
|
1307 | ! |
if (!comment == "") { |
1308 | ! |
card$append_text("Comment", "header3") |
1309 | ! |
card$append_text(comment) |
1310 |
} |
|
1311 | ! |
card$append_src(teal.code::get_code(final_q())) |
1312 | ! |
card |
1313 |
} |
|
1314 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
1315 |
} |
|
1316 |
### |
|
1317 |
}) |
|
1318 |
} |
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 |
#' @templateVar ggnames "Elbow plot", "Circle plot", "Biplot", "Eigenvector plot" |
|
17 |
#' @template ggplot2_args_multi |
|
18 |
#' |
|
19 |
#' @inherit shared_params return |
|
20 |
#' |
|
21 |
#' @examplesShinylive |
|
22 |
#' library(teal.modules.general) |
|
23 |
#' interactive <- function() TRUE |
|
24 |
#' {{ next_example }} |
|
25 |
#' @examples |
|
26 |
#' # general data example |
|
27 |
#' data <- teal_data() |
|
28 |
#' data <- within(data, { |
|
29 |
#' require(nestcolor) |
|
30 |
#' USArrests <- USArrests |
|
31 |
#' }) |
|
32 |
#' |
|
33 |
#' app <- init( |
|
34 |
#' data = data, |
|
35 |
#' modules = modules( |
|
36 |
#' tm_a_pca( |
|
37 |
#' "PCA", |
|
38 |
#' dat = data_extract_spec( |
|
39 |
#' dataname = "USArrests", |
|
40 |
#' select = select_spec( |
|
41 |
#' choices = variable_choices( |
|
42 |
#' data = data[["USArrests"]], c("Murder", "Assault", "UrbanPop", "Rape") |
|
43 |
#' ), |
|
44 |
#' selected = c("Murder", "Assault"), |
|
45 |
#' multiple = TRUE |
|
46 |
#' ), |
|
47 |
#' filter = NULL |
|
48 |
#' ) |
|
49 |
#' ) |
|
50 |
#' ) |
|
51 |
#' ) |
|
52 |
#' if (interactive()) { |
|
53 |
#' shinyApp(app$ui, app$server) |
|
54 |
#' } |
|
55 |
#' |
|
56 |
#' @examplesShinylive |
|
57 |
#' library(teal.modules.general) |
|
58 |
#' interactive <- function() TRUE |
|
59 |
#' {{ next_example }} |
|
60 |
#' @examples |
|
61 |
#' # CDISC data example |
|
62 |
#' data <- teal_data() |
|
63 |
#' data <- within(data, { |
|
64 |
#' require(nestcolor) |
|
65 |
#' ADSL <- rADSL |
|
66 |
#' }) |
|
67 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
68 |
#' |
|
69 |
#' app <- init( |
|
70 |
#' data = data, |
|
71 |
#' modules = modules( |
|
72 |
#' tm_a_pca( |
|
73 |
#' "PCA", |
|
74 |
#' dat = data_extract_spec( |
|
75 |
#' dataname = "ADSL", |
|
76 |
#' select = select_spec( |
|
77 |
#' choices = variable_choices( |
|
78 |
#' data = data[["ADSL"]], c("BMRKR1", "AGE", "EOSDY") |
|
79 |
#' ), |
|
80 |
#' selected = c("BMRKR1", "AGE"), |
|
81 |
#' multiple = TRUE |
|
82 |
#' ), |
|
83 |
#' filter = NULL |
|
84 |
#' ) |
|
85 |
#' ) |
|
86 |
#' ) |
|
87 |
#' ) |
|
88 |
#' if (interactive()) { |
|
89 |
#' shinyApp(app$ui, app$server) |
|
90 |
#' } |
|
91 |
#' |
|
92 |
#' @export |
|
93 |
#' |
|
94 |
tm_a_pca <- function(label = "Principal Component Analysis", |
|
95 |
dat, |
|
96 |
plot_height = c(600, 200, 2000), |
|
97 |
plot_width = NULL, |
|
98 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
99 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
100 |
rotate_xaxis_labels = FALSE, |
|
101 |
font_size = c(12, 8, 20), |
|
102 |
alpha = c(1, 0, 1), |
|
103 |
size = c(2, 1, 8), |
|
104 |
pre_output = NULL, |
|
105 |
post_output = NULL) { |
|
106 | ! |
message("Initializing tm_a_pca") |
107 | ||
108 |
# Normalize the parameters |
|
109 | ! |
if (inherits(dat, "data_extract_spec")) dat <- list(dat) |
110 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
111 | ||
112 |
# Start of assertions |
|
113 | ! |
checkmate::assert_string(label) |
114 | ! |
checkmate::assert_list(dat, types = "data_extract_spec") |
115 | ||
116 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
117 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
118 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
119 | ! |
checkmate::assert_numeric( |
120 | ! |
plot_width[1], |
121 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
122 |
) |
|
123 | ||
124 | ! |
ggtheme <- match.arg(ggtheme) |
125 | ||
126 | ! |
plot_choices <- c("Elbow plot", "Circle plot", "Biplot", "Eigenvector plot") |
127 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
128 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
129 | ||
130 | ! |
checkmate::assert_flag(rotate_xaxis_labels) |
131 | ||
132 | ! |
if (length(font_size) == 1) { |
133 | ! |
checkmate::assert_numeric(font_size, any.missing = FALSE, finite = TRUE, lower = 8, upper = 20) |
134 |
} else { |
|
135 | ! |
checkmate::assert_numeric(font_size, len = 3, any.missing = FALSE, finite = TRUE, lower = 8, upper = 20) |
136 | ! |
checkmate::assert_numeric(font_size[1], lower = font_size[2], upper = font_size[3], .var.name = "font_size") |
137 |
} |
|
138 | ||
139 | ! |
if (length(alpha) == 1) { |
140 | ! |
checkmate::assert_numeric(alpha, any.missing = FALSE, finite = TRUE, lower = 0, upper = 1) |
141 |
} else { |
|
142 | ! |
checkmate::assert_numeric(alpha, len = 3, any.missing = FALSE, finite = TRUE, lower = 0, upper = 1) |
143 | ! |
checkmate::assert_numeric(alpha[1], lower = alpha[2], upper = alpha[3], .var.name = "alpha") |
144 |
} |
|
145 | ||
146 | ! |
if (length(size) == 1) { |
147 | ! |
checkmate::assert_numeric(size, any.missing = FALSE, finite = TRUE, lower = 1, upper = 8) |
148 |
} else { |
|
149 | ! |
checkmate::assert_numeric(size, len = 3, any.missing = FALSE, finite = TRUE, lower = 1, upper = 8) |
150 | ! |
checkmate::assert_numeric(size[1], lower = size[2], upper = size[3], .var.name = "size") |
151 |
} |
|
152 | ||
153 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
154 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
155 |
# End of assertions |
|
156 | ||
157 |
# Make UI args |
|
158 | ! |
args <- as.list(environment()) |
159 | ||
160 | ! |
data_extract_list <- list(dat = dat) |
161 | ||
162 | ! |
ans <- module( |
163 | ! |
label = label, |
164 | ! |
server = srv_a_pca, |
165 | ! |
ui = ui_a_pca, |
166 | ! |
ui_args = args, |
167 | ! |
server_args = c( |
168 | ! |
data_extract_list, |
169 | ! |
list( |
170 | ! |
plot_height = plot_height, |
171 | ! |
plot_width = plot_width, |
172 | ! |
ggplot2_args = ggplot2_args |
173 |
) |
|
174 |
), |
|
175 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
176 |
) |
|
177 | ! |
attr(ans, "teal_bookmarkable") <- FALSE |
178 | ! |
ans |
179 |
} |
|
180 | ||
181 |
# UI function for the PCA module |
|
182 |
ui_a_pca <- function(id, ...) { |
|
183 | ! |
ns <- NS(id) |
184 | ! |
args <- list(...) |
185 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$dat) |
186 | ||
187 | ! |
color_selector <- args$dat |
188 | ! |
for (i in seq_along(color_selector)) { |
189 | ! |
color_selector[[i]]$select$multiple <- FALSE |
190 | ! |
color_selector[[i]]$select$always_selected <- NULL |
191 | ! |
color_selector[[i]]$select$selected <- NULL |
192 |
} |
|
193 | ||
194 | ! |
tagList( |
195 | ! |
include_css_files("custom"), |
196 | ! |
teal.widgets::standard_layout( |
197 | ! |
output = teal.widgets::white_small_well( |
198 | ! |
uiOutput(ns("all_plots")) |
199 |
), |
|
200 | ! |
encoding = tags$div( |
201 |
### Reporter |
|
202 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
203 |
### |
|
204 | ! |
tags$label("Encodings", class = "text-primary"), |
205 | ! |
teal.transform::datanames_input(args["dat"]), |
206 | ! |
teal.transform::data_extract_ui( |
207 | ! |
id = ns("dat"), |
208 | ! |
label = "Data selection", |
209 | ! |
data_extract_spec = args$dat, |
210 | ! |
is_single_dataset = is_single_dataset_value |
211 |
), |
|
212 | ! |
teal.widgets::panel_group( |
213 | ! |
teal.widgets::panel_item( |
214 | ! |
title = "Display", |
215 | ! |
collapsed = FALSE, |
216 | ! |
checkboxGroupInput( |
217 | ! |
ns("tables_display"), |
218 | ! |
"Tables display", |
219 | ! |
choices = c("PC importance" = "importance", "Eigenvectors" = "eigenvector"), |
220 | ! |
selected = c("importance", "eigenvector") |
221 |
), |
|
222 | ! |
radioButtons( |
223 | ! |
ns("plot_type"), |
224 | ! |
label = "Plot type", |
225 | ! |
choices = args$plot_choices, |
226 | ! |
selected = args$plot_choices[1] |
227 |
) |
|
228 |
), |
|
229 | ! |
teal.widgets::panel_item( |
230 | ! |
title = "Pre-processing", |
231 | ! |
radioButtons( |
232 | ! |
ns("standardization"), "Standardization", |
233 | ! |
choices = c("None" = "none", "Center" = "center", "Center & Scale" = "center_scale"), |
234 | ! |
selected = "center_scale" |
235 |
), |
|
236 | ! |
radioButtons( |
237 | ! |
ns("na_action"), "NA action", |
238 | ! |
choices = c("None" = "none", "Drop" = "drop"), |
239 | ! |
selected = "none" |
240 |
) |
|
241 |
), |
|
242 | ! |
teal.widgets::panel_item( |
243 | ! |
title = "Selected plot specific settings", |
244 | ! |
collapsed = FALSE, |
245 | ! |
uiOutput(ns("plot_settings")), |
246 | ! |
conditionalPanel( |
247 | ! |
condition = sprintf("input['%s'] == 'Biplot'", ns("plot_type")), |
248 | ! |
list( |
249 | ! |
teal.transform::data_extract_ui( |
250 | ! |
id = ns("response"), |
251 | ! |
label = "Color by", |
252 | ! |
data_extract_spec = color_selector, |
253 | ! |
is_single_dataset = is_single_dataset_value |
254 |
), |
|
255 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("alpha"), "Opacity:", args$alpha, ticks = FALSE), |
256 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("size"), "Points size:", args$size, ticks = FALSE) |
257 |
) |
|
258 |
) |
|
259 |
), |
|
260 | ! |
teal.widgets::panel_item( |
261 | ! |
title = "Plot settings", |
262 | ! |
collapsed = TRUE, |
263 | ! |
conditionalPanel( |
264 | ! |
condition = sprintf( |
265 | ! |
"input['%s'] == 'Elbow plot' || input['%s'] == 'Eigenvector plot'", |
266 | ! |
ns("plot_type"), |
267 | ! |
ns("plot_type") |
268 |
), |
|
269 | ! |
list(checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = args$rotate_xaxis_labels)) |
270 |
), |
|
271 | ! |
selectInput( |
272 | ! |
inputId = ns("ggtheme"), |
273 | ! |
label = "Theme (by ggplot):", |
274 | ! |
choices = ggplot_themes, |
275 | ! |
selected = args$ggtheme, |
276 | ! |
multiple = FALSE |
277 |
), |
|
278 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("font_size"), "Font Size", args$font_size, ticks = FALSE) |
279 |
) |
|
280 |
) |
|
281 |
), |
|
282 | ! |
forms = tagList( |
283 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
284 |
), |
|
285 | ! |
pre_output = args$pre_output, |
286 | ! |
post_output = args$post_output |
287 |
) |
|
288 |
) |
|
289 |
} |
|
290 | ||
291 |
# Server function for the PCA module |
|
292 |
srv_a_pca <- function(id, data, reporter, filter_panel_api, dat, plot_height, plot_width, ggplot2_args) { |
|
293 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
294 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
295 | ! |
checkmate::assert_class(data, "reactive") |
296 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
297 | ! |
moduleServer(id, function(input, output, session) { |
298 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
299 | ||
300 | ! |
response <- dat |
301 | ||
302 | ! |
for (i in seq_along(response)) { |
303 | ! |
response[[i]]$select$multiple <- FALSE |
304 | ! |
response[[i]]$select$always_selected <- NULL |
305 | ! |
response[[i]]$select$selected <- NULL |
306 | ! |
all_cols <- teal.data::col_labels(isolate(data())[[response[[i]]$dataname]]) |
307 | ! |
ignore_cols <- unlist(teal.data::join_keys(isolate(data()))[[response[[i]]$dataname]]) |
308 | ! |
color_cols <- all_cols[!names(all_cols) %in% ignore_cols] |
309 | ! |
response[[i]]$select$choices <- teal.transform::choices_labeled(names(color_cols), color_cols) |
310 |
} |
|
311 | ||
312 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
313 | ! |
data_extract = list(dat = dat, response = response), |
314 | ! |
datasets = data, |
315 | ! |
select_validation_rule = list( |
316 | ! |
dat = ~ if (length(.) < 2L) "Please select more than 1 variable to perform PCA.", |
317 | ! |
response = shinyvalidate::compose_rules( |
318 | ! |
shinyvalidate::sv_optional(), |
319 | ! |
~ if (isTRUE(is.element(., selector_list()$dat()$select))) { |
320 | ! |
"Response must not have been used for PCA." |
321 |
} |
|
322 |
) |
|
323 |
) |
|
324 |
) |
|
325 | ||
326 | ! |
iv_r <- reactive({ |
327 | ! |
iv <- shinyvalidate::InputValidator$new() |
328 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
329 |
}) |
|
330 | ||
331 | ! |
iv_extra <- shinyvalidate::InputValidator$new() |
332 | ! |
iv_extra$add_rule("x_axis", function(value) { |
333 | ! |
if (isTRUE(input$plot_type %in% c("Circle plot", "Biplot"))) { |
334 | ! |
if (!shinyvalidate::input_provided(value)) { |
335 | ! |
"Need X axis" |
336 |
} |
|
337 |
} |
|
338 |
}) |
|
339 | ! |
iv_extra$add_rule("y_axis", function(value) { |
340 | ! |
if (isTRUE(input$plot_type %in% c("Circle plot", "Biplot"))) { |
341 | ! |
if (!shinyvalidate::input_provided(value)) { |
342 | ! |
"Need Y axis" |
343 |
} |
|
344 |
} |
|
345 |
}) |
|
346 | ! |
rule_dupl <- function(...) { |
347 | ! |
if (isTRUE(input$plot_type %in% c("Circle plot", "Biplot"))) { |
348 | ! |
if (isTRUE(input$x_axis == input$y_axis)) { |
349 | ! |
"Please choose different X and Y axes." |
350 |
} |
|
351 |
} |
|
352 |
} |
|
353 | ! |
iv_extra$add_rule("x_axis", rule_dupl) |
354 | ! |
iv_extra$add_rule("y_axis", rule_dupl) |
355 | ! |
iv_extra$add_rule("variables", function(value) { |
356 | ! |
if (identical(input$plot_type, "Circle plot")) { |
357 | ! |
if (!shinyvalidate::input_provided(value)) { |
358 | ! |
"Need Original Coordinates" |
359 |
} |
|
360 |
} |
|
361 |
}) |
|
362 | ! |
iv_extra$add_rule("pc", function(value) { |
363 | ! |
if (identical(input$plot_type, "Eigenvector plot")) { |
364 | ! |
if (!shinyvalidate::input_provided(value)) { |
365 | ! |
"Need PC" |
366 |
} |
|
367 |
} |
|
368 |
}) |
|
369 | ! |
iv_extra$enable() |
370 | ||
371 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
372 | ! |
selector_list = selector_list, |
373 | ! |
datasets = data |
374 |
) |
|
375 | ||
376 | ! |
anl_merged_q <- reactive({ |
377 | ! |
req(anl_merged_input()) |
378 | ! |
data() %>% |
379 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
380 |
}) |
|
381 | ||
382 | ! |
merged <- list( |
383 | ! |
anl_input_r = anl_merged_input, |
384 | ! |
anl_q_r = anl_merged_q |
385 |
) |
|
386 | ||
387 | ! |
validation <- reactive({ |
388 | ! |
req(merged$anl_q_r()) |
389 |
# inputs |
|
390 | ! |
keep_cols <- as.character(merged$anl_input_r()$columns_source$dat) |
391 | ! |
na_action <- input$na_action |
392 | ! |
standardization <- input$standardization |
393 | ! |
center <- standardization %in% c("center", "center_scale") |
394 | ! |
scale <- standardization == "center_scale" |
395 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
396 | ||
397 | ! |
teal::validate_has_data(ANL, 10) |
398 | ! |
validate(need( |
399 | ! |
na_action != "none" | !anyNA(ANL[keep_cols]), |
400 | ! |
paste( |
401 | ! |
"There are NAs in the dataset. Please deal with them in preprocessing", |
402 | ! |
"or select \"Drop\" in the NA actions inside the encodings panel (left)." |
403 |
) |
|
404 |
)) |
|
405 | ! |
if (scale) { |
406 | ! |
not_single <- vapply(ANL[keep_cols], function(column) length(unique(column)) != 1, FUN.VALUE = logical(1)) |
407 | ||
408 | ! |
msg <- paste0( |
409 | ! |
"You have selected `Center & Scale` under `Standardization` in the `Pre-processing` panel, ", |
410 | ! |
"but one or more of your columns has/have a variance value of zero, indicating all values are identical" |
411 |
) |
|
412 | ! |
validate(need(all(not_single), msg)) |
413 |
} |
|
414 |
}) |
|
415 | ||
416 |
# computation ---- |
|
417 | ! |
computation <- reactive({ |
418 | ! |
validation() |
419 | ||
420 |
# inputs |
|
421 | ! |
keep_cols <- as.character(merged$anl_input_r()$columns_source$dat) |
422 | ! |
na_action <- input$na_action |
423 | ! |
standardization <- input$standardization |
424 | ! |
center <- standardization %in% c("center", "center_scale") |
425 | ! |
scale <- standardization == "center_scale" |
426 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
427 | ||
428 | ! |
qenv <- teal.code::eval_code( |
429 | ! |
merged$anl_q_r(), |
430 | ! |
substitute( |
431 | ! |
expr = keep_columns <- keep_cols, |
432 | ! |
env = list(keep_cols = keep_cols) |
433 |
) |
|
434 |
) |
|
435 | ||
436 | ! |
if (na_action == "drop") { |
437 | ! |
qenv <- teal.code::eval_code( |
438 | ! |
qenv, |
439 | ! |
quote(ANL <- tidyr::drop_na(ANL, keep_columns)) |
440 |
) |
|
441 |
} |
|
442 | ||
443 | ! |
qenv <- teal.code::eval_code( |
444 | ! |
qenv, |
445 | ! |
substitute( |
446 | ! |
expr = pca <- summary(stats::prcomp(ANL[keep_columns], center = center, scale. = scale, retx = TRUE)), |
447 | ! |
env = list(center = center, scale = scale) |
448 |
) |
|
449 |
) |
|
450 | ||
451 | ! |
qenv <- teal.code::eval_code( |
452 | ! |
qenv, |
453 | ! |
quote({ |
454 | ! |
tbl_importance <- dplyr::as_tibble(pca$importance, rownames = "Metric") |
455 | ! |
tbl_importance |
456 |
}) |
|
457 |
) |
|
458 | ||
459 | ! |
teal.code::eval_code( |
460 | ! |
qenv, |
461 | ! |
quote({ |
462 | ! |
tbl_eigenvector <- dplyr::as_tibble(pca$rotation, rownames = "Variable") |
463 | ! |
tbl_eigenvector |
464 |
}) |
|
465 |
) |
|
466 |
}) |
|
467 | ||
468 |
# plot args ---- |
|
469 | ! |
output$plot_settings <- renderUI({ |
470 |
# reactivity triggers |
|
471 | ! |
req(iv_r()$is_valid()) |
472 | ! |
req(computation()) |
473 | ! |
qenv <- computation() |
474 | ||
475 | ! |
ns <- session$ns |
476 | ||
477 | ! |
pca <- qenv[["pca"]] |
478 | ! |
chcs_pcs <- colnames(pca$rotation) |
479 | ! |
chcs_vars <- qenv[["keep_columns"]] |
480 | ||
481 | ! |
tagList( |
482 | ! |
conditionalPanel( |
483 | ! |
condition = sprintf( |
484 | ! |
"input['%s'] == 'Biplot' || input['%s'] == 'Circle plot'", |
485 | ! |
ns("plot_type"), ns("plot_type") |
486 |
), |
|
487 | ! |
list( |
488 | ! |
teal.widgets::optionalSelectInput(ns("x_axis"), "X axis", choices = chcs_pcs, selected = chcs_pcs[1]), |
489 | ! |
teal.widgets::optionalSelectInput(ns("y_axis"), "Y axis", choices = chcs_pcs, selected = chcs_pcs[2]), |
490 | ! |
teal.widgets::optionalSelectInput( |
491 | ! |
ns("variables"), "Original coordinates", |
492 | ! |
choices = chcs_vars, selected = chcs_vars, |
493 | ! |
multiple = TRUE |
494 |
) |
|
495 |
) |
|
496 |
), |
|
497 | ! |
conditionalPanel( |
498 | ! |
condition = sprintf("input['%s'] == 'Elbow plot'", ns("plot_type")), |
499 | ! |
helpText("No plot specific settings available.") |
500 |
), |
|
501 | ! |
conditionalPanel( |
502 | ! |
condition = paste0("input['", ns("plot_type"), "'] == 'Eigenvector plot'"), |
503 | ! |
teal.widgets::optionalSelectInput(ns("pc"), "PC", choices = chcs_pcs, selected = chcs_pcs[1]) |
504 |
) |
|
505 |
) |
|
506 |
}) |
|
507 | ||
508 |
# plot elbow ---- |
|
509 | ! |
plot_elbow <- function(base_q) { |
510 | ! |
ggtheme <- input$ggtheme |
511 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
512 | ! |
font_size <- input$font_size |
513 | ||
514 | ! |
angle_value <- ifelse(isTRUE(rotate_xaxis_labels), 45, 0) |
515 | ! |
hjust_value <- ifelse(isTRUE(rotate_xaxis_labels), 1, 0.5) |
516 | ||
517 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
518 | ! |
labs = list(x = "Principal component", y = "Proportion of variance explained", color = "", fill = "Legend"), |
519 | ! |
theme = list( |
520 | ! |
legend.position = "right", |
521 | ! |
legend.spacing.y = quote(grid::unit(-5, "pt")), |
522 | ! |
legend.title = quote(element_text(vjust = 25)), |
523 | ! |
axis.text.x = substitute( |
524 | ! |
element_text(angle = angle_value, hjust = hjust_value), |
525 | ! |
list(angle_value = angle_value, hjust_value = hjust_value) |
526 |
), |
|
527 | ! |
text = substitute(element_text(size = font_size), list(font_size = font_size)) |
528 |
) |
|
529 |
) |
|
530 | ||
531 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
532 | ! |
teal.widgets::resolve_ggplot2_args( |
533 | ! |
user_plot = ggplot2_args[["Elbow plot"]], |
534 | ! |
user_default = ggplot2_args$default, |
535 | ! |
module_plot = dev_ggplot2_args |
536 |
), |
|
537 | ! |
ggtheme = ggtheme |
538 |
) |
|
539 | ||
540 | ! |
teal.code::eval_code( |
541 | ! |
base_q, |
542 | ! |
substitute( |
543 | ! |
expr = { |
544 | ! |
elb_dat <- pca$importance[c("Proportion of Variance", "Cumulative Proportion"), ] %>% |
545 | ! |
dplyr::as_tibble(rownames = "metric") %>% |
546 | ! |
tidyr::gather("component", "value", -metric) %>% |
547 | ! |
dplyr::mutate( |
548 | ! |
component = factor(component, levels = unique(stringr::str_sort(component, numeric = TRUE))) |
549 |
) |
|
550 | ||
551 | ! |
cols <- c(getOption("ggplot2.discrete.colour"), c("lightblue", "darkred", "black"))[1:3] |
552 | ! |
g <- ggplot(mapping = aes_string(x = "component", y = "value")) + |
553 | ! |
geom_bar( |
554 | ! |
aes(fill = "Single variance"), |
555 | ! |
data = dplyr::filter(elb_dat, metric == "Proportion of Variance"), |
556 | ! |
color = "black", |
557 | ! |
stat = "identity" |
558 |
) + |
|
559 | ! |
geom_point( |
560 | ! |
aes(color = "Cumulative variance"), |
561 | ! |
data = dplyr::filter(elb_dat, metric == "Cumulative Proportion") |
562 |
) + |
|
563 | ! |
geom_line( |
564 | ! |
aes(group = 1, color = "Cumulative variance"), |
565 | ! |
data = dplyr::filter(elb_dat, metric == "Cumulative Proportion") |
566 |
) + |
|
567 | ! |
labs + |
568 | ! |
scale_color_manual(values = c("Cumulative variance" = cols[2], "Single variance" = cols[3])) + |
569 | ! |
scale_fill_manual(values = c("Cumulative variance" = cols[2], "Single variance" = cols[1])) + |
570 | ! |
ggthemes + |
571 | ! |
themes |
572 | ||
573 | ! |
print(g) |
574 |
}, |
|
575 | ! |
env = list( |
576 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
577 | ! |
labs = parsed_ggplot2_args$labs, |
578 | ! |
themes = parsed_ggplot2_args$theme |
579 |
) |
|
580 |
) |
|
581 |
) |
|
582 |
} |
|
583 | ||
584 |
# plot circle ---- |
|
585 | ! |
plot_circle <- function(base_q) { |
586 | ! |
x_axis <- input$x_axis |
587 | ! |
y_axis <- input$y_axis |
588 | ! |
variables <- input$variables |
589 | ! |
ggtheme <- input$ggtheme |
590 | ||
591 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
592 | ! |
font_size <- input$font_size |
593 | ||
594 | ! |
angle <- ifelse(isTRUE(rotate_xaxis_labels), 45, 0) |
595 | ! |
hjust <- ifelse(isTRUE(rotate_xaxis_labels), 1, 0.5) |
596 | ||
597 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
598 | ! |
theme = list( |
599 | ! |
text = substitute(element_text(size = font_size), list(font_size = font_size)), |
600 | ! |
axis.text.x = substitute( |
601 | ! |
element_text(angle = angle_val, hjust = hjust_val), |
602 | ! |
list(angle_val = angle, hjust_val = hjust) |
603 |
) |
|
604 |
) |
|
605 |
) |
|
606 | ||
607 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
608 | ! |
user_plot = ggplot2_args[["Circle plot"]], |
609 | ! |
user_default = ggplot2_args$default, |
610 | ! |
module_plot = dev_ggplot2_args |
611 |
) |
|
612 | ||
613 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
614 | ! |
all_ggplot2_args, |
615 | ! |
ggtheme = ggtheme |
616 |
) |
|
617 | ||
618 | ! |
teal.code::eval_code( |
619 | ! |
base_q, |
620 | ! |
substitute( |
621 | ! |
expr = { |
622 | ! |
pca_rot <- pca$rotation[, c(x_axis, y_axis)] %>% |
623 | ! |
dplyr::as_tibble(rownames = "label") %>% |
624 | ! |
dplyr::filter(label %in% variables) |
625 | ||
626 | ! |
circle_data <- data.frame( |
627 | ! |
x = cos(seq(0, 2 * pi, length.out = 100)), |
628 | ! |
y = sin(seq(0, 2 * pi, length.out = 100)) |
629 |
) |
|
630 | ||
631 | ! |
g <- ggplot(pca_rot) + |
632 | ! |
geom_point(aes_string(x = x_axis, y = y_axis)) + |
633 | ! |
geom_label( |
634 | ! |
aes_string(x = x_axis, y = y_axis, label = "label"), |
635 | ! |
nudge_x = 0.1, nudge_y = 0.05, |
636 | ! |
fontface = "bold" |
637 |
) + |
|
638 | ! |
geom_path(aes(x, y, group = 1), data = circle_data) + |
639 | ! |
geom_point(aes(x = x, y = y), data = data.frame(x = 0, y = 0), shape = "x", size = 5) + |
640 | ! |
labs + |
641 | ! |
ggthemes + |
642 | ! |
themes |
643 | ! |
print(g) |
644 |
}, |
|
645 | ! |
env = list( |
646 | ! |
x_axis = x_axis, |
647 | ! |
y_axis = y_axis, |
648 | ! |
variables = variables, |
649 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
650 | ! |
labs = `if`(is.null(parsed_ggplot2_args$labs), quote(labs()), parsed_ggplot2_args$labs), |
651 | ! |
themes = parsed_ggplot2_args$theme |
652 |
) |
|
653 |
) |
|
654 |
) |
|
655 |
} |
|
656 | ||
657 |
# plot biplot ---- |
|
658 | ! |
plot_biplot <- function(base_q) { |
659 | ! |
qenv <- base_q |
660 | ||
661 | ! |
ANL <- qenv[["ANL"]] |
662 | ||
663 | ! |
resp_col <- as.character(merged$anl_input_r()$columns_source$response) |
664 | ! |
dat_cols <- as.character(merged$anl_input_r()$columns_source$dat) |
665 | ! |
x_axis <- input$x_axis |
666 | ! |
y_axis <- input$y_axis |
667 | ! |
variables <- input$variables |
668 | ! |
pca <- qenv[["pca"]] |
669 | ||
670 | ! |
ggtheme <- input$ggtheme |
671 | ||
672 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
673 | ! |
alpha <- input$alpha |
674 | ! |
size <- input$size |
675 | ! |
font_size <- input$font_size |
676 | ||
677 | ! |
qenv <- teal.code::eval_code( |
678 | ! |
qenv, |
679 | ! |
substitute( |
680 | ! |
expr = pca_rot <- dplyr::as_tibble(pca$x[, c(x_axis, y_axis)]), |
681 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
682 |
) |
|
683 |
) |
|
684 | ||
685 |
# rot_vars = data frame that displays arrows in the plot, need to be scaled to data |
|
686 | ! |
if (!is.null(input$variables)) { |
687 | ! |
qenv <- teal.code::eval_code( |
688 | ! |
qenv, |
689 | ! |
substitute( |
690 | ! |
expr = { |
691 | ! |
r <- sqrt(qchisq(0.69, df = 2)) * prod(colMeans(pca_rot ^ 2)) ^ (1 / 4) # styler: off |
692 | ! |
v_scale <- rowSums(pca$rotation ^ 2) # styler: off |
693 | ||
694 | ! |
rot_vars <- pca$rotation[, c(x_axis, y_axis)] %>% |
695 | ! |
dplyr::as_tibble(rownames = "label") %>% |
696 | ! |
dplyr::mutate_at(vars(c(x_axis, y_axis)), function(x) r * x / sqrt(max(v_scale))) |
697 |
}, |
|
698 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
699 |
) |
|
700 |
) %>% |
|
701 | ! |
teal.code::eval_code( |
702 | ! |
if (is.logical(pca$center) && !pca$center) { |
703 | ! |
substitute( |
704 | ! |
expr = { |
705 | ! |
rot_vars <- rot_vars %>% |
706 | ! |
tibble::column_to_rownames("label") %>% |
707 | ! |
sweep(1, apply(ANL[keep_columns], 2, mean, na.rm = TRUE)) %>% |
708 | ! |
tibble::rownames_to_column("label") %>% |
709 | ! |
dplyr::mutate( |
710 | ! |
xstart = mean(pca$x[, x_axis], na.rm = TRUE), |
711 | ! |
ystart = mean(pca$x[, y_axis], na.rm = TRUE) |
712 |
) |
|
713 |
}, |
|
714 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
715 |
) |
|
716 |
} else { |
|
717 | ! |
quote(rot_vars <- rot_vars %>% dplyr::mutate(xstart = 0, ystart = 0)) |
718 |
} |
|
719 |
) %>% |
|
720 | ! |
teal.code::eval_code( |
721 | ! |
substitute( |
722 | ! |
expr = rot_vars <- rot_vars %>% dplyr::filter(label %in% variables), |
723 | ! |
env = list(variables = variables) |
724 |
) |
|
725 |
) |
|
726 |
} |
|
727 | ||
728 | ! |
pca_plot_biplot_expr <- list(quote(ggplot())) |
729 | ||
730 | ! |
if (length(resp_col) == 0) { |
731 | ! |
pca_plot_biplot_expr <- c( |
732 | ! |
pca_plot_biplot_expr, |
733 | ! |
substitute( |
734 | ! |
geom_point(aes_string(x = x_axis, y = y_axis), data = pca_rot, alpha = alpha, size = size), |
735 | ! |
list(x_axis = input$x_axis, y_axis = input$y_axis, alpha = input$alpha, size = input$size) |
736 |
) |
|
737 |
) |
|
738 | ! |
dev_labs <- list() |
739 |
} else { |
|
740 | ! |
rp_keys <- setdiff(colnames(ANL), as.character(unlist(merged$anl_input_r()$columns_source))) |
741 | ||
742 | ! |
response <- ANL[[resp_col]] |
743 | ||
744 | ! |
aes_biplot <- substitute( |
745 | ! |
aes_string(x = x_axis, y = y_axis, color = "response"), |
746 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
747 |
) |
|
748 | ||
749 | ! |
qenv <- teal.code::eval_code( |
750 | ! |
qenv, |
751 | ! |
substitute(response <- ANL[[resp_col]], env = list(resp_col = resp_col)) |
752 |
) |
|
753 | ||
754 | ! |
dev_labs <- list(color = varname_w_label(resp_col, ANL)) |
755 | ||
756 | ! |
scales_biplot <- |
757 | ! |
if ( |
758 | ! |
is.character(response) || |
759 | ! |
is.factor(response) || |
760 | ! |
(is.numeric(response) && length(unique(response)) <= 6) |
761 |
) { |
|
762 | ! |
qenv <- teal.code::eval_code( |
763 | ! |
qenv, |
764 | ! |
quote(pca_rot$response <- as.factor(response)) |
765 |
) |
|
766 | ! |
quote(scale_color_brewer(palette = "Dark2")) |
767 | ! |
} else if (inherits(response, "Date")) { |
768 | ! |
qenv <- teal.code::eval_code( |
769 | ! |
qenv, |
770 | ! |
quote(pca_rot$response <- numeric(response)) |
771 |
) |
|
772 | ||
773 | ! |
quote( |
774 | ! |
scale_color_gradient( |
775 | ! |
low = c(getOption("ggplot2.discrete.colour")[2], "darkred")[1], |
776 | ! |
high = c(getOption("ggplot2.discrete.colour"), "lightblue")[1], |
777 | ! |
labels = function(x) as.Date(x, origin = "1970-01-01") |
778 |
) |
|
779 |
) |
|
780 |
} else { |
|
781 | ! |
qenv <- teal.code::eval_code( |
782 | ! |
qenv, |
783 | ! |
quote(pca_rot$response <- response) |
784 |
) |
|
785 | ! |
quote(scale_color_gradient( |
786 | ! |
low = c(getOption("ggplot2.discrete.colour")[2], "darkred")[1], |
787 | ! |
high = c(getOption("ggplot2.discrete.colour"), "lightblue")[1] |
788 |
)) |
|
789 |
} |
|
790 | ||
791 | ! |
pca_plot_biplot_expr <- c( |
792 | ! |
pca_plot_biplot_expr, |
793 | ! |
substitute( |
794 | ! |
geom_point(aes_biplot, data = pca_rot, alpha = alpha, size = size), |
795 | ! |
env = list(aes_biplot = aes_biplot, alpha = alpha, size = size) |
796 |
), |
|
797 | ! |
scales_biplot |
798 |
) |
|
799 |
} |
|
800 | ||
801 | ! |
if (!is.null(input$variables)) { |
802 | ! |
pca_plot_biplot_expr <- c( |
803 | ! |
pca_plot_biplot_expr, |
804 | ! |
substitute( |
805 | ! |
geom_segment( |
806 | ! |
aes_string(x = "xstart", y = "ystart", xend = x_axis, yend = y_axis), |
807 | ! |
data = rot_vars, |
808 | ! |
lineend = "round", linejoin = "round", |
809 | ! |
arrow = grid::arrow(length = grid::unit(0.5, "cm")) |
810 |
), |
|
811 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
812 |
), |
|
813 | ! |
substitute( |
814 | ! |
geom_label( |
815 | ! |
aes_string( |
816 | ! |
x = x_axis, |
817 | ! |
y = y_axis, |
818 | ! |
label = "label" |
819 |
), |
|
820 | ! |
data = rot_vars, |
821 | ! |
nudge_y = 0.1, |
822 | ! |
fontface = "bold" |
823 |
), |
|
824 | ! |
env = list(x_axis = x_axis, y_axis = y_axis) |
825 |
), |
|
826 | ! |
quote(geom_point(aes(x = xstart, y = ystart), data = rot_vars, shape = "x", size = 5)) |
827 |
) |
|
828 |
} |
|
829 | ||
830 | ! |
angle <- ifelse(isTRUE(rotate_xaxis_labels), 45, 0) |
831 | ! |
hjust <- ifelse(isTRUE(rotate_xaxis_labels), 1, 0.5) |
832 | ||
833 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
834 | ! |
labs = dev_labs, |
835 | ! |
theme = list( |
836 | ! |
text = substitute(element_text(size = font_size), list(font_size = font_size)), |
837 | ! |
axis.text.x = substitute( |
838 | ! |
element_text(angle = angle_val, hjust = hjust_val), |
839 | ! |
list(angle_val = angle, hjust_val = hjust) |
840 |
) |
|
841 |
) |
|
842 |
) |
|
843 | ||
844 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
845 | ! |
user_plot = ggplot2_args[["Biplot"]], |
846 | ! |
user_default = ggplot2_args$default, |
847 | ! |
module_plot = dev_ggplot2_args |
848 |
) |
|
849 | ||
850 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
851 | ! |
all_ggplot2_args, |
852 | ! |
ggtheme = ggtheme |
853 |
) |
|
854 | ||
855 | ! |
pca_plot_biplot_expr <- c( |
856 | ! |
pca_plot_biplot_expr, |
857 | ! |
parsed_ggplot2_args |
858 |
) |
|
859 | ||
860 | ! |
teal.code::eval_code( |
861 | ! |
qenv, |
862 | ! |
substitute( |
863 | ! |
expr = { |
864 | ! |
g <- plot_call |
865 | ! |
print(g) |
866 |
}, |
|
867 | ! |
env = list( |
868 | ! |
plot_call = Reduce(function(x, y) call("+", x, y), pca_plot_biplot_expr) |
869 |
) |
|
870 |
) |
|
871 |
) |
|
872 |
} |
|
873 | ||
874 |
# plot pc_var ---- |
|
875 | ! |
plot_pc_var <- function(base_q) { |
876 | ! |
pc <- input$pc |
877 | ! |
ggtheme <- input$ggtheme |
878 | ||
879 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
880 | ! |
font_size <- input$font_size |
881 | ||
882 | ! |
angle <- ifelse(rotate_xaxis_labels, 45, 0) |
883 | ! |
hjust <- ifelse(rotate_xaxis_labels, 1, 0.5) |
884 | ||
885 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
886 | ! |
theme = list( |
887 | ! |
text = substitute(element_text(size = font_size), list(font_size = font_size)), |
888 | ! |
axis.text.x = substitute( |
889 | ! |
element_text(angle = angle_val, hjust = hjust_val), |
890 | ! |
list(angle_val = angle, hjust_val = hjust) |
891 |
) |
|
892 |
) |
|
893 |
) |
|
894 | ||
895 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
896 | ! |
user_plot = ggplot2_args[["Eigenvector plot"]], |
897 | ! |
user_default = ggplot2_args$default, |
898 | ! |
module_plot = dev_ggplot2_args |
899 |
) |
|
900 | ||
901 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
902 | ! |
all_ggplot2_args, |
903 | ! |
ggtheme = ggtheme |
904 |
) |
|
905 | ||
906 | ! |
ggplot_exprs <- c( |
907 | ! |
list( |
908 | ! |
quote(ggplot(pca_rot)), |
909 | ! |
substitute( |
910 | ! |
geom_bar( |
911 | ! |
aes_string(x = "Variable", y = pc), |
912 | ! |
stat = "identity", |
913 | ! |
color = "black", |
914 | ! |
fill = c(getOption("ggplot2.discrete.colour"), "lightblue")[1] |
915 |
), |
|
916 | ! |
env = list(pc = pc) |
917 |
), |
|
918 | ! |
substitute( |
919 | ! |
geom_text( |
920 | ! |
aes( |
921 | ! |
x = Variable, |
922 | ! |
y = pc_name, |
923 | ! |
label = round(pc_name, 3), |
924 | ! |
vjust = ifelse(pc_name > 0, -0.5, 1.3) |
925 |
) |
|
926 |
), |
|
927 | ! |
env = list(pc_name = as.name(pc)) |
928 |
) |
|
929 |
), |
|
930 | ! |
parsed_ggplot2_args$labs, |
931 | ! |
parsed_ggplot2_args$ggtheme, |
932 | ! |
parsed_ggplot2_args$theme |
933 |
) |
|
934 | ||
935 | ! |
teal.code::eval_code( |
936 | ! |
base_q, |
937 | ! |
substitute( |
938 | ! |
expr = { |
939 | ! |
pca_rot <- pca$rotation[, pc, drop = FALSE] %>% |
940 | ! |
dplyr::as_tibble(rownames = "Variable") |
941 | ||
942 | ! |
g <- plot_call |
943 | ||
944 | ! |
print(g) |
945 |
}, |
|
946 | ! |
env = list( |
947 | ! |
pc = pc, |
948 | ! |
plot_call = Reduce(function(x, y) call("+", x, y), ggplot_exprs) |
949 |
) |
|
950 |
) |
|
951 |
) |
|
952 |
} |
|
953 | ||
954 |
# plot final ---- |
|
955 | ! |
output_q <- reactive({ |
956 | ! |
req(computation()) |
957 | ! |
teal::validate_inputs(iv_r()) |
958 | ! |
teal::validate_inputs(iv_extra, header = "Plot settings are required") |
959 | ||
960 | ! |
switch(input$plot_type, |
961 | ! |
"Elbow plot" = plot_elbow(computation()), |
962 | ! |
"Circle plot" = plot_circle(computation()), |
963 | ! |
"Biplot" = plot_biplot(computation()), |
964 | ! |
"Eigenvector plot" = plot_pc_var(computation()), |
965 | ! |
stop("Unknown plot") |
966 |
) |
|
967 |
}) |
|
968 | ||
969 | ! |
plot_r <- reactive({ |
970 | ! |
output_q()[["g"]] |
971 |
}) |
|
972 | ||
973 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
974 | ! |
id = "pca_plot", |
975 | ! |
plot_r = plot_r, |
976 | ! |
height = plot_height, |
977 | ! |
width = plot_width, |
978 | ! |
graph_align = "center" |
979 |
) |
|
980 | ||
981 |
# tables ---- |
|
982 | ! |
output$tbl_importance <- renderTable( |
983 | ! |
expr = { |
984 | ! |
req("importance" %in% input$tables_display, computation()) |
985 | ! |
computation()[["tbl_importance"]] |
986 |
}, |
|
987 | ! |
bordered = TRUE, |
988 | ! |
align = "c", |
989 | ! |
digits = 3 |
990 |
) |
|
991 | ||
992 | ! |
output$tbl_importance_ui <- renderUI({ |
993 | ! |
req("importance" %in% input$tables_display) |
994 | ! |
tags$div( |
995 | ! |
align = "center", |
996 | ! |
tags$h4("Principal components importance"), |
997 | ! |
tableOutput(session$ns("tbl_importance")), |
998 | ! |
tags$hr() |
999 |
) |
|
1000 |
}) |
|
1001 | ||
1002 | ! |
output$tbl_eigenvector <- renderTable( |
1003 | ! |
expr = { |
1004 | ! |
req("eigenvector" %in% input$tables_display, req(computation())) |
1005 | ! |
computation()[["tbl_eigenvector"]] |
1006 |
}, |
|
1007 | ! |
bordered = TRUE, |
1008 | ! |
align = "c", |
1009 | ! |
digits = 3 |
1010 |
) |
|
1011 | ||
1012 | ! |
output$tbl_eigenvector_ui <- renderUI({ |
1013 | ! |
req("eigenvector" %in% input$tables_display) |
1014 | ! |
tags$div( |
1015 | ! |
align = "center", |
1016 | ! |
tags$h4("Eigenvectors"), |
1017 | ! |
tableOutput(session$ns("tbl_eigenvector")), |
1018 | ! |
tags$hr() |
1019 |
) |
|
1020 |
}) |
|
1021 | ||
1022 | ! |
output$all_plots <- renderUI({ |
1023 | ! |
teal::validate_inputs(iv_r()) |
1024 | ! |
teal::validate_inputs(iv_extra, header = "Plot settings are required") |
1025 | ||
1026 | ! |
validation() |
1027 | ! |
tags$div( |
1028 | ! |
class = "overflow-scroll", |
1029 | ! |
uiOutput(session$ns("tbl_importance_ui")), |
1030 | ! |
uiOutput(session$ns("tbl_eigenvector_ui")), |
1031 | ! |
teal.widgets::plot_with_settings_ui(id = session$ns("pca_plot")) |
1032 |
) |
|
1033 |
}) |
|
1034 | ||
1035 | ! |
teal.widgets::verbatim_popup_srv( |
1036 | ! |
id = "rcode", |
1037 | ! |
verbatim_content = reactive(teal.code::get_code(output_q())), |
1038 | ! |
title = "R Code for PCA" |
1039 |
) |
|
1040 | ||
1041 |
### REPORTER |
|
1042 | ! |
if (with_reporter) { |
1043 | ! |
card_fun <- function(comment, label) { |
1044 | ! |
card <- teal::report_card_template( |
1045 | ! |
title = "Principal Component Analysis Plot", |
1046 | ! |
label = label, |
1047 | ! |
with_filter = with_filter, |
1048 | ! |
filter_panel_api = filter_panel_api |
1049 |
) |
|
1050 | ! |
card$append_text("Principal Components Table", "header3") |
1051 | ! |
card$append_table(computation()[["tbl_importance"]]) |
1052 | ! |
card$append_text("Eigenvectors Table", "header3") |
1053 | ! |
card$append_table(computation()[["tbl_eigenvector"]]) |
1054 | ! |
card$append_text("Plot", "header3") |
1055 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
1056 | ! |
if (!comment == "") { |
1057 | ! |
card$append_text("Comment", "header3") |
1058 | ! |
card$append_text(comment) |
1059 |
} |
|
1060 | ! |
card$append_src(teal.code::get_code(output_q())) |
1061 | ! |
card |
1062 |
} |
|
1063 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
1064 |
} |
|
1065 |
### |
|
1066 |
}) |
|
1067 |
} |
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 |
#' @examplesShinylive |
|
50 |
#' library(teal.modules.general) |
|
51 |
#' interactive <- function() TRUE |
|
52 |
#' {{ next_example }} |
|
53 |
#' @examples |
|
54 |
#' # general data example |
|
55 |
#' data <- teal_data() |
|
56 |
#' data <- within(data, { |
|
57 |
#' require(nestcolor) |
|
58 |
#' CO2 <- data.frame(CO2) |
|
59 |
#' }) |
|
60 |
#' |
|
61 |
#' app <- init( |
|
62 |
#' data = data, |
|
63 |
#' modules = tm_g_bivariate( |
|
64 |
#' x = data_extract_spec( |
|
65 |
#' dataname = "CO2", |
|
66 |
#' select = select_spec( |
|
67 |
#' label = "Select variable:", |
|
68 |
#' choices = variable_choices(data[["CO2"]]), |
|
69 |
#' selected = "conc", |
|
70 |
#' fixed = FALSE |
|
71 |
#' ) |
|
72 |
#' ), |
|
73 |
#' y = data_extract_spec( |
|
74 |
#' dataname = "CO2", |
|
75 |
#' select = select_spec( |
|
76 |
#' label = "Select variable:", |
|
77 |
#' choices = variable_choices(data[["CO2"]]), |
|
78 |
#' selected = "uptake", |
|
79 |
#' multiple = FALSE, |
|
80 |
#' fixed = FALSE |
|
81 |
#' ) |
|
82 |
#' ), |
|
83 |
#' row_facet = data_extract_spec( |
|
84 |
#' dataname = "CO2", |
|
85 |
#' select = select_spec( |
|
86 |
#' label = "Select variable:", |
|
87 |
#' choices = variable_choices(data[["CO2"]]), |
|
88 |
#' selected = "Type", |
|
89 |
#' fixed = FALSE |
|
90 |
#' ) |
|
91 |
#' ), |
|
92 |
#' col_facet = data_extract_spec( |
|
93 |
#' dataname = "CO2", |
|
94 |
#' select = select_spec( |
|
95 |
#' label = "Select variable:", |
|
96 |
#' choices = variable_choices(data[["CO2"]]), |
|
97 |
#' selected = "Treatment", |
|
98 |
#' fixed = FALSE |
|
99 |
#' ) |
|
100 |
#' ) |
|
101 |
#' ) |
|
102 |
#' ) |
|
103 |
#' if (interactive()) { |
|
104 |
#' shinyApp(app$ui, app$server) |
|
105 |
#' } |
|
106 |
#' |
|
107 |
#' @examplesShinylive |
|
108 |
#' library(teal.modules.general) |
|
109 |
#' interactive <- function() TRUE |
|
110 |
#' {{ next_example }} |
|
111 |
#' @examples |
|
112 |
#' # CDISC data example |
|
113 |
#' data <- teal_data() |
|
114 |
#' data <- within(data, { |
|
115 |
#' require(nestcolor) |
|
116 |
#' ADSL <- rADSL |
|
117 |
#' }) |
|
118 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
119 |
#' |
|
120 |
#' app <- init( |
|
121 |
#' data = data, |
|
122 |
#' modules = tm_g_bivariate( |
|
123 |
#' x = data_extract_spec( |
|
124 |
#' dataname = "ADSL", |
|
125 |
#' select = select_spec( |
|
126 |
#' label = "Select variable:", |
|
127 |
#' choices = variable_choices(data[["ADSL"]]), |
|
128 |
#' selected = "AGE", |
|
129 |
#' fixed = FALSE |
|
130 |
#' ) |
|
131 |
#' ), |
|
132 |
#' y = data_extract_spec( |
|
133 |
#' dataname = "ADSL", |
|
134 |
#' select = select_spec( |
|
135 |
#' label = "Select variable:", |
|
136 |
#' choices = variable_choices(data[["ADSL"]]), |
|
137 |
#' selected = "SEX", |
|
138 |
#' multiple = FALSE, |
|
139 |
#' fixed = FALSE |
|
140 |
#' ) |
|
141 |
#' ), |
|
142 |
#' row_facet = data_extract_spec( |
|
143 |
#' dataname = "ADSL", |
|
144 |
#' select = select_spec( |
|
145 |
#' label = "Select variable:", |
|
146 |
#' choices = variable_choices(data[["ADSL"]]), |
|
147 |
#' selected = "ARM", |
|
148 |
#' fixed = FALSE |
|
149 |
#' ) |
|
150 |
#' ), |
|
151 |
#' col_facet = data_extract_spec( |
|
152 |
#' dataname = "ADSL", |
|
153 |
#' select = select_spec( |
|
154 |
#' label = "Select variable:", |
|
155 |
#' choices = variable_choices(data[["ADSL"]]), |
|
156 |
#' selected = "COUNTRY", |
|
157 |
#' fixed = FALSE |
|
158 |
#' ) |
|
159 |
#' ) |
|
160 |
#' ) |
|
161 |
#' ) |
|
162 |
#' if (interactive()) { |
|
163 |
#' shinyApp(app$ui, app$server) |
|
164 |
#' } |
|
165 |
#' |
|
166 |
#' @export |
|
167 |
#' |
|
168 |
tm_g_bivariate <- function(label = "Bivariate Plots", |
|
169 |
x, |
|
170 |
y, |
|
171 |
row_facet = NULL, |
|
172 |
col_facet = NULL, |
|
173 |
facet = !is.null(row_facet) || !is.null(col_facet), |
|
174 |
color = NULL, |
|
175 |
fill = NULL, |
|
176 |
size = NULL, |
|
177 |
use_density = FALSE, |
|
178 |
color_settings = FALSE, |
|
179 |
free_x_scales = FALSE, |
|
180 |
free_y_scales = FALSE, |
|
181 |
plot_height = c(600, 200, 2000), |
|
182 |
plot_width = NULL, |
|
183 |
rotate_xaxis_labels = FALSE, |
|
184 |
swap_axes = FALSE, |
|
185 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
186 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
187 |
pre_output = NULL, |
|
188 |
post_output = NULL) { |
|
189 | 18x |
message("Initializing tm_g_bivariate") |
190 | ||
191 |
# Normalize the parameters |
|
192 | 14x |
if (inherits(x, "data_extract_spec")) x <- list(x) |
193 | 13x |
if (inherits(y, "data_extract_spec")) y <- list(y) |
194 | 1x |
if (inherits(row_facet, "data_extract_spec")) row_facet <- list(row_facet) |
195 | 1x |
if (inherits(col_facet, "data_extract_spec")) col_facet <- list(col_facet) |
196 | 1x |
if (inherits(color, "data_extract_spec")) color <- list(color) |
197 | 1x |
if (inherits(fill, "data_extract_spec")) fill <- list(fill) |
198 | 1x |
if (inherits(size, "data_extract_spec")) size <- list(size) |
199 | ||
200 |
# Start of assertions |
|
201 | 18x |
checkmate::assert_string(label) |
202 | ||
203 | 18x |
checkmate::assert_list(x, types = "data_extract_spec") |
204 | 18x |
assert_single_selection(x) |
205 | ||
206 | 16x |
checkmate::assert_list(y, types = "data_extract_spec") |
207 | 16x |
assert_single_selection(y) |
208 | ||
209 | 14x |
checkmate::assert_list(row_facet, types = "data_extract_spec", null.ok = TRUE) |
210 | 14x |
assert_single_selection(row_facet) |
211 | ||
212 | 14x |
checkmate::assert_list(col_facet, types = "data_extract_spec", null.ok = TRUE) |
213 | 14x |
assert_single_selection(col_facet) |
214 | ||
215 | 14x |
checkmate::assert_flag(facet) |
216 | ||
217 | 14x |
checkmate::assert_list(color, types = "data_extract_spec", null.ok = TRUE) |
218 | 14x |
assert_single_selection(color) |
219 | ||
220 | 14x |
checkmate::assert_list(fill, types = "data_extract_spec", null.ok = TRUE) |
221 | 14x |
assert_single_selection(fill) |
222 | ||
223 | 14x |
checkmate::assert_list(size, types = "data_extract_spec", null.ok = TRUE) |
224 | 14x |
assert_single_selection(size) |
225 | ||
226 | 14x |
checkmate::assert_flag(use_density) |
227 | ||
228 |
# Determines color, fill & size if they are not explicitly set |
|
229 | 14x |
checkmate::assert_flag(color_settings) |
230 | 14x |
if (color_settings) { |
231 | 2x |
if (is.null(color)) { |
232 | 2x |
color <- x |
233 | 2x |
color[[1]]$select <- teal.transform::select_spec(choices = color[[1]]$select$choices, selected = NULL) |
234 |
} |
|
235 | 2x |
if (is.null(fill)) { |
236 | 2x |
fill <- x |
237 | 2x |
fill[[1]]$select <- teal.transform::select_spec(choices = fill[[1]]$select$choices, selected = NULL) |
238 |
} |
|
239 | 2x |
if (is.null(size)) { |
240 | 2x |
size <- x |
241 | 2x |
size[[1]]$select <- teal.transform::select_spec(choices = size[[1]]$select$choices, selected = NULL) |
242 |
} |
|
243 |
} else { |
|
244 | 12x |
if (!is.null(c(color, fill, size))) { |
245 | 3x |
stop("'color_settings' argument needs to be set to TRUE if 'color', 'fill', and/or 'size' is/are supplied.") |
246 |
} |
|
247 |
} |
|
248 | ||
249 | 11x |
checkmate::assert_flag(free_x_scales) |
250 | 11x |
checkmate::assert_flag(free_y_scales) |
251 | ||
252 | 11x |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
253 | 10x |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
254 | 8x |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
255 | 7x |
checkmate::assert_numeric( |
256 | 7x |
plot_width[1], |
257 | 7x |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
258 |
) |
|
259 | ||
260 | 5x |
checkmate::assert_flag(rotate_xaxis_labels) |
261 | 5x |
checkmate::assert_flag(swap_axes) |
262 | ||
263 | 5x |
ggtheme <- match.arg(ggtheme) |
264 | 5x |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
265 | ||
266 | 5x |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
267 | 5x |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
268 |
# End of assertions |
|
269 | ||
270 |
# Make UI args |
|
271 | 5x |
args <- as.list(environment()) |
272 | ||
273 | 5x |
data_extract_list <- list( |
274 | 5x |
x = x, |
275 | 5x |
y = y, |
276 | 5x |
row_facet = row_facet, |
277 | 5x |
col_facet = col_facet, |
278 | 5x |
color_settings = color_settings, |
279 | 5x |
color = color, |
280 | 5x |
fill = fill, |
281 | 5x |
size = size |
282 |
) |
|
283 | ||
284 | 5x |
ans <- module( |
285 | 5x |
label = label, |
286 | 5x |
server = srv_g_bivariate, |
287 | 5x |
ui = ui_g_bivariate, |
288 | 5x |
ui_args = args, |
289 | 5x |
server_args = c( |
290 | 5x |
data_extract_list, |
291 | 5x |
list(plot_height = plot_height, plot_width = plot_width, ggplot2_args = ggplot2_args) |
292 |
), |
|
293 | 5x |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
294 |
) |
|
295 | 5x |
attr(ans, "teal_bookmarkable") <- TRUE |
296 | 5x |
ans |
297 |
} |
|
298 | ||
299 |
# UI function for the bivariate module |
|
300 |
ui_g_bivariate <- function(id, ...) { |
|
301 | ! |
args <- list(...) |
302 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset( |
303 | ! |
args$x, args$y, args$row_facet, args$col_facet, args$color, args$fill, args$size |
304 |
) |
|
305 | ||
306 | ! |
ns <- NS(id) |
307 | ! |
teal.widgets::standard_layout( |
308 | ! |
output = teal.widgets::white_small_well( |
309 | ! |
tags$div(teal.widgets::plot_with_settings_ui(id = ns("myplot"))) |
310 |
), |
|
311 | ! |
encoding = tags$div( |
312 |
### Reporter |
|
313 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
314 |
### |
|
315 | ! |
tags$label("Encodings", class = "text-primary"), |
316 | ! |
teal.transform::datanames_input(args[c("x", "y", "row_facet", "col_facet", "color", "fill", "size")]), |
317 | ! |
teal.transform::data_extract_ui( |
318 | ! |
id = ns("x"), |
319 | ! |
label = "X variable", |
320 | ! |
data_extract_spec = args$x, |
321 | ! |
is_single_dataset = is_single_dataset_value |
322 |
), |
|
323 | ! |
teal.transform::data_extract_ui( |
324 | ! |
id = ns("y"), |
325 | ! |
label = "Y variable", |
326 | ! |
data_extract_spec = args$y, |
327 | ! |
is_single_dataset = is_single_dataset_value |
328 |
), |
|
329 | ! |
conditionalPanel( |
330 | ! |
condition = |
331 | ! |
"$(\"button[data-id*='-x-dataset'][data-id$='-select']\").text() == '- Nothing selected - ' || |
332 | ! |
$(\"button[data-id*='-y-dataset'][data-id$='-select']\").text() == '- Nothing selected - ' ", |
333 | ! |
shinyWidgets::radioGroupButtons( |
334 | ! |
inputId = ns("use_density"), |
335 | ! |
label = NULL, |
336 | ! |
choices = c("frequency", "density"), |
337 | ! |
selected = ifelse(args$use_density, "density", "frequency"), |
338 | ! |
justified = TRUE |
339 |
) |
|
340 |
), |
|
341 | ! |
if (!is.null(args$row_facet) || !is.null(args$col_facet)) { |
342 | ! |
tags$div( |
343 | ! |
class = "data-extract-box", |
344 | ! |
tags$label("Facetting"), |
345 | ! |
shinyWidgets::switchInput(inputId = ns("facetting"), value = args$facet, size = "mini"), |
346 | ! |
conditionalPanel( |
347 | ! |
condition = paste0("input['", ns("facetting"), "']"), |
348 | ! |
tags$div( |
349 | ! |
if (!is.null(args$row_facet)) { |
350 | ! |
teal.transform::data_extract_ui( |
351 | ! |
id = ns("row_facet"), |
352 | ! |
label = "Row facetting variable", |
353 | ! |
data_extract_spec = args$row_facet, |
354 | ! |
is_single_dataset = is_single_dataset_value |
355 |
) |
|
356 |
}, |
|
357 | ! |
if (!is.null(args$col_facet)) { |
358 | ! |
teal.transform::data_extract_ui( |
359 | ! |
id = ns("col_facet"), |
360 | ! |
label = "Column facetting variable", |
361 | ! |
data_extract_spec = args$col_facet, |
362 | ! |
is_single_dataset = is_single_dataset_value |
363 |
) |
|
364 |
}, |
|
365 | ! |
checkboxInput(ns("free_x_scales"), "free x scales", value = args$free_x_scales), |
366 | ! |
checkboxInput(ns("free_y_scales"), "free y scales", value = args$free_y_scales) |
367 |
) |
|
368 |
) |
|
369 |
) |
|
370 |
}, |
|
371 | ! |
if (args$color_settings) { |
372 |
# Put a grey border around the coloring settings |
|
373 | ! |
tags$div( |
374 | ! |
class = "data-extract-box", |
375 | ! |
tags$label("Color settings"), |
376 | ! |
shinyWidgets::switchInput(inputId = ns("coloring"), value = TRUE, size = "mini"), |
377 | ! |
conditionalPanel( |
378 | ! |
condition = paste0("input['", ns("coloring"), "']"), |
379 | ! |
tags$div( |
380 | ! |
teal.transform::data_extract_ui( |
381 | ! |
id = ns("color"), |
382 | ! |
label = "Outline color by variable", |
383 | ! |
data_extract_spec = args$color, |
384 | ! |
is_single_dataset = is_single_dataset_value |
385 |
), |
|
386 | ! |
teal.transform::data_extract_ui( |
387 | ! |
id = ns("fill"), |
388 | ! |
label = "Fill color by variable", |
389 | ! |
data_extract_spec = args$fill, |
390 | ! |
is_single_dataset = is_single_dataset_value |
391 |
), |
|
392 | ! |
tags$div( |
393 | ! |
id = ns("size_settings"), |
394 | ! |
teal.transform::data_extract_ui( |
395 | ! |
id = ns("size"), |
396 | ! |
label = "Size of points by variable (only if x and y are numeric)", |
397 | ! |
data_extract_spec = args$size, |
398 | ! |
is_single_dataset = is_single_dataset_value |
399 |
) |
|
400 |
) |
|
401 |
) |
|
402 |
) |
|
403 |
) |
|
404 |
}, |
|
405 | ! |
teal.widgets::panel_group( |
406 | ! |
teal.widgets::panel_item( |
407 | ! |
title = "Plot settings", |
408 | ! |
checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = args$rotate_xaxis_labels), |
409 | ! |
checkboxInput(ns("swap_axes"), "Swap axes", value = args$swap_axes), |
410 | ! |
selectInput( |
411 | ! |
inputId = ns("ggtheme"), |
412 | ! |
label = "Theme (by ggplot):", |
413 | ! |
choices = ggplot_themes, |
414 | ! |
selected = args$ggtheme, |
415 | ! |
multiple = FALSE |
416 |
), |
|
417 | ! |
sliderInput( |
418 | ! |
ns("alpha"), "Opacity Scatterplot:", |
419 | ! |
min = 0, max = 1, |
420 | ! |
step = .05, value = .5, ticks = FALSE |
421 |
), |
|
422 | ! |
sliderInput( |
423 | ! |
ns("fixed_size"), "Scatterplot point size:", |
424 | ! |
min = 1, max = 8, |
425 | ! |
step = 1, value = 2, ticks = FALSE |
426 |
), |
|
427 | ! |
checkboxInput(ns("add_lines"), "Add lines"), |
428 |
) |
|
429 |
) |
|
430 |
), |
|
431 | ! |
forms = tagList( |
432 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
433 |
), |
|
434 | ! |
pre_output = args$pre_output, |
435 | ! |
post_output = args$post_output |
436 |
) |
|
437 |
} |
|
438 | ||
439 |
# Server function for the bivariate module |
|
440 |
srv_g_bivariate <- function(id, |
|
441 |
data, |
|
442 |
reporter, |
|
443 |
filter_panel_api, |
|
444 |
x, |
|
445 |
y, |
|
446 |
row_facet, |
|
447 |
col_facet, |
|
448 |
color_settings = FALSE, |
|
449 |
color, |
|
450 |
fill, |
|
451 |
size, |
|
452 |
plot_height, |
|
453 |
plot_width, |
|
454 |
ggplot2_args) { |
|
455 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
456 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
457 | ! |
checkmate::assert_class(data, "reactive") |
458 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
459 | ! |
moduleServer(id, function(input, output, session) { |
460 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
461 | ||
462 | ! |
ns <- session$ns |
463 | ||
464 | ! |
data_extract <- list( |
465 | ! |
x = x, y = y, row_facet = row_facet, col_facet = col_facet, |
466 | ! |
color = color, fill = fill, size = size |
467 |
) |
|
468 | ||
469 | ! |
rule_var <- function(other) { |
470 | ! |
function(value) { |
471 | ! |
othervalue <- selector_list()[[other]]()$select |
472 | ! |
if (length(value) == 0L && length(othervalue) == 0L) { |
473 | ! |
"Please select at least one of x-variable or y-variable" |
474 |
} |
|
475 |
} |
|
476 |
} |
|
477 | ! |
rule_diff <- function(other) { |
478 | ! |
function(value) { |
479 | ! |
othervalue <- selector_list()[[other]]()[["select"]] |
480 | ! |
if (!is.null(othervalue)) { |
481 | ! |
if (identical(value, othervalue)) { |
482 | ! |
"Row and column facetting variables must be different." |
483 |
} |
|
484 |
} |
|
485 |
} |
|
486 |
} |
|
487 | ||
488 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
489 | ! |
data_extract = data_extract, |
490 | ! |
datasets = data, |
491 | ! |
select_validation_rule = list( |
492 | ! |
x = rule_var("y"), |
493 | ! |
y = rule_var("x"), |
494 | ! |
row_facet = shinyvalidate::compose_rules( |
495 | ! |
shinyvalidate::sv_optional(), |
496 | ! |
rule_diff("col_facet") |
497 |
), |
|
498 | ! |
col_facet = shinyvalidate::compose_rules( |
499 | ! |
shinyvalidate::sv_optional(), |
500 | ! |
rule_diff("row_facet") |
501 |
) |
|
502 |
) |
|
503 |
) |
|
504 | ||
505 | ! |
iv_r <- reactive({ |
506 | ! |
iv_facet <- shinyvalidate::InputValidator$new() |
507 | ! |
iv_child <- teal.transform::compose_and_enable_validators(iv_facet, selector_list, |
508 | ! |
validator_names = c("row_facet", "col_facet") |
509 |
) |
|
510 | ! |
iv_child$condition(~ isTRUE(input$facetting)) |
511 | ||
512 | ! |
iv <- shinyvalidate::InputValidator$new() |
513 | ! |
iv$add_validator(iv_child) |
514 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list, validator_names = c("x", "y")) |
515 |
}) |
|
516 | ||
517 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
518 | ! |
selector_list = selector_list, |
519 | ! |
datasets = data |
520 |
) |
|
521 | ||
522 | ! |
anl_merged_q <- reactive({ |
523 | ! |
req(anl_merged_input()) |
524 | ! |
data() %>% |
525 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
526 |
}) |
|
527 | ||
528 | ! |
merged <- list( |
529 | ! |
anl_input_r = anl_merged_input, |
530 | ! |
anl_q_r = anl_merged_q |
531 |
) |
|
532 | ||
533 | ! |
output_q <- reactive({ |
534 | ! |
teal::validate_inputs(iv_r()) |
535 | ||
536 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
537 | ! |
teal::validate_has_data(ANL, 3) |
538 | ||
539 | ! |
x_col_vec <- as.vector(merged$anl_input_r()$columns_source$x) |
540 | ! |
x_name <- `if`(is.null(x_col_vec), character(0), x_col_vec) |
541 | ! |
y_col_vec <- as.vector(merged$anl_input_r()$columns_source$y) |
542 | ! |
y_name <- `if`(is.null(y_col_vec), character(0), y_col_vec) |
543 | ||
544 | ! |
row_facet_name <- as.vector(merged$anl_input_r()$columns_source$row_facet) |
545 | ! |
col_facet_name <- as.vector(merged$anl_input_r()$columns_source$col_facet) |
546 | ! |
color_name <- if ("color" %in% names(merged$anl_input_r()$columns_source)) { |
547 | ! |
as.vector(merged$anl_input_r()$columns_source$color) |
548 |
} else { |
|
549 | ! |
character(0) |
550 |
} |
|
551 | ! |
fill_name <- if ("fill" %in% names(merged$anl_input_r()$columns_source)) { |
552 | ! |
as.vector(merged$anl_input_r()$columns_source$fill) |
553 |
} else { |
|
554 | ! |
character(0) |
555 |
} |
|
556 | ! |
size_name <- if ("size" %in% names(merged$anl_input_r()$columns_source)) { |
557 | ! |
as.vector(merged$anl_input_r()$columns_source$size) |
558 |
} else { |
|
559 | ! |
character(0) |
560 |
} |
|
561 | ||
562 | ! |
use_density <- input$use_density == "density" |
563 | ! |
free_x_scales <- input$free_x_scales |
564 | ! |
free_y_scales <- input$free_y_scales |
565 | ! |
ggtheme <- input$ggtheme |
566 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
567 | ! |
swap_axes <- input$swap_axes |
568 | ||
569 | ! |
is_scatterplot <- all(vapply(ANL[c(x_name, y_name)], is.numeric, logical(1))) && |
570 | ! |
length(x_name) > 0 && length(y_name) > 0 |
571 | ||
572 | ! |
if (is_scatterplot) { |
573 | ! |
shinyjs::show("alpha") |
574 | ! |
alpha <- input$alpha |
575 | ! |
shinyjs::show("add_lines") |
576 | ||
577 | ! |
if (color_settings && input$coloring) { |
578 | ! |
shinyjs::hide("fixed_size") |
579 | ! |
shinyjs::show("size_settings") |
580 | ! |
size <- NULL |
581 |
} else { |
|
582 | ! |
shinyjs::show("fixed_size") |
583 | ! |
size <- input$fixed_size |
584 |
} |
|
585 |
} else { |
|
586 | ! |
shinyjs::hide("add_lines") |
587 | ! |
updateCheckboxInput(session, "add_lines", value = restoreInput(ns("add_lines"), FALSE)) |
588 | ! |
shinyjs::hide("alpha") |
589 | ! |
shinyjs::hide("fixed_size") |
590 | ! |
shinyjs::hide("size_settings") |
591 | ! |
alpha <- 1 |
592 | ! |
size <- NULL |
593 |
} |
|
594 | ||
595 | ! |
teal::validate_has_data(ANL[, c(x_name, y_name), drop = FALSE], 3, complete = TRUE, allow_inf = FALSE) |
596 | ||
597 | ! |
cl <- bivariate_plot_call( |
598 | ! |
data_name = "ANL", |
599 | ! |
x = x_name, |
600 | ! |
y = y_name, |
601 | ! |
x_class = ifelse(!identical(x_name, character(0)), class(ANL[[x_name]]), "NULL"), |
602 | ! |
y_class = ifelse(!identical(y_name, character(0)), class(ANL[[y_name]]), "NULL"), |
603 | ! |
x_label = varname_w_label(x_name, ANL), |
604 | ! |
y_label = varname_w_label(y_name, ANL), |
605 | ! |
freq = !use_density, |
606 | ! |
theme = ggtheme, |
607 | ! |
rotate_xaxis_labels = rotate_xaxis_labels, |
608 | ! |
swap_axes = swap_axes, |
609 | ! |
alpha = alpha, |
610 | ! |
size = size, |
611 | ! |
ggplot2_args = ggplot2_args |
612 |
) |
|
613 | ||
614 | ! |
facetting <- (isTRUE(input$facetting) && (!is.null(row_facet_name) || !is.null(col_facet_name))) |
615 | ||
616 | ! |
if (facetting) { |
617 | ! |
facet_cl <- facet_ggplot_call(row_facet_name, col_facet_name, free_x_scales, free_y_scales) |
618 | ||
619 | ! |
if (!is.null(facet_cl)) { |
620 | ! |
cl <- call("+", cl, facet_cl) |
621 |
} |
|
622 |
} |
|
623 | ||
624 | ! |
if (input$add_lines) { |
625 | ! |
cl <- call("+", cl, quote(geom_line(size = 1))) |
626 |
} |
|
627 | ||
628 | ! |
coloring_cl <- NULL |
629 | ! |
if (color_settings) { |
630 | ! |
if (input$coloring) { |
631 | ! |
coloring_cl <- coloring_ggplot_call( |
632 | ! |
colour = color_name, |
633 | ! |
fill = fill_name, |
634 | ! |
size = size_name, |
635 | ! |
is_point = any(grepl("geom_point", cl %>% deparse())) |
636 |
) |
|
637 | ! |
legend_lbls <- substitute( |
638 | ! |
expr = labs(color = color_name, fill = fill_name, size = size_name), |
639 | ! |
env = list( |
640 | ! |
color_name = varname_w_label(color_name, ANL), |
641 | ! |
fill_name = varname_w_label(fill_name, ANL), |
642 | ! |
size_name = varname_w_label(size_name, ANL) |
643 |
) |
|
644 |
) |
|
645 |
} |
|
646 | ! |
if (!is.null(coloring_cl)) { |
647 | ! |
cl <- call("+", call("+", cl, coloring_cl), legend_lbls) |
648 |
} |
|
649 |
} |
|
650 | ||
651 |
# Add labels to facets |
|
652 | ! |
nulled_row_facet_name <- varname_w_label(row_facet_name, ANL) |
653 | ! |
nulled_col_facet_name <- varname_w_label(col_facet_name, ANL) |
654 | ! |
without_facet <- (is.null(nulled_row_facet_name) && is.null(nulled_col_facet_name)) || !facetting |
655 | ||
656 | ! |
print_call <- if (without_facet) { |
657 | ! |
quote(print(p)) |
658 |
} else { |
|
659 | ! |
substitute( |
660 | ! |
expr = { |
661 |
# Add facetting labels |
|
662 |
# optional: grid.newpage() # nolint: commented_code. |
|
663 |
# Prefixed with teal.modules.general as its usage will appear in "Show R code" |
|
664 | ! |
p <- teal.modules.general::add_facet_labels( |
665 | ! |
p, |
666 | ! |
xfacet_label = nulled_col_facet_name, |
667 | ! |
yfacet_label = nulled_row_facet_name |
668 |
) |
|
669 | ! |
grid::grid.newpage() |
670 | ! |
grid::grid.draw(p) |
671 |
}, |
|
672 | ! |
env = list(nulled_col_facet_name = nulled_col_facet_name, nulled_row_facet_name = nulled_row_facet_name) |
673 |
) |
|
674 |
} |
|
675 | ||
676 | ! |
teal.code::eval_code(merged$anl_q_r(), substitute(expr = p <- cl, env = list(cl = cl))) %>% |
677 | ! |
teal.code::eval_code(print_call) |
678 |
}) |
|
679 | ||
680 | ! |
plot_r <- reactive({ |
681 | ! |
output_q()[["p"]] |
682 |
}) |
|
683 | ||
684 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
685 | ! |
id = "myplot", |
686 | ! |
plot_r = plot_r, |
687 | ! |
height = plot_height, |
688 | ! |
width = plot_width |
689 |
) |
|
690 | ||
691 | ! |
teal.widgets::verbatim_popup_srv( |
692 | ! |
id = "rcode", |
693 | ! |
verbatim_content = reactive(teal.code::get_code(output_q())), |
694 | ! |
title = "Bivariate Plot" |
695 |
) |
|
696 | ||
697 |
### REPORTER |
|
698 | ! |
if (with_reporter) { |
699 | ! |
card_fun <- function(comment, label) { |
700 | ! |
card <- teal::report_card_template( |
701 | ! |
title = "Bivariate Plot", |
702 | ! |
label = label, |
703 | ! |
with_filter = with_filter, |
704 | ! |
filter_panel_api = filter_panel_api |
705 |
) |
|
706 | ! |
card$append_text("Plot", "header3") |
707 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
708 | ! |
if (!comment == "") { |
709 | ! |
card$append_text("Comment", "header3") |
710 | ! |
card$append_text(comment) |
711 |
} |
|
712 | ! |
card$append_src(teal.code::get_code(output_q())) |
713 | ! |
card |
714 |
} |
|
715 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
716 |
} |
|
717 |
### |
|
718 |
}) |
|
719 |
} |
|
720 | ||
721 |
# Get Substituted ggplot call |
|
722 |
bivariate_plot_call <- function(data_name, |
|
723 |
x = character(0), |
|
724 |
y = character(0), |
|
725 |
x_class = "NULL", |
|
726 |
y_class = "NULL", |
|
727 |
x_label = NULL, |
|
728 |
y_label = NULL, |
|
729 |
freq = TRUE, |
|
730 |
theme = "gray", |
|
731 |
rotate_xaxis_labels = FALSE, |
|
732 |
swap_axes = FALSE, |
|
733 |
alpha = double(0), |
|
734 |
size = 2, |
|
735 |
ggplot2_args = teal.widgets::ggplot2_args()) { |
|
736 | ! |
supported_types <- c("NULL", "numeric", "integer", "factor", "character", "logical", "ordered") |
737 | ! |
validate(need(x_class %in% supported_types, paste0("Data type '", x_class, "' is not supported."))) |
738 | ! |
validate(need(y_class %in% supported_types, paste0("Data type '", y_class, "' is not supported."))) |
739 | ||
740 | ||
741 | ! |
if (identical(x, character(0))) { |
742 | ! |
x <- x_label <- "-" |
743 |
} else { |
|
744 | ! |
x <- if (is.call(x)) x else as.name(x) |
745 |
} |
|
746 | ! |
if (identical(y, character(0))) { |
747 | ! |
y <- y_label <- "-" |
748 |
} else { |
|
749 | ! |
y <- if (is.call(y)) y else as.name(y) |
750 |
} |
|
751 | ||
752 | ! |
cl <- bivariate_ggplot_call( |
753 | ! |
x_class = x_class, |
754 | ! |
y_class = y_class, |
755 | ! |
freq = freq, |
756 | ! |
theme = theme, |
757 | ! |
rotate_xaxis_labels = rotate_xaxis_labels, |
758 | ! |
swap_axes = swap_axes, |
759 | ! |
alpha = alpha, |
760 | ! |
size = size, |
761 | ! |
ggplot2_args = ggplot2_args, |
762 | ! |
x = x, |
763 | ! |
y = y, |
764 | ! |
xlab = x_label, |
765 | ! |
ylab = y_label, |
766 | ! |
data_name = data_name |
767 |
) |
|
768 |
} |
|
769 | ||
770 |
# Create ggplot part of plot call |
|
771 |
# Due to the type of the x and y variable the plot type is chosen |
|
772 |
bivariate_ggplot_call <- function(x_class, |
|
773 |
y_class, |
|
774 |
freq = TRUE, |
|
775 |
theme = "gray", |
|
776 |
rotate_xaxis_labels = FALSE, |
|
777 |
swap_axes = FALSE, |
|
778 |
size = double(0), |
|
779 |
alpha = double(0), |
|
780 |
x = NULL, |
|
781 |
y = NULL, |
|
782 |
xlab = "-", |
|
783 |
ylab = "-", |
|
784 |
data_name = "ANL", |
|
785 |
ggplot2_args = teal.widgets::ggplot2_args()) { |
|
786 | 42x |
x_class <- switch(x_class, |
787 | 42x |
"character" = , |
788 | 42x |
"ordered" = , |
789 | 42x |
"logical" = , |
790 | 42x |
"factor" = "factor", |
791 | 42x |
"integer" = , |
792 | 42x |
"numeric" = "numeric", |
793 | 42x |
"NULL" = "NULL", |
794 | 42x |
stop("unsupported x_class: ", x_class) |
795 |
) |
|
796 | 42x |
y_class <- switch(y_class, |
797 | 42x |
"character" = , |
798 | 42x |
"ordered" = , |
799 | 42x |
"logical" = , |
800 | 42x |
"factor" = "factor", |
801 | 42x |
"integer" = , |
802 | 42x |
"numeric" = "numeric", |
803 | 42x |
"NULL" = "NULL", |
804 | 42x |
stop("unsupported y_class: ", y_class) |
805 |
) |
|
806 | ||
807 | 42x |
if (all(c(x_class, y_class) == "NULL")) { |
808 | ! |
stop("either x or y is required") |
809 |
} |
|
810 | ||
811 | 42x |
reduce_plot_call <- function(...) { |
812 | 104x |
args <- Filter(Negate(is.null), list(...)) |
813 | 104x |
Reduce(function(x, y) call("+", x, y), args) |
814 |
} |
|
815 | ||
816 | 42x |
plot_call <- substitute(ggplot(data_name), env = list(data_name = as.name(data_name))) |
817 | ||
818 |
# Single data plots |
|
819 | 42x |
if (x_class == "numeric" && y_class == "NULL") { |
820 | 6x |
plot_call <- reduce_plot_call(plot_call, substitute(aes(x = xval), env = list(xval = x))) |
821 | ||
822 | 6x |
if (freq) { |
823 | 4x |
plot_call <- reduce_plot_call( |
824 | 4x |
plot_call, |
825 | 4x |
quote(geom_histogram(bins = 30)), |
826 | 4x |
quote(ylab("Frequency")) |
827 |
) |
|
828 |
} else { |
|
829 | 2x |
plot_call <- reduce_plot_call( |
830 | 2x |
plot_call, |
831 | 2x |
quote(geom_histogram(bins = 30, aes(y = after_stat(density)))), |
832 | 2x |
quote(geom_density(aes(y = after_stat(density)))), |
833 | 2x |
quote(ylab("Density")) |
834 |
) |
|
835 |
} |
|
836 | 36x |
} else if (x_class == "NULL" && y_class == "numeric") { |
837 | 6x |
plot_call <- reduce_plot_call(plot_call, substitute(aes(x = yval), env = list(yval = y))) |
838 | ||
839 | 6x |
if (freq) { |
840 | 4x |
plot_call <- reduce_plot_call( |
841 | 4x |
plot_call, |
842 | 4x |
quote(geom_histogram(bins = 30)), |
843 | 4x |
quote(ylab("Frequency")) |
844 |
) |
|
845 |
} else { |
|
846 | 2x |
plot_call <- reduce_plot_call( |
847 | 2x |
plot_call, |
848 | 2x |
quote(geom_histogram(bins = 30, aes(y = after_stat(density)))), |
849 | 2x |
quote(geom_density(aes(y = after_stat(density)))), |
850 | 2x |
quote(ylab("Density")) |
851 |
) |
|
852 |
} |
|
853 | 30x |
} else if (x_class == "factor" && y_class == "NULL") { |
854 | 4x |
plot_call <- reduce_plot_call(plot_call, substitute(aes(x = xval), env = list(xval = x))) |
855 | ||
856 | 4x |
if (freq) { |
857 | 2x |
plot_call <- reduce_plot_call( |
858 | 2x |
plot_call, |
859 | 2x |
quote(geom_bar()), |
860 | 2x |
quote(ylab("Frequency")) |
861 |
) |
|
862 |
} else { |
|
863 | 2x |
plot_call <- reduce_plot_call( |
864 | 2x |
plot_call, |
865 | 2x |
quote(geom_bar(aes(y = after_stat(prop), group = 1))), |
866 | 2x |
quote(ylab("Fraction")) |
867 |
) |
|
868 |
} |
|
869 | 26x |
} else if (x_class == "NULL" && y_class == "factor") { |
870 | 4x |
plot_call <- reduce_plot_call(plot_call, substitute(aes(x = yval), env = list(yval = y))) |
871 | ||
872 | 4x |
if (freq) { |
873 | 2x |
plot_call <- reduce_plot_call( |
874 | 2x |
plot_call, |
875 | 2x |
quote(geom_bar()), |
876 | 2x |
quote(ylab("Frequency")) |
877 |
) |
|
878 |
} else { |
|
879 | 2x |
plot_call <- reduce_plot_call( |
880 | 2x |
plot_call, |
881 | 2x |
quote(geom_bar(aes(y = after_stat(prop), group = 1))), |
882 | 2x |
quote(ylab("Fraction")) |
883 |
) |
|
884 |
} |
|
885 |
# Numeric Plots |
|
886 | 22x |
} else if (x_class == "numeric" && y_class == "numeric") { |
887 | 2x |
plot_call <- reduce_plot_call( |
888 | 2x |
plot_call, |
889 | 2x |
substitute(aes(x = xval, y = yval), env = list(xval = x, yval = y)), |
890 |
# pch = 21 for consistent coloring behaviour b/w all geoms (outline and fill properties) |
|
891 | 2x |
`if`( |
892 | 2x |
!is.null(size), |
893 | 2x |
substitute( |
894 | 2x |
geom_point(alpha = alphaval, size = sizeval, pch = 21), |
895 | 2x |
env = list(alphaval = alpha, sizeval = size) |
896 |
), |
|
897 | 2x |
substitute( |
898 | 2x |
geom_point(alpha = alphaval, pch = 21), |
899 | 2x |
env = list(alphaval = alpha) |
900 |
) |
|
901 |
) |
|
902 |
) |
|
903 | 20x |
} else if ((x_class == "numeric" && y_class == "factor") || (x_class == "factor" && y_class == "numeric")) { |
904 | 6x |
plot_call <- reduce_plot_call( |
905 | 6x |
plot_call, |
906 | 6x |
substitute(aes(x = xval, y = yval), env = list(xval = x, yval = y)), |
907 | 6x |
quote(geom_boxplot()) |
908 |
) |
|
909 |
# Factor and character plots |
|
910 | 14x |
} else if (x_class == "factor" && y_class == "factor") { |
911 | 14x |
plot_call <- reduce_plot_call( |
912 | 14x |
plot_call, |
913 | 14x |
substitute( |
914 | 14x |
ggmosaic::geom_mosaic(aes(x = ggmosaic::product(xval), fill = yval), na.rm = TRUE), |
915 | 14x |
env = list(xval = x, yval = y) |
916 |
) |
|
917 |
) |
|
918 |
} else { |
|
919 | ! |
stop("x y type combination not allowed") |
920 |
} |
|
921 | ||
922 | 42x |
labs_base <- if (x_class == "NULL") { |
923 | 10x |
list(x = substitute(ylab, list(ylab = ylab))) |
924 | 42x |
} else if (y_class == "NULL") { |
925 | 10x |
list(x = substitute(xlab, list(xlab = xlab))) |
926 |
} else { |
|
927 | 22x |
list( |
928 | 22x |
x = substitute(xlab, list(xlab = xlab)), |
929 | 22x |
y = substitute(ylab, list(ylab = ylab)) |
930 |
) |
|
931 |
} |
|
932 | ||
933 | 42x |
dev_ggplot2_args <- teal.widgets::ggplot2_args(labs = labs_base) |
934 | ||
935 | 42x |
if (rotate_xaxis_labels) { |
936 | ! |
dev_ggplot2_args$theme <- list(axis.text.x = quote(element_text(angle = 45, hjust = 1))) |
937 |
} |
|
938 | ||
939 | 42x |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
940 | 42x |
user_plot = ggplot2_args, |
941 | 42x |
module_plot = dev_ggplot2_args |
942 |
) |
|
943 | ||
944 | 42x |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args(all_ggplot2_args, ggtheme = theme) |
945 | ||
946 | 42x |
plot_call <- reduce_plot_call( |
947 | 42x |
plot_call, |
948 | 42x |
parsed_ggplot2_args$labs, |
949 | 42x |
parsed_ggplot2_args$ggtheme, |
950 | 42x |
parsed_ggplot2_args$theme |
951 |
) |
|
952 | ||
953 | 42x |
if (swap_axes) { |
954 | ! |
plot_call <- reduce_plot_call(plot_call, quote(coord_flip())) |
955 |
} |
|
956 | ||
957 | 42x |
plot_call |
958 |
} |
|
959 | ||
960 |
# Create facet call |
|
961 |
facet_ggplot_call <- function(row_facet = character(0), |
|
962 |
col_facet = character(0), |
|
963 |
free_x_scales = FALSE, |
|
964 |
free_y_scales = FALSE) { |
|
965 | ! |
scales <- if (free_x_scales && free_y_scales) { |
966 | ! |
"free" |
967 | ! |
} else if (free_x_scales) { |
968 | ! |
"free_x" |
969 | ! |
} else if (free_y_scales) { |
970 | ! |
"free_y" |
971 |
} else { |
|
972 | ! |
"fixed" |
973 |
} |
|
974 | ||
975 | ! |
if (identical(row_facet, character(0)) && identical(col_facet, character(0))) { |
976 | ! |
NULL |
977 | ! |
} else if (!identical(row_facet, character(0)) && !identical(col_facet, character(0))) { |
978 | ! |
call( |
979 | ! |
"facet_grid", |
980 | ! |
rows = call_fun_dots("vars", row_facet), |
981 | ! |
cols = call_fun_dots("vars", col_facet), |
982 | ! |
scales = scales |
983 |
) |
|
984 | ! |
} else if (identical(row_facet, character(0)) && !identical(col_facet, character(0))) { |
985 | ! |
call("facet_grid", cols = call_fun_dots("vars", col_facet), scales = scales) |
986 | ! |
} else if (!identical(row_facet, character(0)) && identical(col_facet, character(0))) { |
987 | ! |
call("facet_grid", rows = call_fun_dots("vars", row_facet), scales = scales) |
988 |
} |
|
989 |
} |
|
990 | ||
991 |
coloring_ggplot_call <- function(colour, |
|
992 |
fill, |
|
993 |
size, |
|
994 |
is_point = FALSE) { |
|
995 |
if ( |
|
996 | 15x |
!identical(colour, character(0)) && |
997 | 15x |
!identical(fill, character(0)) && |
998 | 15x |
is_point && |
999 | 15x |
!identical(size, character(0)) |
1000 |
) { |
|
1001 | 1x |
substitute( |
1002 | 1x |
expr = aes(colour = colour_name, fill = fill_name, size = size_name), |
1003 | 1x |
env = list(colour_name = as.name(colour), fill_name = as.name(fill), size_name = as.name(size)) |
1004 |
) |
|
1005 |
} else if ( |
|
1006 | 14x |
identical(colour, character(0)) && |
1007 | 14x |
!identical(fill, character(0)) && |
1008 | 14x |
is_point && |
1009 | 14x |
identical(size, character(0)) |
1010 |
) { |
|
1011 | 1x |
substitute(expr = aes(fill = fill_name), env = list(fill_name = as.name(fill))) |
1012 |
} else if ( |
|
1013 | 13x |
!identical(colour, character(0)) && |
1014 | 13x |
!identical(fill, character(0)) && |
1015 | 13x |
(!is_point || identical(size, character(0))) |
1016 |
) { |
|
1017 | 3x |
substitute( |
1018 | 3x |
expr = aes(colour = colour_name, fill = fill_name), |
1019 | 3x |
env = list(colour_name = as.name(colour), fill_name = as.name(fill)) |
1020 |
) |
|
1021 |
} else if ( |
|
1022 | 10x |
!identical(colour, character(0)) && |
1023 | 10x |
identical(fill, character(0)) && |
1024 | 10x |
(!is_point || identical(size, character(0))) |
1025 |
) { |
|
1026 | 1x |
substitute(expr = aes(colour = colour_name), env = list(colour_name = as.name(colour))) |
1027 |
} else if ( |
|
1028 | 9x |
identical(colour, character(0)) && |
1029 | 9x |
!identical(fill, character(0)) && |
1030 | 9x |
(!is_point || identical(size, character(0))) |
1031 |
) { |
|
1032 | 2x |
substitute(expr = aes(fill = fill_name), env = list(fill_name = as.name(fill))) |
1033 |
} else if ( |
|
1034 | 7x |
identical(colour, character(0)) && |
1035 | 7x |
identical(fill, character(0)) && |
1036 | 7x |
is_point && |
1037 | 7x |
!identical(size, character(0)) |
1038 |
) { |
|
1039 | 1x |
substitute(expr = aes(size = size_name), env = list(size_name = as.name(size))) |
1040 |
} else if ( |
|
1041 | 6x |
!identical(colour, character(0)) && |
1042 | 6x |
identical(fill, character(0)) && |
1043 | 6x |
is_point && |
1044 | 6x |
!identical(size, character(0)) |
1045 |
) { |
|
1046 | 1x |
substitute( |
1047 | 1x |
expr = aes(colour = colour_name, size = size_name), |
1048 | 1x |
env = list(colour_name = as.name(colour), size_name = as.name(size)) |
1049 |
) |
|
1050 |
} else if ( |
|
1051 | 5x |
identical(colour, character(0)) && |
1052 | 5x |
!identical(fill, character(0)) && |
1053 | 5x |
is_point && |
1054 | 5x |
!identical(size, character(0)) |
1055 |
) { |
|
1056 | 1x |
substitute( |
1057 | 1x |
expr = aes(colour = colour_name, fill = fill_name, size = size_name), |
1058 | 1x |
env = list(colour_name = as.name(fill), fill_name = as.name(fill), size_name = as.name(size)) |
1059 |
) |
|
1060 |
} else { |
|
1061 | 4x |
NULL |
1062 |
} |
|
1063 |
} |
1 |
#' `teal` module: Variable browser |
|
2 |
#' |
|
3 |
#' Module provides provides a detailed summary and visualization of variable distributions |
|
4 |
#' for `data.frame` objects, with interactive features to customize analysis. |
|
5 |
#' |
|
6 |
#' Numeric columns with fewer than 30 distinct values can be treated as either discrete |
|
7 |
#' or continuous with a checkbox allowing users to switch how they are treated(if < 6 unique values |
|
8 |
#' then the default is discrete, otherwise it is continuous). |
|
9 |
#' |
|
10 |
#' @inheritParams teal::module |
|
11 |
#' @inheritParams shared_params |
|
12 |
#' @param parent_dataname (`character(1)`) string specifying a parent dataset. |
|
13 |
#' If it exists in `datasets_selected`then an extra checkbox will be shown to |
|
14 |
#' allow users to not show variables in other datasets which exist in this `dataname`. |
|
15 |
#' This is typically used to remove `ADSL` columns in `CDISC` data. |
|
16 |
#' In non `CDISC` data this can be ignored. Defaults to `"ADSL"`. |
|
17 |
#' @param datasets_selected (`character`) vector of datasets which should be |
|
18 |
#' shown, in order. Names must correspond with datasets names. |
|
19 |
#' If vector of length zero (default) then all datasets are shown. |
|
20 |
#' Note: Only `data.frame` objects are compatible; using other types will cause an error. |
|
21 |
#' |
|
22 |
#' @inherit shared_params return |
|
23 |
#' |
|
24 |
#' @examplesShinylive |
|
25 |
#' library(teal.modules.general) |
|
26 |
#' interactive <- function() TRUE |
|
27 |
#' {{ next_example }} |
|
28 |
# nolint start: line_length_linter. |
|
29 |
#' @examplesIf require("sparkline", quietly = TRUE) && require("htmlwidgets", quietly = TRUE) && require("jsonlite", quietly = TRUE) |
|
30 |
# nolint end: line_length_linter. |
|
31 |
#' # general data example |
|
32 |
#' data <- teal_data() |
|
33 |
#' data <- within(data, { |
|
34 |
#' iris <- iris |
|
35 |
#' mtcars <- mtcars |
|
36 |
#' women <- women |
|
37 |
#' faithful <- faithful |
|
38 |
#' CO2 <- CO2 |
|
39 |
#' }) |
|
40 |
#' |
|
41 |
#' app <- init( |
|
42 |
#' data = data, |
|
43 |
#' modules = modules( |
|
44 |
#' tm_variable_browser( |
|
45 |
#' label = "Variable browser" |
|
46 |
#' ) |
|
47 |
#' ) |
|
48 |
#' ) |
|
49 |
#' if (interactive()) { |
|
50 |
#' shinyApp(app$ui, app$server) |
|
51 |
#' } |
|
52 |
#' |
|
53 |
#' @examplesShinylive |
|
54 |
#' library(teal.modules.general) |
|
55 |
#' interactive <- function() TRUE |
|
56 |
#' {{ next_example }} |
|
57 |
# nolint start: line_length_linter. |
|
58 |
#' @examplesIf require("sparkline", quietly = TRUE) && require("htmlwidgets", quietly = TRUE) && require("jsonlite", quietly = TRUE) |
|
59 |
# nolint end: line_length_linter. |
|
60 |
#' # CDISC example data |
|
61 |
#' library(sparkline) |
|
62 |
#' data <- teal_data() |
|
63 |
#' data <- within(data, { |
|
64 |
#' ADSL <- rADSL |
|
65 |
#' ADTTE <- rADTTE |
|
66 |
#' }) |
|
67 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
68 |
#' |
|
69 |
#' app <- init( |
|
70 |
#' data = data, |
|
71 |
#' modules = modules( |
|
72 |
#' tm_variable_browser( |
|
73 |
#' label = "Variable browser" |
|
74 |
#' ) |
|
75 |
#' ) |
|
76 |
#' ) |
|
77 |
#' if (interactive()) { |
|
78 |
#' shinyApp(app$ui, app$server) |
|
79 |
#' } |
|
80 |
#' |
|
81 |
#' @export |
|
82 |
#' |
|
83 |
tm_variable_browser <- function(label = "Variable Browser", |
|
84 |
datasets_selected = character(0), |
|
85 |
parent_dataname = "ADSL", |
|
86 |
pre_output = NULL, |
|
87 |
post_output = NULL, |
|
88 |
ggplot2_args = teal.widgets::ggplot2_args()) { |
|
89 | ! |
message("Initializing tm_variable_browser") |
90 | ||
91 |
# Requires Suggested packages |
|
92 | ! |
if (!requireNamespace("sparkline", quietly = TRUE)) { |
93 | ! |
stop("Cannot load sparkline - please install the package or restart your session.") |
94 |
} |
|
95 | ! |
if (!requireNamespace("htmlwidgets", quietly = TRUE)) { |
96 | ! |
stop("Cannot load htmlwidgets - please install the package or restart your session.") |
97 |
} |
|
98 | ! |
if (!requireNamespace("jsonlite", quietly = TRUE)) { |
99 | ! |
stop("Cannot load jsonlite - please install the package or restart your session.") |
100 |
} |
|
101 | ||
102 |
# Start of assertions |
|
103 | ! |
checkmate::assert_string(label) |
104 | ! |
checkmate::assert_character(datasets_selected) |
105 | ! |
checkmate::assert_character(parent_dataname, min.len = 0, max.len = 1) |
106 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
107 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
108 | ! |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
109 |
# End of assertions |
|
110 | ||
111 | ! |
datasets_selected <- unique(datasets_selected) |
112 | ||
113 | ! |
ans <- module( |
114 | ! |
label, |
115 | ! |
server = srv_variable_browser, |
116 | ! |
ui = ui_variable_browser, |
117 | ! |
datanames = "all", |
118 | ! |
server_args = list( |
119 | ! |
datasets_selected = datasets_selected, |
120 | ! |
parent_dataname = parent_dataname, |
121 | ! |
ggplot2_args = ggplot2_args |
122 |
), |
|
123 | ! |
ui_args = list( |
124 | ! |
pre_output = pre_output, |
125 | ! |
post_output = post_output |
126 |
) |
|
127 |
) |
|
128 |
# `shiny` inputs are stored properly but the majority of the module is state of `datatable` which is not stored. |
|
129 | ! |
attr(ans, "teal_bookmarkable") <- NULL |
130 | ! |
ans |
131 |
} |
|
132 | ||
133 |
# UI function for the variable browser module |
|
134 |
ui_variable_browser <- function(id, |
|
135 |
pre_output = NULL, |
|
136 |
post_output = NULL) { |
|
137 | ! |
ns <- NS(id) |
138 | ||
139 | ! |
tagList( |
140 | ! |
include_css_files("custom"), |
141 | ! |
shinyjs::useShinyjs(), |
142 | ! |
teal.widgets::standard_layout( |
143 | ! |
output = fluidRow( |
144 | ! |
htmlwidgets::getDependency("sparkline"), # needed for sparklines to work |
145 | ! |
column( |
146 | ! |
6, |
147 |
# variable browser |
|
148 | ! |
teal.widgets::white_small_well( |
149 | ! |
uiOutput(ns("ui_variable_browser")), |
150 | ! |
shinyjs::hidden({ |
151 | ! |
checkboxInput(ns("show_parent_vars"), "Show parent dataset variables", value = FALSE) |
152 |
}) |
|
153 |
) |
|
154 |
), |
|
155 | ! |
column( |
156 | ! |
6, |
157 | ! |
teal.widgets::white_small_well( |
158 |
### Reporter |
|
159 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
160 |
### |
|
161 | ! |
tags$div( |
162 | ! |
class = "block", |
163 | ! |
uiOutput(ns("ui_histogram_display")) |
164 |
), |
|
165 | ! |
tags$div( |
166 | ! |
class = "block", |
167 | ! |
uiOutput(ns("ui_numeric_display")) |
168 |
), |
|
169 | ! |
teal.widgets::plot_with_settings_ui(ns("variable_plot")), |
170 | ! |
tags$br(), |
171 |
# input user-defined text size |
|
172 | ! |
teal.widgets::panel_item( |
173 | ! |
title = "Plot settings", |
174 | ! |
collapsed = TRUE, |
175 | ! |
selectInput( |
176 | ! |
inputId = ns("ggplot_theme"), label = "ggplot2 theme", |
177 | ! |
choices = ggplot_themes, |
178 | ! |
selected = "grey" |
179 |
), |
|
180 | ! |
fluidRow( |
181 | ! |
column(6, sliderInput( |
182 | ! |
inputId = ns("font_size"), label = "font size", |
183 | ! |
min = 5L, max = 30L, value = 15L, step = 1L, ticks = FALSE |
184 |
)), |
|
185 | ! |
column(6, sliderInput( |
186 | ! |
inputId = ns("label_rotation"), label = "rotate x labels", |
187 | ! |
min = 0L, max = 90L, value = 45L, step = 1, ticks = FALSE |
188 |
)) |
|
189 |
) |
|
190 |
), |
|
191 | ! |
tags$br(), |
192 | ! |
teal.widgets::get_dt_rows(ns("variable_summary_table"), ns("variable_summary_table_rows")), |
193 | ! |
DT::dataTableOutput(ns("variable_summary_table")) |
194 |
) |
|
195 |
) |
|
196 |
), |
|
197 | ! |
pre_output = pre_output, |
198 | ! |
post_output = post_output |
199 |
) |
|
200 |
) |
|
201 |
} |
|
202 | ||
203 |
# Server function for the variable browser module |
|
204 |
srv_variable_browser <- function(id, |
|
205 |
data, |
|
206 |
reporter, |
|
207 |
filter_panel_api, |
|
208 |
datasets_selected, parent_dataname, ggplot2_args) { |
|
209 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
210 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
211 | ! |
checkmate::assert_class(data, "reactive") |
212 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
213 | ! |
moduleServer(id, function(input, output, session) { |
214 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
215 | ||
216 |
# if there are < this number of unique records then a numeric |
|
217 |
# variable can be treated as a factor and all factors with < this groups |
|
218 |
# have their values plotted |
|
219 | ! |
.unique_records_for_factor <- 30 |
220 |
# if there are < this number of unique records then a numeric |
|
221 |
# variable is by default treated as a factor |
|
222 | ! |
.unique_records_default_as_factor <- 6 # nolint: object_length. |
223 | ||
224 | ! |
varname_numeric_as_factor <- reactiveValues() |
225 | ||
226 | ! |
datanames <- isolate(names(data())) |
227 | ! |
datanames <- Filter(function(name) { |
228 | ! |
is.data.frame(isolate(data())[[name]]) |
229 | ! |
}, datanames) |
230 | ||
231 | ! |
checkmate::assert_character(datasets_selected) |
232 | ! |
checkmate::assert_subset(datasets_selected, datanames) |
233 | ! |
if (!identical(datasets_selected, character(0))) { |
234 | ! |
checkmate::assert_subset(datasets_selected, datanames) |
235 | ! |
datanames <- datasets_selected |
236 |
} |
|
237 | ||
238 | ! |
output$ui_variable_browser <- renderUI({ |
239 | ! |
ns <- session$ns |
240 | ! |
do.call( |
241 | ! |
tabsetPanel, |
242 | ! |
c( |
243 | ! |
id = ns("tabset_panel"), |
244 | ! |
do.call( |
245 | ! |
tagList, |
246 | ! |
lapply(datanames, function(dataname) { |
247 | ! |
tabPanel( |
248 | ! |
dataname, |
249 | ! |
tags$div( |
250 | ! |
class = "mt-4", |
251 | ! |
textOutput(ns(paste0("dataset_summary_", dataname))) |
252 |
), |
|
253 | ! |
tags$div( |
254 | ! |
class = "mt-4", |
255 | ! |
teal.widgets::get_dt_rows( |
256 | ! |
ns(paste0("variable_browser_", dataname)), |
257 | ! |
ns(paste0("variable_browser_", dataname, "_rows")) |
258 |
), |
|
259 | ! |
DT::dataTableOutput(ns(paste0("variable_browser_", dataname)), width = "100%") |
260 |
) |
|
261 |
) |
|
262 |
}) |
|
263 |
) |
|
264 |
) |
|
265 |
) |
|
266 |
}) |
|
267 | ||
268 |
# conditionally display checkbox |
|
269 | ! |
shinyjs::toggle( |
270 | ! |
id = "show_parent_vars", |
271 | ! |
condition = length(parent_dataname) > 0 && parent_dataname %in% datanames |
272 |
) |
|
273 | ||
274 | ! |
columns_names <- new.env() |
275 | ||
276 |
# plot_var$data holds the name of the currently selected dataset |
|
277 |
# plot_var$variable[[<dataset_name>]] holds the name of the currently selected |
|
278 |
# variable for dataset <dataset_name> |
|
279 | ! |
plot_var <- reactiveValues(data = NULL, variable = list()) |
280 | ||
281 | ! |
establish_updating_selection(datanames, input, plot_var, columns_names) |
282 | ||
283 |
# validations |
|
284 | ! |
validation_checks <- validate_input(input, plot_var, data) |
285 | ||
286 |
# data_for_analysis is a list with two elements: a column from a dataset and the column label |
|
287 | ! |
plotted_data <- reactive({ |
288 | ! |
validation_checks() |
289 | ||
290 | ! |
get_plotted_data(input, plot_var, data) |
291 |
}) |
|
292 | ||
293 | ! |
treat_numeric_as_factor <- reactive({ |
294 | ! |
if (is_num_var_short(.unique_records_for_factor, input, plotted_data)) { |
295 | ! |
input$numeric_as_factor |
296 |
} else { |
|
297 | ! |
FALSE |
298 |
} |
|
299 |
}) |
|
300 | ||
301 | ! |
render_tabset_panel_content( |
302 | ! |
input = input, |
303 | ! |
output = output, |
304 | ! |
data = data, |
305 | ! |
datanames = datanames, |
306 | ! |
parent_dataname = parent_dataname, |
307 | ! |
columns_names = columns_names, |
308 | ! |
plot_var = plot_var |
309 |
) |
|
310 |
# add used-defined text size to ggplot arguments passed from caller frame |
|
311 | ! |
all_ggplot2_args <- reactive({ |
312 | ! |
user_text <- teal.widgets::ggplot2_args( |
313 | ! |
theme = list( |
314 | ! |
"text" = ggplot2::element_text(size = input[["font_size"]]), |
315 | ! |
"axis.text.x" = ggplot2::element_text(angle = input[["label_rotation"]], hjust = 1) |
316 |
) |
|
317 |
) |
|
318 | ! |
user_theme <- utils::getFromNamespace(sprintf("theme_%s", input[["ggplot_theme"]]), ns = "ggplot2") |
319 | ! |
user_theme <- user_theme() |
320 |
# temporary fix to circumvent assertion issue with resolve_ggplot2_args |
|
321 |
# drop problematic elements |
|
322 | ! |
user_theme <- user_theme[grep("strip.text.y.left", names(user_theme), fixed = TRUE, invert = TRUE)] |
323 | ||
324 | ! |
teal.widgets::resolve_ggplot2_args( |
325 | ! |
user_plot = user_text, |
326 | ! |
user_default = teal.widgets::ggplot2_args(theme = user_theme), |
327 | ! |
module_plot = ggplot2_args |
328 |
) |
|
329 |
}) |
|
330 | ||
331 | ! |
output$ui_numeric_display <- renderUI({ |
332 | ! |
validation_checks() |
333 | ! |
dataname <- input$tabset_panel |
334 | ! |
varname <- plot_var$variable[[dataname]] |
335 | ! |
df <- data()[[dataname]] |
336 | ||
337 | ! |
numeric_ui <- tagList( |
338 | ! |
fluidRow( |
339 | ! |
tags$div( |
340 | ! |
class = "col-md-4", |
341 | ! |
tags$br(), |
342 | ! |
shinyWidgets::switchInput( |
343 | ! |
inputId = session$ns("display_density"), |
344 | ! |
label = "Show density", |
345 | ! |
value = `if`(is.null(isolate(input$display_density)), TRUE, isolate(input$display_density)), |
346 | ! |
width = "50%", |
347 | ! |
labelWidth = "100px", |
348 | ! |
handleWidth = "50px" |
349 |
) |
|
350 |
), |
|
351 | ! |
tags$div( |
352 | ! |
class = "col-md-4", |
353 | ! |
tags$br(), |
354 | ! |
shinyWidgets::switchInput( |
355 | ! |
inputId = session$ns("remove_outliers"), |
356 | ! |
label = "Remove outliers", |
357 | ! |
value = `if`(is.null(isolate(input$remove_outliers)), FALSE, isolate(input$remove_outliers)), |
358 | ! |
width = "50%", |
359 | ! |
labelWidth = "100px", |
360 | ! |
handleWidth = "50px" |
361 |
) |
|
362 |
), |
|
363 | ! |
tags$div( |
364 | ! |
class = "col-md-4", |
365 | ! |
uiOutput(session$ns("outlier_definition_slider_ui")) |
366 |
) |
|
367 |
), |
|
368 | ! |
tags$div( |
369 | ! |
class = "ml-4", |
370 | ! |
uiOutput(session$ns("ui_density_help")), |
371 | ! |
uiOutput(session$ns("ui_outlier_help")) |
372 |
) |
|
373 |
) |
|
374 | ||
375 | ! |
observeEvent(input$numeric_as_factor, ignoreInit = TRUE, { |
376 | ! |
varname_numeric_as_factor[[plot_var$variable[[dataname]]]] <- input$numeric_as_factor |
377 |
}) |
|
378 | ||
379 | ! |
if (is.numeric(df[[varname]])) { |
380 | ! |
unique_entries <- length(unique(df[[varname]])) |
381 | ! |
if (unique_entries < .unique_records_for_factor && unique_entries > 0) { |
382 | ! |
list( |
383 | ! |
checkboxInput( |
384 | ! |
session$ns("numeric_as_factor"), |
385 | ! |
"Treat variable as factor", |
386 | ! |
value = `if`( |
387 | ! |
is.null(varname_numeric_as_factor[[varname]]), |
388 | ! |
unique_entries < .unique_records_default_as_factor, |
389 | ! |
varname_numeric_as_factor[[varname]] |
390 |
) |
|
391 |
), |
|
392 | ! |
conditionalPanel("!input.numeric_as_factor", ns = session$ns, numeric_ui) |
393 |
) |
|
394 | ! |
} else if (unique_entries > 0) { |
395 | ! |
numeric_ui |
396 |
} |
|
397 |
} else { |
|
398 | ! |
NULL |
399 |
} |
|
400 |
}) |
|
401 | ||
402 | ! |
output$ui_histogram_display <- renderUI({ |
403 | ! |
validation_checks() |
404 | ! |
dataname <- input$tabset_panel |
405 | ! |
varname <- plot_var$variable[[dataname]] |
406 | ! |
df <- data()[[dataname]] |
407 | ||
408 | ! |
numeric_ui <- tagList(fluidRow( |
409 | ! |
tags$div( |
410 | ! |
class = "col-md-4", |
411 | ! |
shinyWidgets::switchInput( |
412 | ! |
inputId = session$ns("remove_NA_hist"), |
413 | ! |
label = "Remove NA values", |
414 | ! |
value = FALSE, |
415 | ! |
width = "50%", |
416 | ! |
labelWidth = "100px", |
417 | ! |
handleWidth = "50px" |
418 |
) |
|
419 |
) |
|
420 |
)) |
|
421 | ||
422 | ! |
var <- df[[varname]] |
423 | ! |
if (anyNA(var) && (is.factor(var) || is.character(var) || is.logical(var))) { |
424 | ! |
groups <- unique(as.character(var)) |
425 | ! |
len_groups <- length(groups) |
426 | ! |
if (len_groups >= .unique_records_for_factor) { |
427 | ! |
NULL |
428 |
} else { |
|
429 | ! |
numeric_ui |
430 |
} |
|
431 |
} else { |
|
432 | ! |
NULL |
433 |
} |
|
434 |
}) |
|
435 | ||
436 | ! |
output$outlier_definition_slider_ui <- renderUI({ |
437 | ! |
req(input$remove_outliers) |
438 | ! |
sliderInput( |
439 | ! |
inputId = session$ns("outlier_definition_slider"), |
440 | ! |
tags$div( |
441 | ! |
class = "teal-tooltip", |
442 | ! |
tagList( |
443 | ! |
"Outlier definition:", |
444 | ! |
icon("circle-info"), |
445 | ! |
tags$span( |
446 | ! |
class = "tooltiptext", |
447 | ! |
paste( |
448 | ! |
"Use the slider to choose the cut-off value to define outliers; the larger the value the", |
449 | ! |
"further below Q1/above Q3 points have to be in order to be classed as outliers" |
450 |
) |
|
451 |
) |
|
452 |
) |
|
453 |
), |
|
454 | ! |
min = 1, |
455 | ! |
max = 5, |
456 | ! |
value = 3, |
457 | ! |
step = 0.5 |
458 |
) |
|
459 |
}) |
|
460 | ||
461 | ! |
output$ui_density_help <- renderUI({ |
462 | ! |
req(is.logical(input$display_density)) |
463 | ! |
if (input$display_density) { |
464 | ! |
tags$small(helpText(paste( |
465 | ! |
"Kernel density estimation with gaussian kernel", |
466 | ! |
"and bandwidth function bw.nrd0 (R default)" |
467 |
))) |
|
468 |
} else { |
|
469 | ! |
NULL |
470 |
} |
|
471 |
}) |
|
472 | ||
473 | ! |
output$ui_outlier_help <- renderUI({ |
474 | ! |
req(is.logical(input$remove_outliers), input$outlier_definition_slider) |
475 | ! |
if (input$remove_outliers) { |
476 | ! |
tags$small( |
477 | ! |
helpText( |
478 | ! |
withMathJax(paste0( |
479 | ! |
"Outlier data points (\\( X \\lt Q1 - ", input$outlier_definition_slider, "\\times IQR \\) or |
480 | ! |
\\(Q3 + ", input$outlier_definition_slider, "\\times IQR \\lt X\\)) |
481 | ! |
have not been displayed on the graph and will not be used for any kernel density estimations, ", |
482 | ! |
"although their values remain in the statisics table below." |
483 |
)) |
|
484 |
) |
|
485 |
) |
|
486 |
} else { |
|
487 | ! |
NULL |
488 |
} |
|
489 |
}) |
|
490 | ||
491 | ||
492 | ! |
variable_plot_r <- reactive({ |
493 | ! |
display_density <- `if`(is.null(input$display_density), FALSE, input$display_density) |
494 | ! |
remove_outliers <- `if`(is.null(input$remove_outliers), FALSE, input$remove_outliers) |
495 | ||
496 | ! |
if (remove_outliers) { |
497 | ! |
req(input$outlier_definition_slider) |
498 | ! |
outlier_definition <- as.numeric(input$outlier_definition_slider) |
499 |
} else { |
|
500 | ! |
outlier_definition <- 0 |
501 |
} |
|
502 | ||
503 | ! |
plot_var_summary( |
504 | ! |
var = plotted_data()$data, |
505 | ! |
var_lab = plotted_data()$var_description, |
506 | ! |
wrap_character = 15, |
507 | ! |
numeric_as_factor = treat_numeric_as_factor(), |
508 | ! |
remove_NA_hist = input$remove_NA_hist, |
509 | ! |
display_density = display_density, |
510 | ! |
outlier_definition = outlier_definition, |
511 | ! |
records_for_factor = .unique_records_for_factor, |
512 | ! |
ggplot2_args = all_ggplot2_args() |
513 |
) |
|
514 |
}) |
|
515 | ||
516 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
517 | ! |
id = "variable_plot", |
518 | ! |
plot_r = variable_plot_r, |
519 | ! |
height = c(500, 200, 2000) |
520 |
) |
|
521 | ||
522 | ! |
output$variable_summary_table <- DT::renderDataTable({ |
523 | ! |
var_summary_table( |
524 | ! |
plotted_data()$data, |
525 | ! |
treat_numeric_as_factor(), |
526 | ! |
input$variable_summary_table_rows, |
527 | ! |
if (!is.null(input$remove_outliers) && input$remove_outliers) { |
528 | ! |
req(input$outlier_definition_slider) |
529 | ! |
as.numeric(input$outlier_definition_slider) |
530 |
} else { |
|
531 | ! |
0 |
532 |
} |
|
533 |
) |
|
534 |
}) |
|
535 | ||
536 |
### REPORTER |
|
537 | ! |
if (with_reporter) { |
538 | ! |
card_fun <- function(comment) { |
539 | ! |
card <- teal::TealReportCard$new() |
540 | ! |
card$set_name("Variable Browser Plot") |
541 | ! |
card$append_text("Variable Browser Plot", "header2") |
542 | ! |
if (with_filter) card$append_fs(filter_panel_api$get_filter_state()) |
543 | ! |
card$append_text("Plot", "header3") |
544 | ! |
card$append_plot(variable_plot_r(), dim = pws$dim()) |
545 | ! |
if (!comment == "") { |
546 | ! |
card$append_text("Comment", "header3") |
547 | ! |
card$append_text(comment) |
548 |
} |
|
549 | ! |
card |
550 |
} |
|
551 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
552 |
} |
|
553 |
### |
|
554 |
}) |
|
555 |
} |
|
556 | ||
557 |
#' Summarize NAs. |
|
558 |
#' |
|
559 |
#' Summarizes occurrence of missing values in vector. |
|
560 |
#' @param x vector of any type and length |
|
561 |
#' @return Character string describing `NA` occurrence. |
|
562 |
#' @keywords internal |
|
563 |
var_missings_info <- function(x) { |
|
564 | ! |
sprintf("%s [%s%%]", sum(is.na(x)), round(mean(is.na(x) * 100), 2)) |
565 |
} |
|
566 | ||
567 |
#' Summarizes variable |
|
568 |
#' |
|
569 |
#' Creates html summary with statistics relevant to data type. For numeric values it returns central |
|
570 |
#' tendency measures, for factor returns level counts, for Date date range, for other just |
|
571 |
#' number of levels. |
|
572 |
#' |
|
573 |
#' @param x vector of any type |
|
574 |
#' @param numeric_as_factor `logical` should the numeric variable be treated as a factor |
|
575 |
#' @param dt_rows `numeric` current/latest `DT` page length |
|
576 |
#' @param outlier_definition If 0 no outliers are removed, otherwise |
|
577 |
#' outliers (those more than `outlier_definition*IQR below/above Q1/Q3` be removed) |
|
578 |
#' @return text with simple statistics. |
|
579 |
#' @keywords internal |
|
580 |
var_summary_table <- function(x, numeric_as_factor, dt_rows, outlier_definition) { |
|
581 | ! |
if (is.null(dt_rows)) { |
582 | ! |
dt_rows <- 10 |
583 |
} |
|
584 | ! |
if (is.numeric(x) && !numeric_as_factor) { |
585 | ! |
req(!any(is.infinite(x))) |
586 | ||
587 | ! |
x <- remove_outliers_from(x, outlier_definition) |
588 | ||
589 | ! |
qvals <- round(stats::quantile(x, na.rm = TRUE, probs = c(0.25, 0.5, 0.75), type = 2), 2) |
590 |
# classical central tendency measures |
|
591 | ||
592 | ! |
summary <- |
593 | ! |
data.frame( |
594 | ! |
Statistic = c("min", "Q1", "median", "mean", "Q3", "max", "sd", "n"), |
595 | ! |
Value = c( |
596 | ! |
round(min(x, na.rm = TRUE), 2), |
597 | ! |
qvals[1], |
598 | ! |
qvals[2], |
599 | ! |
round(mean(x, na.rm = TRUE), 2), |
600 | ! |
qvals[3], |
601 | ! |
round(max(x, na.rm = TRUE), 2), |
602 | ! |
round(stats::sd(x, na.rm = TRUE), 2), |
603 | ! |
length(x[!is.na(x)]) |
604 |
) |
|
605 |
) |
|
606 | ||
607 | ! |
DT::datatable(summary, rownames = FALSE, options = list(dom = "<t>", pageLength = dt_rows)) |
608 | ! |
} else if (is.factor(x) || is.character(x) || (is.numeric(x) && numeric_as_factor) || is.logical(x)) { |
609 |
# make sure factor is ordered numeric |
|
610 | ! |
if (is.numeric(x)) { |
611 | ! |
x <- factor(x, levels = sort(unique(x))) |
612 |
} |
|
613 | ||
614 | ! |
level_counts <- table(x) |
615 | ! |
max_levels_signif <- nchar(level_counts) |
616 | ||
617 | ! |
if (!all(is.na(x))) { |
618 | ! |
levels <- names(level_counts) |
619 | ! |
counts <- sprintf( |
620 | ! |
"%s [%.2f%%]", |
621 | ! |
format(level_counts, width = max_levels_signif), prop.table(level_counts) * 100 |
622 |
) |
|
623 |
} else { |
|
624 | ! |
levels <- character(0) |
625 | ! |
counts <- numeric(0) |
626 |
} |
|
627 | ||
628 | ! |
summary <- data.frame( |
629 | ! |
Level = levels, |
630 | ! |
Count = counts, |
631 | ! |
stringsAsFactors = FALSE |
632 |
) |
|
633 | ||
634 |
# sort the dataset in decreasing order of counts (needed as character variables default to alphabetical) |
|
635 | ! |
summary <- summary[order(summary$Count, decreasing = TRUE), ] |
636 | ||
637 | ! |
dom_opts <- if (nrow(summary) <= 10) { |
638 | ! |
"<t>" |
639 |
} else { |
|
640 | ! |
"<lf<t>ip>" |
641 |
} |
|
642 | ! |
DT::datatable(summary, rownames = FALSE, options = list(dom = dom_opts, pageLength = dt_rows)) |
643 | ! |
} else if (inherits(x, "Date") || inherits(x, "POSIXct") || inherits(x, "POSIXlt")) { |
644 | ! |
summary <- |
645 | ! |
data.frame( |
646 | ! |
Statistic = c("min", "median", "max"), |
647 | ! |
Value = c( |
648 | ! |
min(x, na.rm = TRUE), |
649 | ! |
stats::median(x, na.rm = TRUE), |
650 | ! |
max(x, na.rm = TRUE) |
651 |
) |
|
652 |
) |
|
653 | ! |
DT::datatable(summary, rownames = FALSE, options = list(dom = "<t>", pageLength = dt_rows)) |
654 |
} else { |
|
655 | ! |
NULL |
656 |
} |
|
657 |
} |
|
658 | ||
659 |
#' Plot variable |
|
660 |
#' |
|
661 |
#' Creates summary plot with statistics relevant to data type. |
|
662 |
#' |
|
663 |
#' @inheritParams shared_params |
|
664 |
#' @param var vector of any type to be plotted. For numeric variables it produces histogram with |
|
665 |
#' density line, for factors it creates frequency plot |
|
666 |
#' @param var_lab text describing selected variable to be displayed on the plot |
|
667 |
#' @param wrap_character (`numeric`) number of characters at which to wrap text values of `var` |
|
668 |
#' @param numeric_as_factor (`logical`) should the numeric variable be treated as a factor |
|
669 |
#' @param display_density (`logical`) should density estimation be displayed for numeric values |
|
670 |
#' @param remove_NA_hist (`logical`) should `NA` values be removed for histogram of factor like variables |
|
671 |
#' @param outlier_definition if 0 no outliers are removed, otherwise |
|
672 |
#' outliers (those more than outlier_definition*IQR below/above Q1/Q3 be removed) |
|
673 |
#' @param records_for_factor (`numeric`) if the number of factor levels is >= than this value then |
|
674 |
#' a graph of the factors isn't shown, only a list of values |
|
675 |
#' |
|
676 |
#' @return plot |
|
677 |
#' @keywords internal |
|
678 |
plot_var_summary <- function(var, |
|
679 |
var_lab, |
|
680 |
wrap_character = NULL, |
|
681 |
numeric_as_factor, |
|
682 |
display_density = is.numeric(var), |
|
683 |
remove_NA_hist = FALSE, # nolint: object_name. |
|
684 |
outlier_definition, |
|
685 |
records_for_factor, |
|
686 |
ggplot2_args) { |
|
687 | ! |
checkmate::assert_character(var_lab) |
688 | ! |
checkmate::assert_numeric(wrap_character, null.ok = TRUE) |
689 | ! |
checkmate::assert_flag(numeric_as_factor) |
690 | ! |
checkmate::assert_flag(display_density) |
691 | ! |
checkmate::assert_logical(remove_NA_hist, null.ok = TRUE) |
692 | ! |
checkmate::assert_number(outlier_definition, lower = 0, finite = TRUE) |
693 | ! |
checkmate::assert_integerish(records_for_factor, lower = 0, len = 1, any.missing = FALSE) |
694 | ! |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
695 | ||
696 | ! |
grid::grid.newpage() |
697 | ||
698 | ! |
plot_main <- if (is.factor(var) || is.character(var) || is.logical(var)) { |
699 | ! |
groups <- unique(as.character(var)) |
700 | ! |
len_groups <- length(groups) |
701 | ! |
if (len_groups >= records_for_factor) { |
702 | ! |
grid::textGrob( |
703 | ! |
sprintf( |
704 | ! |
"%s unique values\n%s:\n %s\n ...\n %s", |
705 | ! |
len_groups, |
706 | ! |
var_lab, |
707 | ! |
paste(utils::head(groups), collapse = ",\n "), |
708 | ! |
paste(utils::tail(groups), collapse = ",\n ") |
709 |
), |
|
710 | ! |
x = grid::unit(1, "line"), |
711 | ! |
y = grid::unit(1, "npc") - grid::unit(1, "line"), |
712 | ! |
just = c("left", "top") |
713 |
) |
|
714 |
} else { |
|
715 | ! |
if (!is.null(wrap_character)) { |
716 | ! |
var <- stringr::str_wrap(var, width = wrap_character) |
717 |
} |
|
718 | ! |
var <- if (isTRUE(remove_NA_hist)) as.vector(stats::na.omit(var)) else var |
719 | ! |
ggplot(data.frame(var), aes(x = forcats::fct_infreq(as.factor(var)))) + |
720 | ! |
geom_bar( |
721 | ! |
stat = "count", aes(fill = ifelse(is.na(var), "withcolor", "")), show.legend = FALSE |
722 |
) + |
|
723 | ! |
scale_fill_manual(values = c("gray50", "tan")) |
724 |
} |
|
725 | ! |
} else if (is.numeric(var)) { |
726 | ! |
validate(need(any(!is.na(var)), "No data left to visualize.")) |
727 | ||
728 |
# Filter out NA |
|
729 | ! |
var <- var[which(!is.na(var))] |
730 | ||
731 | ! |
validate(need(!any(is.infinite(var)), "Cannot display graph when data includes infinite values")) |
732 | ||
733 | ! |
if (numeric_as_factor) { |
734 | ! |
var <- factor(var) |
735 | ! |
ggplot(NULL, aes(x = var)) + |
736 | ! |
geom_histogram(stat = "count") |
737 |
} else { |
|
738 |
# remove outliers |
|
739 | ! |
if (outlier_definition != 0) { |
740 | ! |
number_records <- length(var) |
741 | ! |
var <- remove_outliers_from(var, outlier_definition) |
742 | ! |
number_outliers <- number_records - length(var) |
743 | ! |
outlier_text <- paste0( |
744 | ! |
number_outliers, " outliers (", |
745 | ! |
round(number_outliers / number_records * 100, 2), |
746 | ! |
"% of non-missing records) not shown" |
747 |
) |
|
748 | ! |
validate(need( |
749 | ! |
length(var) > 1, |
750 | ! |
"At least two data points must remain after removing outliers for this graph to be displayed" |
751 |
)) |
|
752 |
} |
|
753 |
## histogram |
|
754 | ! |
binwidth <- get_bin_width(var) |
755 | ! |
p <- ggplot(data = data.frame(var = var), aes(x = var, y = after_stat(count))) + |
756 | ! |
geom_histogram(binwidth = binwidth) + |
757 | ! |
scale_y_continuous( |
758 | ! |
sec.axis = sec_axis( |
759 | ! |
trans = ~ . / nrow(data.frame(var = var)), |
760 | ! |
labels = scales::percent, |
761 | ! |
name = "proportion (in %)" |
762 |
) |
|
763 |
) |
|
764 | ||
765 | ! |
if (display_density) { |
766 | ! |
p <- p + geom_density(aes(y = after_stat(count * binwidth))) |
767 |
} |
|
768 | ||
769 | ! |
if (outlier_definition != 0) { |
770 | ! |
p <- p + annotate( |
771 | ! |
geom = "text", |
772 | ! |
label = outlier_text, |
773 | ! |
x = Inf, y = Inf, |
774 | ! |
hjust = 1.02, vjust = 1.2, |
775 | ! |
color = "black", |
776 |
# explicitly modify geom text size according |
|
777 | ! |
size = ggplot2_args[["theme"]][["text"]][["size"]] / 3.5 |
778 |
) |
|
779 |
} |
|
780 | ! |
p |
781 |
} |
|
782 | ! |
} else if (inherits(var, "Date") || inherits(var, "POSIXct") || inherits(var, "POSIXlt")) { |
783 | ! |
var_num <- as.numeric(var) |
784 | ! |
binwidth <- get_bin_width(var_num, 1) |
785 | ! |
p <- ggplot(data = data.frame(var = var), aes(x = var, y = after_stat(count))) + |
786 | ! |
geom_histogram(binwidth = binwidth) |
787 |
} else { |
|
788 | ! |
grid::textGrob( |
789 | ! |
paste(strwrap( |
790 | ! |
utils::capture.output(utils::str(var)), |
791 | ! |
width = .9 * grid::convertWidth(grid::unit(1, "npc"), "char", TRUE) |
792 | ! |
), collapse = "\n"), |
793 | ! |
x = grid::unit(1, "line"), y = grid::unit(1, "npc") - grid::unit(1, "line"), just = c("left", "top") |
794 |
) |
|
795 |
} |
|
796 | ||
797 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
798 | ! |
labs = list(x = var_lab) |
799 |
) |
|
800 |
### |
|
801 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
802 | ! |
ggplot2_args, |
803 | ! |
module_plot = dev_ggplot2_args |
804 |
) |
|
805 | ||
806 | ! |
if (is.ggplot(plot_main)) { |
807 | ! |
if (is.numeric(var) && !numeric_as_factor) { |
808 |
# numeric not as factor |
|
809 | ! |
plot_main <- plot_main + |
810 | ! |
theme_light() + |
811 | ! |
list( |
812 | ! |
labs = do.call("labs", all_ggplot2_args$labs), |
813 | ! |
theme = do.call("theme", all_ggplot2_args$theme) |
814 |
) |
|
815 |
} else { |
|
816 |
# factor low number of levels OR numeric as factor OR Date |
|
817 | ! |
plot_main <- plot_main + |
818 | ! |
theme_light() + |
819 | ! |
list( |
820 | ! |
labs = do.call("labs", all_ggplot2_args$labs), |
821 | ! |
theme = do.call("theme", all_ggplot2_args$theme) |
822 |
) |
|
823 |
} |
|
824 | ! |
plot_main <- ggplotGrob(plot_main) |
825 |
} |
|
826 | ||
827 | ! |
grid::grid.draw(plot_main) |
828 | ! |
plot_main |
829 |
} |
|
830 | ||
831 |
is_num_var_short <- function(.unique_records_for_factor, input, data_for_analysis) { |
|
832 | ! |
length(unique(data_for_analysis()$data)) < .unique_records_for_factor && !is.null(input$numeric_as_factor) |
833 |
} |
|
834 | ||
835 |
#' Validates the variable browser inputs |
|
836 |
#' |
|
837 |
#' @param input (`session$input`) the `shiny` session input |
|
838 |
#' @param plot_var (`list`) list of a data frame and an array of variable names |
|
839 |
#' @param data (`teal_data`) the datasets passed to the module |
|
840 |
#' |
|
841 |
#' @returns `logical` TRUE if validations pass; a `shiny` validation error otherwise |
|
842 |
#' @keywords internal |
|
843 |
validate_input <- function(input, plot_var, data) { |
|
844 | ! |
reactive({ |
845 | ! |
dataset_name <- req(input$tabset_panel) |
846 | ! |
varname <- plot_var$variable[[dataset_name]] |
847 | ||
848 | ! |
validate(need(dataset_name, "No data selected")) |
849 | ! |
validate(need(varname, "No variable selected")) |
850 | ! |
df <- data()[[dataset_name]] |
851 | ! |
teal::validate_has_data(df, 1) |
852 | ! |
teal::validate_has_variable(varname = varname, data = df, "Variable not available") |
853 | ||
854 | ! |
TRUE |
855 |
}) |
|
856 |
} |
|
857 | ||
858 |
get_plotted_data <- function(input, plot_var, data) { |
|
859 | ! |
dataset_name <- input$tabset_panel |
860 | ! |
varname <- plot_var$variable[[dataset_name]] |
861 | ! |
df <- data()[[dataset_name]] |
862 | ||
863 | ! |
var_description <- teal.data::col_labels(df)[[varname]] |
864 | ! |
list(data = df[[varname]], var_description = var_description) |
865 |
} |
|
866 | ||
867 |
#' Renders the left-hand side `tabset` panel of the module |
|
868 |
#' |
|
869 |
#' @param datanames (`character`) the name of the dataset |
|
870 |
#' @param parent_dataname (`character`) the name of a parent `dataname` to filter out variables from |
|
871 |
#' @param data (`teal_data`) the object containing all datasets |
|
872 |
#' @param input (`session$input`) the `shiny` session input |
|
873 |
#' @param output (`session$output`) the `shiny` session output |
|
874 |
#' @param columns_names (`environment`) the environment containing bindings for each dataset |
|
875 |
#' @param plot_var (`list`) the list containing the currently selected dataset (tab) and its column names |
|
876 |
#' @keywords internal |
|
877 |
render_tabset_panel_content <- function(datanames, parent_dataname, output, data, input, columns_names, plot_var) { |
|
878 | ! |
lapply(datanames, render_single_tab, |
879 | ! |
input = input, |
880 | ! |
output = output, |
881 | ! |
data = data, |
882 | ! |
parent_dataname = parent_dataname, |
883 | ! |
columns_names = columns_names, |
884 | ! |
plot_var = plot_var |
885 |
) |
|
886 |
} |
|
887 | ||
888 |
#' Renders a single tab in the left-hand side tabset panel |
|
889 |
#' |
|
890 |
#' Renders a single tab in the left-hand side tabset panel. The rendered tab contains |
|
891 |
#' information about one dataset out of many presented in the module. |
|
892 |
#' |
|
893 |
#' @param dataset_name (`character`) the name of the dataset contained in the rendered tab |
|
894 |
#' @param parent_dataname (`character`) the name of a parent `dataname` to filter out variables from |
|
895 |
#' @inheritParams render_tabset_panel_content |
|
896 |
#' @keywords internal |
|
897 |
render_single_tab <- function(dataset_name, parent_dataname, output, data, input, columns_names, plot_var) { |
|
898 | ! |
render_tab_header(dataset_name, output, data) |
899 | ||
900 | ! |
render_tab_table( |
901 | ! |
dataset_name = dataset_name, |
902 | ! |
parent_dataname = parent_dataname, |
903 | ! |
output = output, |
904 | ! |
data = data, |
905 | ! |
input = input, |
906 | ! |
columns_names = columns_names, |
907 | ! |
plot_var = plot_var |
908 |
) |
|
909 |
} |
|
910 | ||
911 |
#' Renders the text headlining a single tab in the left-hand side tabset panel |
|
912 |
#' |
|
913 |
#' @param dataset_name (`character`) the name of the dataset of the tab |
|
914 |
#' @inheritParams render_tabset_panel_content |
|
915 |
#' @keywords internal |
|
916 |
render_tab_header <- function(dataset_name, output, data) { |
|
917 | ! |
dataset_ui_id <- paste0("dataset_summary_", dataset_name) |
918 | ! |
output[[dataset_ui_id]] <- renderText({ |
919 | ! |
df <- data()[[dataset_name]] |
920 | ! |
join_keys <- teal.data::join_keys(data()) |
921 | ! |
if (!is.null(join_keys)) { |
922 | ! |
key <- teal.data::join_keys(data())[dataset_name, dataset_name] |
923 |
} else { |
|
924 | ! |
key <- NULL |
925 |
} |
|
926 | ! |
sprintf( |
927 | ! |
"Dataset with %s unique key rows and %s variables", |
928 | ! |
nrow(unique(`if`(length(key) > 0, df[, key, drop = FALSE], df))), |
929 | ! |
ncol(df) |
930 |
) |
|
931 |
}) |
|
932 |
} |
|
933 | ||
934 |
#' Renders the table for a single dataset in the left-hand side tabset panel |
|
935 |
#' |
|
936 |
#' The table contains column names, column labels, |
|
937 |
#' small summary about NA values and `sparkline` (if appropriate). |
|
938 |
#' |
|
939 |
#' @param dataset_name (`character`) the name of the dataset |
|
940 |
#' @param parent_dataname (`character`) the name of a parent `dataname` to filter out variables from |
|
941 |
#' @inheritParams render_tabset_panel_content |
|
942 |
#' @keywords internal |
|
943 |
render_tab_table <- function(dataset_name, parent_dataname, output, data, input, columns_names, plot_var) { |
|
944 | ! |
table_ui_id <- paste0("variable_browser_", dataset_name) |
945 | ||
946 | ! |
output[[table_ui_id]] <- DT::renderDataTable({ |
947 | ! |
df <- data()[[dataset_name]] |
948 | ||
949 | ! |
get_vars_df <- function(input, dataset_name, parent_name, data) { |
950 | ! |
data_cols <- colnames(df) |
951 | ! |
if (isTRUE(input$show_parent_vars)) { |
952 | ! |
data_cols |
953 | ! |
} else if (dataset_name != parent_name && parent_name %in% names(data)) { |
954 | ! |
setdiff(data_cols, colnames(data()[[parent_name]])) |
955 |
} else { |
|
956 | ! |
data_cols |
957 |
} |
|
958 |
} |
|
959 | ||
960 | ! |
if (length(parent_dataname) > 0) { |
961 | ! |
df_vars <- get_vars_df(input, dataset_name, parent_dataname, data) |
962 | ! |
df <- df[df_vars] |
963 |
} |
|
964 | ||
965 | ! |
if (is.null(df) || ncol(df) == 0) { |
966 | ! |
columns_names[[dataset_name]] <- character(0) |
967 | ! |
df_output <- data.frame( |
968 | ! |
Type = character(0), |
969 | ! |
Variable = character(0), |
970 | ! |
Label = character(0), |
971 | ! |
Missings = character(0), |
972 | ! |
Sparklines = character(0), |
973 | ! |
stringsAsFactors = FALSE |
974 |
) |
|
975 |
} else { |
|
976 |
# extract data variable labels |
|
977 | ! |
labels <- teal.data::col_labels(df) |
978 | ||
979 | ! |
columns_names[[dataset_name]] <- names(labels) |
980 | ||
981 |
# calculate number of missing values |
|
982 | ! |
missings <- vapply( |
983 | ! |
df, |
984 | ! |
var_missings_info, |
985 | ! |
FUN.VALUE = character(1), |
986 | ! |
USE.NAMES = FALSE |
987 |
) |
|
988 | ||
989 |
# get icons proper for the data types |
|
990 | ! |
icons <- vapply(df, function(x) class(x)[1L], character(1L)) |
991 | ||
992 | ! |
join_keys <- teal.data::join_keys(data()) |
993 | ! |
if (!is.null(join_keys)) { |
994 | ! |
icons[intersect(join_keys[dataset_name, dataset_name], colnames(df))] <- "primary_key" |
995 |
} |
|
996 | ! |
icons <- variable_type_icons(icons) |
997 | ||
998 |
# generate sparklines |
|
999 | ! |
sparklines_html <- vapply( |
1000 | ! |
df, |
1001 | ! |
create_sparklines, |
1002 | ! |
FUN.VALUE = character(1), |
1003 | ! |
USE.NAMES = FALSE |
1004 |
) |
|
1005 | ||
1006 | ! |
df_output <- data.frame( |
1007 | ! |
Type = icons, |
1008 | ! |
Variable = names(labels), |
1009 | ! |
Label = labels, |
1010 | ! |
Missings = missings, |
1011 | ! |
Sparklines = sparklines_html, |
1012 | ! |
stringsAsFactors = FALSE |
1013 |
) |
|
1014 |
} |
|
1015 | ||
1016 |
# Select row 1 as default / fallback |
|
1017 | ! |
selected_ix <- 1 |
1018 |
# Define starting page index (base-0 index of the first item on page |
|
1019 |
# note: in many cases it's not the item itself |
|
1020 | ! |
selected_page_ix <- 0 |
1021 | ||
1022 |
# Retrieve current selected variable if any |
|
1023 | ! |
isolated_variable <- isolate(plot_var$variable[[dataset_name]]) |
1024 | ||
1025 | ! |
if (!is.null(isolated_variable)) { |
1026 | ! |
index <- which(columns_names[[dataset_name]] == isolated_variable)[1] |
1027 | ! |
if (!is.null(index) && !is.na(index) && length(index) > 0) selected_ix <- index |
1028 |
} |
|
1029 | ||
1030 |
# Retrieve the index of the first item of the current page |
|
1031 |
# it works with varying number of entries on the page (10, 25, ...) |
|
1032 | ! |
table_id_sel <- paste0("variable_browser_", dataset_name, "_state") |
1033 | ! |
dt_state <- isolate(input[[table_id_sel]]) |
1034 | ! |
if (selected_ix != 1 && !is.null(dt_state)) { |
1035 | ! |
selected_page_ix <- floor(selected_ix / dt_state$length) * dt_state$length |
1036 |
} |
|
1037 | ||
1038 | ! |
DT::datatable( |
1039 | ! |
df_output, |
1040 | ! |
escape = FALSE, |
1041 | ! |
rownames = FALSE, |
1042 | ! |
selection = list(mode = "single", target = "row", selected = selected_ix), |
1043 | ! |
options = list( |
1044 | ! |
fnDrawCallback = htmlwidgets::JS("function() { HTMLWidgets.staticRender(); }"), |
1045 | ! |
pageLength = input[[paste0(table_ui_id, "_rows")]], |
1046 | ! |
displayStart = selected_page_ix |
1047 |
) |
|
1048 |
) |
|
1049 |
}) |
|
1050 |
} |
|
1051 | ||
1052 |
#' Creates observers updating the currently selected column |
|
1053 |
#' |
|
1054 |
#' The created observers update the column currently selected in the left-hand side |
|
1055 |
#' tabset panel. |
|
1056 |
#' |
|
1057 |
#' @note |
|
1058 |
#' Creates an observer for each dataset (each tab in the tabset panel). |
|
1059 |
#' |
|
1060 |
#' @inheritParams render_tabset_panel_content |
|
1061 |
#' @keywords internal |
|
1062 |
establish_updating_selection <- function(datanames, input, plot_var, columns_names) { |
|
1063 | ! |
lapply(datanames, function(dataset_name) { |
1064 | ! |
table_ui_id <- paste0("variable_browser_", dataset_name) |
1065 | ! |
table_id_sel <- paste0(table_ui_id, "_rows_selected") |
1066 | ! |
observeEvent(input[[table_id_sel]], { |
1067 | ! |
plot_var$data <- dataset_name |
1068 | ! |
plot_var$variable[[dataset_name]] <- columns_names[[dataset_name]][input[[table_id_sel]]] |
1069 |
}) |
|
1070 |
}) |
|
1071 |
} |
|
1072 | ||
1073 |
get_bin_width <- function(x_vec, scaling_factor = 2) { |
|
1074 | ! |
x_vec <- x_vec[!is.na(x_vec)] |
1075 | ! |
qntls <- stats::quantile(x_vec, probs = c(0.1, 0.25, 0.75, 0.9), type = 2) |
1076 | ! |
iqr <- qntls[3] - qntls[2] |
1077 | ! |
binwidth <- max(scaling_factor * iqr / length(x_vec) ^ (1 / 3), sqrt(qntls[4] - qntls[1])) # styler: off |
1078 | ! |
binwidth <- ifelse(binwidth == 0, 1, binwidth) |
1079 |
# to ensure at least two bins when variable span is very small |
|
1080 | ! |
x_span <- diff(range(x_vec)) |
1081 | ! |
if (isTRUE(x_span / binwidth >= 2)) binwidth else x_span / 2 |
1082 |
} |
|
1083 | ||
1084 |
#' Removes the outlier observation from an array |
|
1085 |
#' |
|
1086 |
#' @param var (`numeric`) a numeric vector |
|
1087 |
#' @param outlier_definition (`numeric`) if `0` then no outliers are removed, otherwise |
|
1088 |
#' outliers (those more than `outlier_definition*IQR below/above Q1/Q3`) are removed |
|
1089 |
#' @returns (`numeric`) vector without the outlier values |
|
1090 |
#' @keywords internal |
|
1091 |
remove_outliers_from <- function(var, outlier_definition) { |
|
1092 | 3x |
if (outlier_definition == 0) { |
1093 | 1x |
return(var) |
1094 |
} |
|
1095 | 2x |
q1_q3 <- stats::quantile(var, probs = c(0.25, 0.75), type = 2, na.rm = TRUE) |
1096 | 2x |
iqr <- q1_q3[2] - q1_q3[1] |
1097 | 2x |
var[var >= q1_q3[1] - outlier_definition * iqr & var <= q1_q3[2] + outlier_definition * iqr] |
1098 |
} |
|
1099 | ||
1100 | ||
1101 |
# sparklines ---- |
|
1102 | ||
1103 |
#' S3 generic for `sparkline` widget HTML |
|
1104 |
#' |
|
1105 |
#' Generates the `sparkline` HTML code corresponding to the input array. |
|
1106 |
#' For numeric variables creates a box plot, for character and factors - bar plot. |
|
1107 |
#' Produces an empty string for variables of other types. |
|
1108 |
#' |
|
1109 |
#' @param arr vector of any type and length |
|
1110 |
#' @param width `numeric` the width of the `sparkline` widget (pixels) |
|
1111 |
#' @param bar_spacing `numeric` the spacing between the bars (in pixels) |
|
1112 |
#' @param bar_width `numeric` the width of the bars (in pixels) |
|
1113 |
#' @param ... `list` additional options passed to bar plots of `jquery.sparkline`; |
|
1114 |
#' see [`jquery.sparkline docs`](https://omnipotent.net/jquery.sparkline/#common) |
|
1115 |
#' |
|
1116 |
#' @return Character string containing HTML code of the `sparkline` HTML widget. |
|
1117 |
#' @keywords internal |
|
1118 |
create_sparklines <- function(arr, width = 150, ...) { |
|
1119 | ! |
if (all(is.null(arr))) { |
1120 | ! |
return("") |
1121 |
} |
|
1122 | ! |
UseMethod("create_sparklines") |
1123 |
} |
|
1124 | ||
1125 |
#' @rdname create_sparklines |
|
1126 |
#' @keywords internal |
|
1127 |
#' @export |
|
1128 |
create_sparklines.logical <- function(arr, ...) { |
|
1129 | ! |
create_sparklines(as.factor(arr)) |
1130 |
} |
|
1131 | ||
1132 |
#' @rdname create_sparklines |
|
1133 |
#' @keywords internal |
|
1134 |
#' @export |
|
1135 |
create_sparklines.numeric <- function(arr, width = 150, ...) { |
|
1136 | ! |
if (any(is.infinite(arr))) { |
1137 | ! |
return(as.character(tags$code("infinite values", class = "text-blue"))) |
1138 |
} |
|
1139 | ! |
if (length(arr) > 100000) { |
1140 | ! |
return(as.character(tags$code("Too many rows (>100000)", class = "text-blue"))) |
1141 |
} |
|
1142 | ||
1143 | ! |
arr <- arr[!is.na(arr)] |
1144 | ! |
sparkline::spk_chr(unname(arr), type = "box", width = width, ...) |
1145 |
} |
|
1146 | ||
1147 |
#' @rdname create_sparklines |
|
1148 |
#' @keywords internal |
|
1149 |
#' @export |
|
1150 |
create_sparklines.character <- function(arr, ...) { |
|
1151 | ! |
return(create_sparklines(as.factor(arr))) |
1152 |
} |
|
1153 | ||
1154 | ||
1155 |
#' @rdname create_sparklines |
|
1156 |
#' @keywords internal |
|
1157 |
#' @export |
|
1158 |
create_sparklines.factor <- function(arr, width = 150, bar_spacing = 5, bar_width = 20, ...) { |
|
1159 | ! |
decreasing_order <- TRUE |
1160 | ||
1161 | ! |
counts <- table(arr) |
1162 | ! |
if (length(counts) >= 100) { |
1163 | ! |
return(as.character(tags$code("> 99 levels", class = "text-blue"))) |
1164 | ! |
} else if (length(counts) == 0) { |
1165 | ! |
return(as.character(tags$code("no levels", class = "text-blue"))) |
1166 | ! |
} else if (length(counts) == 1) { |
1167 | ! |
return(as.character(tags$code("one level", class = "text-blue"))) |
1168 |
} |
|
1169 | ||
1170 |
# Summarize the occurences of different levels |
|
1171 |
# and get the maximum and minimum number of occurences |
|
1172 |
# This is needed for the sparkline to correctly display the bar plots |
|
1173 |
# Otherwise they are cropped |
|
1174 | ! |
counts <- sort(counts, decreasing = decreasing_order, method = "radix") |
1175 | ! |
max_value <- if (decreasing_order) counts[1] else counts[length[counts]] |
1176 | ! |
max_value <- unname(max_value) |
1177 | ||
1178 | ! |
sparkline::spk_chr( |
1179 | ! |
unname(counts), |
1180 | ! |
type = "bar", |
1181 | ! |
chartRangeMin = 0, |
1182 | ! |
chartRangeMax = max_value, |
1183 | ! |
width = width, |
1184 | ! |
barWidth = bar_width, |
1185 | ! |
barSpacing = bar_spacing, |
1186 | ! |
tooltipFormatter = custom_sparkline_formatter(names(counts), as.vector(counts)) |
1187 |
) |
|
1188 |
} |
|
1189 | ||
1190 |
#' @rdname create_sparklines |
|
1191 |
#' @keywords internal |
|
1192 |
#' @export |
|
1193 |
create_sparklines.Date <- function(arr, width = 150, bar_spacing = 5, bar_width = 20, ...) { |
|
1194 | ! |
arr_num <- as.numeric(arr) |
1195 | ! |
arr_num <- sort(arr_num, decreasing = FALSE, method = "radix") |
1196 | ! |
binwidth <- get_bin_width(arr_num, 1) |
1197 | ! |
bins <- floor(diff(range(arr_num)) / binwidth) + 1 |
1198 | ! |
if (all(is.na(bins))) { |
1199 | ! |
return(as.character(tags$code("only NA", class = "text-blue"))) |
1200 | ! |
} else if (bins == 1) { |
1201 | ! |
return(as.character(tags$code("one date", class = "text-blue"))) |
1202 |
} |
|
1203 | ! |
counts <- as.vector(unname(base::table(cut(arr_num, breaks = bins)))) |
1204 | ! |
max_value <- max(counts) |
1205 | ||
1206 | ! |
start_bins <- as.integer(seq(1, length(arr_num), length.out = bins)) |
1207 | ! |
labels_start <- as.character(as.Date(arr_num[start_bins], origin = as.Date("1970-01-01"))) |
1208 | ! |
labels <- paste("Start:", labels_start) |
1209 | ||
1210 | ! |
sparkline::spk_chr( |
1211 | ! |
unname(counts), |
1212 | ! |
type = "bar", |
1213 | ! |
chartRangeMin = 0, |
1214 | ! |
chartRangeMax = max_value, |
1215 | ! |
width = width, |
1216 | ! |
barWidth = bar_width, |
1217 | ! |
barSpacing = bar_spacing, |
1218 | ! |
tooltipFormatter = custom_sparkline_formatter(labels, counts) |
1219 |
) |
|
1220 |
} |
|
1221 | ||
1222 |
#' @rdname create_sparklines |
|
1223 |
#' @keywords internal |
|
1224 |
#' @export |
|
1225 |
create_sparklines.POSIXct <- function(arr, width = 150, bar_spacing = 5, bar_width = 20, ...) { |
|
1226 | ! |
arr_num <- as.numeric(arr) |
1227 | ! |
arr_num <- sort(arr_num, decreasing = FALSE, method = "radix") |
1228 | ! |
binwidth <- get_bin_width(arr_num, 1) |
1229 | ! |
bins <- floor(diff(range(arr_num)) / binwidth) + 1 |
1230 | ! |
if (all(is.na(bins))) { |
1231 | ! |
return(as.character(tags$code("only NA", class = "text-blue"))) |
1232 | ! |
} else if (bins == 1) { |
1233 | ! |
return(as.character(tags$code("one date-time", class = "text-blue"))) |
1234 |
} |
|
1235 | ! |
counts <- as.vector(unname(base::table(cut(arr_num, breaks = bins)))) |
1236 | ! |
max_value <- max(counts) |
1237 | ||
1238 | ! |
start_bins <- as.integer(seq(1, length(arr_num), length.out = bins)) |
1239 | ! |
labels_start <- as.character(format(as.POSIXct(arr_num[start_bins], origin = as.Date("1970-01-01")), "%Y-%m-%d")) |
1240 | ! |
labels <- paste("Start:", labels_start) |
1241 | ||
1242 | ! |
sparkline::spk_chr( |
1243 | ! |
unname(counts), |
1244 | ! |
type = "bar", |
1245 | ! |
chartRangeMin = 0, |
1246 | ! |
chartRangeMax = max_value, |
1247 | ! |
width = width, |
1248 | ! |
barWidth = bar_width, |
1249 | ! |
barSpacing = bar_spacing, |
1250 | ! |
tooltipFormatter = custom_sparkline_formatter(labels, counts) |
1251 |
) |
|
1252 |
} |
|
1253 | ||
1254 |
#' @rdname create_sparklines |
|
1255 |
#' @keywords internal |
|
1256 |
#' @export |
|
1257 |
create_sparklines.POSIXlt <- function(arr, width = 150, bar_spacing = 5, bar_width = 20, ...) { |
|
1258 | ! |
arr_num <- as.numeric(arr) |
1259 | ! |
arr_num <- sort(arr_num, decreasing = FALSE, method = "radix") |
1260 | ! |
binwidth <- get_bin_width(arr_num, 1) |
1261 | ! |
bins <- floor(diff(range(arr_num)) / binwidth) + 1 |
1262 | ! |
if (all(is.na(bins))) { |
1263 | ! |
return(as.character(tags$code("only NA", class = "text-blue"))) |
1264 | ! |
} else if (bins == 1) { |
1265 | ! |
return(as.character(tags$code("one date-time", class = "text-blue"))) |
1266 |
} |
|
1267 | ! |
counts <- as.vector(unname(base::table(cut(arr_num, breaks = bins)))) |
1268 | ! |
max_value <- max(counts) |
1269 | ||
1270 | ! |
start_bins <- as.integer(seq(1, length(arr_num), length.out = bins)) |
1271 | ! |
labels_start <- as.character(format(as.POSIXct(arr_num[start_bins], origin = as.Date("1970-01-01")), "%Y-%m-%d")) |
1272 | ! |
labels <- paste("Start:", labels_start) |
1273 | ||
1274 | ! |
sparkline::spk_chr( |
1275 | ! |
unname(counts), |
1276 | ! |
type = "bar", |
1277 | ! |
chartRangeMin = 0, |
1278 | ! |
chartRangeMax = max_value, |
1279 | ! |
width = width, |
1280 | ! |
barWidth = bar_width, |
1281 | ! |
barSpacing = bar_spacing, |
1282 | ! |
tooltipFormatter = custom_sparkline_formatter(labels, counts) |
1283 |
) |
|
1284 |
} |
|
1285 | ||
1286 |
#' @rdname create_sparklines |
|
1287 |
#' @keywords internal |
|
1288 |
#' @export |
|
1289 |
create_sparklines.default <- function(arr, width = 150, ...) { |
|
1290 | ! |
as.character(tags$code("unsupported variable type", class = "text-blue")) |
1291 |
} |
|
1292 | ||
1293 | ||
1294 |
custom_sparkline_formatter <- function(labels, counts) { |
|
1295 | ! |
htmlwidgets::JS( |
1296 | ! |
sprintf( |
1297 | ! |
"function(sparkline, options, field) { |
1298 | ! |
return 'ID: ' + %s[field[0].offset] + '<br>' + 'Count: ' + %s[field[0].offset]; |
1299 |
}", |
|
1300 | ! |
jsonlite::toJSON(labels), |
1301 | ! |
jsonlite::toJSON(counts) |
1302 |
) |
|
1303 |
) |
|
1304 |
} |
1 |
#' `teal` module: 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 |
#' |
|
15 |
#' @templateVar ggnames "Boxplot","Density Plot","Cumulative Distribution Plot" |
|
16 |
#' @template ggplot2_args_multi |
|
17 |
#' |
|
18 |
#' @inherit shared_params return |
|
19 |
#' |
|
20 |
#' @examplesShinylive |
|
21 |
#' library(teal.modules.general) |
|
22 |
#' interactive <- function() TRUE |
|
23 |
#' {{ next_example }} |
|
24 |
#' @examples |
|
25 |
#' # general data example |
|
26 |
#' data <- teal_data() |
|
27 |
#' data <- within(data, { |
|
28 |
#' CO2 <- CO2 |
|
29 |
#' CO2[["primary_key"]] <- seq_len(nrow(CO2)) |
|
30 |
#' }) |
|
31 |
#' join_keys(data) <- join_keys(join_key("CO2", "CO2", "primary_key")) |
|
32 |
#' |
|
33 |
#' vars <- choices_selected(variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment"))) |
|
34 |
#' |
|
35 |
#' app <- init( |
|
36 |
#' data = data, |
|
37 |
#' modules = modules( |
|
38 |
#' tm_outliers( |
|
39 |
#' outlier_var = list( |
|
40 |
#' data_extract_spec( |
|
41 |
#' dataname = "CO2", |
|
42 |
#' select = select_spec( |
|
43 |
#' label = "Select variable:", |
|
44 |
#' choices = variable_choices(data[["CO2"]], c("conc", "uptake")), |
|
45 |
#' selected = "uptake", |
|
46 |
#' multiple = FALSE, |
|
47 |
#' fixed = FALSE |
|
48 |
#' ) |
|
49 |
#' ) |
|
50 |
#' ), |
|
51 |
#' categorical_var = list( |
|
52 |
#' data_extract_spec( |
|
53 |
#' dataname = "CO2", |
|
54 |
#' filter = filter_spec( |
|
55 |
#' vars = vars, |
|
56 |
#' choices = value_choices(data[["CO2"]], vars$selected), |
|
57 |
#' selected = value_choices(data[["CO2"]], vars$selected), |
|
58 |
#' multiple = TRUE |
|
59 |
#' ) |
|
60 |
#' ) |
|
61 |
#' ) |
|
62 |
#' ) |
|
63 |
#' ) |
|
64 |
#' ) |
|
65 |
#' if (interactive()) { |
|
66 |
#' shinyApp(app$ui, app$server) |
|
67 |
#' } |
|
68 |
#' |
|
69 |
#' @examplesShinylive |
|
70 |
#' library(teal.modules.general) |
|
71 |
#' interactive <- function() TRUE |
|
72 |
#' {{ next_example }} |
|
73 |
#' @examples |
|
74 |
#' # CDISC data example |
|
75 |
#' data <- teal_data() |
|
76 |
#' data <- within(data, { |
|
77 |
#' ADSL <- rADSL |
|
78 |
#' }) |
|
79 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
80 |
#' |
|
81 |
#' fact_vars_adsl <- names(Filter(isTRUE, sapply(data[["ADSL"]], is.factor))) |
|
82 |
#' vars <- choices_selected(variable_choices(data[["ADSL"]], fact_vars_adsl)) |
|
83 |
#' |
|
84 |
#' app <- init( |
|
85 |
#' data = data, |
|
86 |
#' modules = modules( |
|
87 |
#' tm_outliers( |
|
88 |
#' outlier_var = list( |
|
89 |
#' data_extract_spec( |
|
90 |
#' dataname = "ADSL", |
|
91 |
#' select = select_spec( |
|
92 |
#' label = "Select variable:", |
|
93 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1")), |
|
94 |
#' selected = "AGE", |
|
95 |
#' multiple = FALSE, |
|
96 |
#' fixed = FALSE |
|
97 |
#' ) |
|
98 |
#' ) |
|
99 |
#' ), |
|
100 |
#' categorical_var = list( |
|
101 |
#' data_extract_spec( |
|
102 |
#' dataname = "ADSL", |
|
103 |
#' filter = filter_spec( |
|
104 |
#' vars = vars, |
|
105 |
#' choices = value_choices(data[["ADSL"]], vars$selected), |
|
106 |
#' selected = value_choices(data[["ADSL"]], vars$selected), |
|
107 |
#' multiple = TRUE |
|
108 |
#' ) |
|
109 |
#' ) |
|
110 |
#' ) |
|
111 |
#' ) |
|
112 |
#' ) |
|
113 |
#' ) |
|
114 |
#' if (interactive()) { |
|
115 |
#' shinyApp(app$ui, app$server) |
|
116 |
#' } |
|
117 |
#' |
|
118 |
#' @export |
|
119 |
#' |
|
120 |
tm_outliers <- function(label = "Outliers Module", |
|
121 |
outlier_var, |
|
122 |
categorical_var = NULL, |
|
123 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
124 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
125 |
plot_height = c(600, 200, 2000), |
|
126 |
plot_width = NULL, |
|
127 |
pre_output = NULL, |
|
128 |
post_output = NULL) { |
|
129 | ! |
message("Initializing tm_outliers") |
130 | ||
131 |
# Normalize the parameters |
|
132 | ! |
if (inherits(outlier_var, "data_extract_spec")) outlier_var <- list(outlier_var) |
133 | ! |
if (inherits(categorical_var, "data_extract_spec")) categorical_var <- list(categorical_var) |
134 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
135 | ||
136 |
# Start of assertions |
|
137 | ! |
checkmate::assert_string(label) |
138 | ! |
checkmate::assert_list(outlier_var, types = "data_extract_spec") |
139 | ||
140 | ! |
checkmate::assert_list(categorical_var, types = "data_extract_spec", null.ok = TRUE) |
141 | ! |
if (is.list(categorical_var)) { |
142 | ! |
lapply(categorical_var, function(x) { |
143 | ! |
if (length(x$filter) > 1L) { |
144 | ! |
stop("tm_outliers: categorical_var data_extract_specs may only specify one filter_spec", call. = FALSE) |
145 |
} |
|
146 |
}) |
|
147 |
} |
|
148 | ||
149 | ! |
ggtheme <- match.arg(ggtheme) |
150 | ||
151 | ! |
plot_choices <- c("Boxplot", "Density Plot", "Cumulative Distribution Plot") |
152 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
153 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
154 | ||
155 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
156 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
157 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
158 | ! |
checkmate::assert_numeric( |
159 | ! |
plot_width[1], |
160 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
161 |
) |
|
162 | ||
163 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
164 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
165 |
# End of assertions |
|
166 | ||
167 |
# Make UI args |
|
168 | ! |
args <- as.list(environment()) |
169 | ||
170 | ! |
data_extract_list <- list( |
171 | ! |
outlier_var = outlier_var, |
172 | ! |
categorical_var = categorical_var |
173 |
) |
|
174 | ||
175 | ! |
ans <- module( |
176 | ! |
label = label, |
177 | ! |
server = srv_outliers, |
178 | ! |
server_args = c( |
179 | ! |
data_extract_list, |
180 | ! |
list(plot_height = plot_height, plot_width = plot_width, ggplot2_args = ggplot2_args) |
181 |
), |
|
182 | ! |
ui = ui_outliers, |
183 | ! |
ui_args = args, |
184 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
185 |
) |
|
186 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
187 | ! |
ans |
188 |
} |
|
189 | ||
190 |
# UI function for the outliers module |
|
191 |
ui_outliers <- function(id, ...) { |
|
192 | ! |
args <- list(...) |
193 | ! |
ns <- NS(id) |
194 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$outlier_var, args$categorical_var) |
195 | ||
196 | ! |
teal.widgets::standard_layout( |
197 | ! |
output = teal.widgets::white_small_well( |
198 | ! |
uiOutput(ns("total_outliers")), |
199 | ! |
DT::dataTableOutput(ns("summary_table")), |
200 | ! |
uiOutput(ns("total_missing")), |
201 | ! |
tags$br(), tags$hr(), |
202 | ! |
tabsetPanel( |
203 | ! |
id = ns("tabs"), |
204 | ! |
tabPanel( |
205 | ! |
"Boxplot", |
206 | ! |
teal.widgets::plot_with_settings_ui(id = ns("box_plot")) |
207 |
), |
|
208 | ! |
tabPanel( |
209 | ! |
"Density Plot", |
210 | ! |
teal.widgets::plot_with_settings_ui(id = ns("density_plot")) |
211 |
), |
|
212 | ! |
tabPanel( |
213 | ! |
"Cumulative Distribution Plot", |
214 | ! |
teal.widgets::plot_with_settings_ui(id = ns("cum_density_plot")) |
215 |
) |
|
216 |
), |
|
217 | ! |
tags$br(), tags$hr(), |
218 | ! |
uiOutput(ns("table_ui_wrap")), |
219 | ! |
DT::dataTableOutput(ns("table_ui")) |
220 |
), |
|
221 | ! |
encoding = tags$div( |
222 |
### Reporter |
|
223 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
224 |
### |
|
225 | ! |
tags$label("Encodings", class = "text-primary"), |
226 | ! |
teal.transform::datanames_input(args[c("outlier_var", "categorical_var")]), |
227 | ! |
teal.transform::data_extract_ui( |
228 | ! |
id = ns("outlier_var"), |
229 | ! |
label = "Variable", |
230 | ! |
data_extract_spec = args$outlier_var, |
231 | ! |
is_single_dataset = is_single_dataset_value |
232 |
), |
|
233 | ! |
if (!is.null(args$categorical_var)) { |
234 | ! |
teal.transform::data_extract_ui( |
235 | ! |
id = ns("categorical_var"), |
236 | ! |
label = "Categorical factor", |
237 | ! |
data_extract_spec = args$categorical_var, |
238 | ! |
is_single_dataset = is_single_dataset_value |
239 |
) |
|
240 |
}, |
|
241 | ! |
conditionalPanel( |
242 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'Boxplot'"), |
243 | ! |
teal.widgets::optionalSelectInput( |
244 | ! |
inputId = ns("boxplot_alts"), |
245 | ! |
label = "Plot type", |
246 | ! |
choices = c("Box plot", "Violin plot"), |
247 | ! |
selected = "Box plot", |
248 | ! |
multiple = FALSE |
249 |
) |
|
250 |
), |
|
251 | ! |
shinyjs::hidden(checkboxInput(ns("split_outliers"), "Define outliers based on group splitting", value = FALSE)), |
252 | ! |
shinyjs::hidden(checkboxInput(ns("order_by_outlier"), "Re-order categories by outliers [by %]", value = FALSE)), |
253 | ! |
teal.widgets::panel_group( |
254 | ! |
teal.widgets::panel_item( |
255 | ! |
title = "Method parameters", |
256 | ! |
collapsed = FALSE, |
257 | ! |
teal.widgets::optionalSelectInput( |
258 | ! |
inputId = ns("method"), |
259 | ! |
label = "Method", |
260 | ! |
choices = c("IQR", "Z-score", "Percentile"), |
261 | ! |
selected = "IQR", |
262 | ! |
multiple = FALSE |
263 |
), |
|
264 | ! |
conditionalPanel( |
265 | ! |
condition = |
266 | ! |
paste0("input['", ns("method"), "'] == 'IQR'"), |
267 | ! |
sliderInput( |
268 | ! |
ns("iqr_slider"), |
269 | ! |
"Outlier range:", |
270 | ! |
min = 1, |
271 | ! |
max = 5, |
272 | ! |
value = 3, |
273 | ! |
step = 0.5 |
274 |
) |
|
275 |
), |
|
276 | ! |
conditionalPanel( |
277 | ! |
condition = |
278 | ! |
paste0("input['", ns("method"), "'] == 'Z-score'"), |
279 | ! |
sliderInput( |
280 | ! |
ns("zscore_slider"), |
281 | ! |
"Outlier range:", |
282 | ! |
min = 1, |
283 | ! |
max = 5, |
284 | ! |
value = 3, |
285 | ! |
step = 0.5 |
286 |
) |
|
287 |
), |
|
288 | ! |
conditionalPanel( |
289 | ! |
condition = |
290 | ! |
paste0("input['", ns("method"), "'] == 'Percentile'"), |
291 | ! |
sliderInput( |
292 | ! |
ns("percentile_slider"), |
293 | ! |
"Outlier range:", |
294 | ! |
min = 0.001, |
295 | ! |
max = 0.5, |
296 | ! |
value = 0.01, |
297 | ! |
step = 0.001 |
298 |
) |
|
299 |
), |
|
300 | ! |
uiOutput(ns("ui_outlier_help")) |
301 |
) |
|
302 |
), |
|
303 | ! |
teal.widgets::panel_item( |
304 | ! |
title = "Plot settings", |
305 | ! |
selectInput( |
306 | ! |
inputId = ns("ggtheme"), |
307 | ! |
label = "Theme (by ggplot):", |
308 | ! |
choices = ggplot_themes, |
309 | ! |
selected = args$ggtheme, |
310 | ! |
multiple = FALSE |
311 |
) |
|
312 |
) |
|
313 |
), |
|
314 | ! |
forms = tagList( |
315 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
316 |
), |
|
317 | ! |
pre_output = args$pre_output, |
318 | ! |
post_output = args$post_output |
319 |
) |
|
320 |
} |
|
321 | ||
322 |
# Server function for the outliers module |
|
323 |
srv_outliers <- function(id, data, reporter, filter_panel_api, outlier_var, |
|
324 |
categorical_var, plot_height, plot_width, ggplot2_args) { |
|
325 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
326 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
327 | ! |
checkmate::assert_class(data, "reactive") |
328 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
329 | ! |
moduleServer(id, function(input, output, session) { |
330 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
331 | ||
332 | ! |
ns <- session$ns |
333 | ||
334 | ! |
vars <- list(outlier_var = outlier_var, categorical_var = categorical_var) |
335 | ||
336 | ! |
rule_diff <- function(other) { |
337 | ! |
function(value) { |
338 | ! |
othervalue <- tryCatch(selector_list()[[other]]()[["select"]], error = function(e) NULL) |
339 | ! |
if (!is.null(othervalue) && identical(othervalue, value)) { |
340 | ! |
"`Variable` and `Categorical factor` cannot be the same" |
341 |
} |
|
342 |
} |
|
343 |
} |
|
344 | ||
345 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
346 | ! |
data_extract = vars, |
347 | ! |
datasets = data, |
348 | ! |
select_validation_rule = list( |
349 | ! |
outlier_var = shinyvalidate::compose_rules( |
350 | ! |
shinyvalidate::sv_required("Please select a variable"), |
351 | ! |
rule_diff("categorical_var") |
352 |
), |
|
353 | ! |
categorical_var = rule_diff("outlier_var") |
354 |
) |
|
355 |
) |
|
356 | ||
357 | ! |
iv_r <- reactive({ |
358 | ! |
iv <- shinyvalidate::InputValidator$new() |
359 | ! |
iv$add_rule("method", shinyvalidate::sv_required("Please select a method")) |
360 | ! |
iv$add_rule("boxplot_alts", shinyvalidate::sv_required("Please select Plot Type")) |
361 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
362 |
}) |
|
363 | ||
364 | ! |
reactive_select_input <- reactive({ |
365 | ! |
if (is.null(selector_list()$categorical_var) || length(selector_list()$categorical_var()$select) == 0) { |
366 | ! |
selector_list()[names(selector_list()) != "categorical_var"] |
367 |
} else { |
|
368 | ! |
selector_list() |
369 |
} |
|
370 |
}) |
|
371 | ||
372 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
373 | ! |
selector_list = reactive_select_input, |
374 | ! |
datasets = data, |
375 | ! |
merge_function = "dplyr::inner_join" |
376 |
) |
|
377 | ||
378 | ! |
anl_merged_q <- reactive({ |
379 | ! |
req(anl_merged_input()) |
380 | ! |
data() %>% |
381 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
382 |
}) |
|
383 | ||
384 | ! |
merged <- list( |
385 | ! |
anl_input_r = anl_merged_input, |
386 | ! |
anl_q_r = anl_merged_q |
387 |
) |
|
388 | ||
389 | ! |
n_outlier_missing <- reactive({ |
390 | ! |
req(iv_r()$is_valid()) |
391 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
392 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
393 | ! |
sum(is.na(ANL[[outlier_var]])) |
394 |
}) |
|
395 | ||
396 |
# Used to create outlier table and the dropdown with additional columns |
|
397 | ! |
dataname_first <- isolate(names(data())[[1]]) |
398 | ||
399 | ! |
common_code_q <- reactive({ |
400 | ! |
req(iv_r()$is_valid()) |
401 | ||
402 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
403 | ! |
qenv <- merged$anl_q_r() |
404 | ||
405 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
406 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
407 | ! |
order_by_outlier <- input$order_by_outlier |
408 | ! |
method <- input$method |
409 | ! |
split_outliers <- input$split_outliers |
410 | ! |
teal::validate_has_data( |
411 |
# missing values in the categorical variable may be used to form a category of its own |
|
412 | ! |
`if`( |
413 | ! |
length(categorical_var) == 0, |
414 | ! |
ANL, |
415 | ! |
ANL[, names(ANL) != categorical_var, drop = FALSE] |
416 |
), |
|
417 | ! |
min_nrow = 10, |
418 | ! |
complete = TRUE, |
419 | ! |
allow_inf = FALSE |
420 |
) |
|
421 | ! |
validate(need(is.numeric(ANL[[outlier_var]]), "`Variable` is not numeric")) |
422 | ! |
validate(need(length(unique(ANL[[outlier_var]])) > 1, "Variable has no variation, i.e. only one unique value")) |
423 | ||
424 |
# show/hide split_outliers |
|
425 | ! |
if (length(categorical_var) == 0) { |
426 | ! |
shinyjs::hide("split_outliers") |
427 | ! |
if (n_outlier_missing() > 0) { |
428 | ! |
qenv <- teal.code::eval_code( |
429 | ! |
qenv, |
430 | ! |
substitute( |
431 | ! |
expr = ANL <- ANL %>% dplyr::filter(!is.na(outlier_var_name)), |
432 | ! |
env = list(outlier_var_name = as.name(outlier_var)) |
433 |
) |
|
434 |
) |
|
435 |
} |
|
436 |
} else { |
|
437 | ! |
validate(need( |
438 | ! |
is.factor(ANL[[categorical_var]]) || |
439 | ! |
is.character(ANL[[categorical_var]]) || |
440 | ! |
is.integer(ANL[[categorical_var]]), |
441 | ! |
"`Categorical factor` must be `factor`, `character`, or `integer`" |
442 |
)) |
|
443 | ||
444 | ! |
if (n_outlier_missing() > 0) { |
445 | ! |
qenv <- teal.code::eval_code( |
446 | ! |
qenv, |
447 | ! |
substitute( |
448 | ! |
expr = ANL <- ANL %>% dplyr::filter(!is.na(outlier_var_name)), |
449 | ! |
env = list(outlier_var_name = as.name(outlier_var)) |
450 |
) |
|
451 |
) |
|
452 |
} |
|
453 | ! |
shinyjs::show("split_outliers") |
454 |
} |
|
455 | ||
456 |
# slider |
|
457 | ! |
outlier_definition_param <- if (method == "IQR") { |
458 | ! |
input$iqr_slider |
459 | ! |
} else if (method == "Z-score") { |
460 | ! |
input$zscore_slider |
461 | ! |
} else if (method == "Percentile") { |
462 | ! |
input$percentile_slider |
463 |
} |
|
464 | ||
465 |
# this is utils function that converts a %>% NULL %>% b into a %>% b |
|
466 | ! |
remove_pipe_null <- function(x) { |
467 | ! |
if (length(x) == 1) { |
468 | ! |
return(x) |
469 |
} |
|
470 | ! |
if (identical(x[[1]], as.name("%>%")) && is.null(x[[3]])) { |
471 | ! |
return(remove_pipe_null(x[[2]])) |
472 |
} |
|
473 | ! |
return(as.call(c(x[[1]], lapply(x[-1], remove_pipe_null)))) |
474 |
} |
|
475 | ||
476 | ! |
qenv <- teal.code::eval_code( |
477 | ! |
qenv, |
478 | ! |
substitute( |
479 | ! |
expr = { |
480 | ! |
ANL_OUTLIER <- ANL %>% |
481 | ! |
group_expr %>% # styler: off |
482 | ! |
dplyr::mutate(is_outlier = { |
483 | ! |
q1_q3 <- stats::quantile(outlier_var_name, probs = c(0.25, 0.75)) |
484 | ! |
iqr <- q1_q3[2] - q1_q3[1] |
485 | ! |
!(outlier_var_name >= q1_q3[1] - 1.5 * iqr & outlier_var_name <= q1_q3[2] + 1.5 * iqr) |
486 |
}) %>% |
|
487 | ! |
calculate_outliers %>% # styler: off |
488 | ! |
ungroup_expr %>% # styler: off |
489 | ! |
dplyr::filter(is_outlier | is_outlier_selected) %>% |
490 | ! |
dplyr::select(-is_outlier) |
491 |
}, |
|
492 | ! |
env = list( |
493 | ! |
calculate_outliers = if (method == "IQR") { |
494 | ! |
substitute( |
495 | ! |
expr = dplyr::mutate(is_outlier_selected = { |
496 | ! |
q1_q3 <- stats::quantile(outlier_var_name, probs = c(0.25, 0.75)) |
497 | ! |
iqr <- q1_q3[2] - q1_q3[1] |
498 |
!( |
|
499 | ! |
outlier_var_name >= q1_q3[1] - outlier_definition_param * iqr & |
500 | ! |
outlier_var_name <= q1_q3[2] + outlier_definition_param * iqr |
501 |
) |
|
502 |
}), |
|
503 | ! |
env = list( |
504 | ! |
outlier_var_name = as.name(outlier_var), |
505 | ! |
outlier_definition_param = outlier_definition_param |
506 |
) |
|
507 |
) |
|
508 | ! |
} else if (method == "Z-score") { |
509 | ! |
substitute( |
510 | ! |
expr = dplyr::mutate( |
511 | ! |
is_outlier_selected = abs(outlier_var_name - mean(outlier_var_name)) / |
512 | ! |
stats::sd(outlier_var_name) > outlier_definition_param |
513 |
), |
|
514 | ! |
env = list( |
515 | ! |
outlier_var_name = as.name(outlier_var), |
516 | ! |
outlier_definition_param = outlier_definition_param |
517 |
) |
|
518 |
) |
|
519 | ! |
} else if (method == "Percentile") { |
520 | ! |
substitute( |
521 | ! |
expr = dplyr::mutate( |
522 | ! |
is_outlier_selected = outlier_var_name < stats::quantile(outlier_var_name, outlier_definition_param) | |
523 | ! |
outlier_var_name > stats::quantile(outlier_var_name, 1 - outlier_definition_param) |
524 |
), |
|
525 | ! |
env = list( |
526 | ! |
outlier_var_name = as.name(outlier_var), |
527 | ! |
outlier_definition_param = outlier_definition_param |
528 |
) |
|
529 |
) |
|
530 |
}, |
|
531 | ! |
outlier_var_name = as.name(outlier_var), |
532 | ! |
group_expr = if (isTRUE(split_outliers) && length(categorical_var) != 0) { |
533 | ! |
substitute(dplyr::group_by(x), list(x = as.name(categorical_var))) |
534 |
}, |
|
535 | ! |
ungroup_expr = if (isTRUE(split_outliers) && length(categorical_var) != 0) { |
536 | ! |
substitute(dplyr::ungroup()) |
537 |
} |
|
538 |
) |
|
539 |
) %>% |
|
540 | ! |
remove_pipe_null() |
541 |
) |
|
542 | ||
543 |
# ANL_OUTLIER_EXTENDED is the base table |
|
544 | ! |
qenv <- teal.code::eval_code( |
545 | ! |
qenv, |
546 | ! |
substitute( |
547 | ! |
expr = { |
548 | ! |
ANL_OUTLIER_EXTENDED <- dplyr::left_join( |
549 | ! |
ANL_OUTLIER, |
550 | ! |
dplyr::select( |
551 | ! |
dataname, |
552 | ! |
dplyr::setdiff(names(dataname), dplyr::setdiff(names(ANL_OUTLIER), join_keys)) |
553 |
), |
|
554 | ! |
by = join_keys |
555 |
) |
|
556 |
}, |
|
557 | ! |
env = list( |
558 | ! |
dataname = as.name(dataname_first), |
559 | ! |
join_keys = as.character(teal.data::join_keys(data())[dataname_first, dataname_first]) |
560 |
) |
|
561 |
) |
|
562 |
) |
|
563 | ||
564 | ! |
if (length(categorical_var) > 0) { |
565 | ! |
qenv <- teal.code::eval_code( |
566 | ! |
qenv, |
567 | ! |
substitute( |
568 | ! |
expr = summary_table_pre <- ANL_OUTLIER %>% |
569 | ! |
dplyr::filter(is_outlier_selected) %>% |
570 | ! |
dplyr::select(outlier_var_name, categorical_var_name) %>% |
571 | ! |
dplyr::group_by(categorical_var_name) %>% |
572 | ! |
dplyr::summarise(n_outliers = dplyr::n()) %>% |
573 | ! |
dplyr::right_join( |
574 | ! |
ANL %>% |
575 | ! |
dplyr::select(outlier_var_name, categorical_var_name) %>% |
576 | ! |
dplyr::group_by(categorical_var_name) %>% |
577 | ! |
dplyr::summarise( |
578 | ! |
total_in_cat = dplyr::n(), |
579 | ! |
n_na = sum(is.na(outlier_var_name) | is.na(categorical_var_name)) |
580 |
), |
|
581 | ! |
by = categorical_var |
582 |
) %>% |
|
583 |
# This is important as there may be categorical variables with natural orderings, e.g. AGE. |
|
584 |
# The plots should be displayed by default in increasing order in these situations. |
|
585 |
# dplyr::arrange will sort integer, factor, and character data types in the expected way. |
|
586 | ! |
dplyr::arrange(categorical_var_name) %>% |
587 | ! |
dplyr::mutate( |
588 | ! |
n_outliers = dplyr::if_else(is.na(n_outliers), 0, as.numeric(n_outliers)), |
589 | ! |
display_str = dplyr::if_else( |
590 | ! |
n_outliers > 0, |
591 | ! |
sprintf("%d [%.02f%%]", n_outliers, 100 * n_outliers / total_in_cat), |
592 | ! |
"0" |
593 |
), |
|
594 | ! |
display_str_na = dplyr::if_else( |
595 | ! |
n_na > 0, |
596 | ! |
sprintf("%d [%.02f%%]", n_na, 100 * n_na / total_in_cat), |
597 | ! |
"0" |
598 |
), |
|
599 | ! |
order = seq_along(n_outliers) |
600 |
), |
|
601 | ! |
env = list( |
602 | ! |
categorical_var = categorical_var, |
603 | ! |
categorical_var_name = as.name(categorical_var), |
604 | ! |
outlier_var_name = as.name(outlier_var) |
605 |
) |
|
606 |
) |
|
607 |
) |
|
608 |
# now to handle when user chooses to order based on amount of outliers |
|
609 | ! |
if (order_by_outlier) { |
610 | ! |
qenv <- teal.code::eval_code( |
611 | ! |
qenv, |
612 | ! |
quote( |
613 | ! |
summary_table_pre <- summary_table_pre %>% |
614 | ! |
dplyr::arrange(desc(n_outliers / total_in_cat)) %>% |
615 | ! |
dplyr::mutate(order = seq_len(nrow(summary_table_pre))) |
616 |
) |
|
617 |
) |
|
618 |
} |
|
619 | ||
620 | ! |
qenv <- teal.code::eval_code( |
621 | ! |
qenv, |
622 | ! |
substitute( |
623 | ! |
expr = { |
624 |
# In order for geom_rug to work properly when reordering takes place inside facet_grid, |
|
625 |
# all tables must have the column used for reording. |
|
626 |
# In this case, the column used for reordering is `order`. |
|
627 | ! |
ANL_OUTLIER <- dplyr::left_join( |
628 | ! |
ANL_OUTLIER, |
629 | ! |
summary_table_pre[, c("order", categorical_var)], |
630 | ! |
by = categorical_var |
631 |
) |
|
632 |
# so that x axis of plot aligns with columns of summary table, from most outliers to least by percentage |
|
633 | ! |
ANL <- ANL %>% |
634 | ! |
dplyr::left_join( |
635 | ! |
dplyr::select(summary_table_pre, categorical_var_name, order), |
636 | ! |
by = categorical_var |
637 |
) %>% |
|
638 | ! |
dplyr::arrange(order) |
639 | ! |
summary_table <- summary_table_pre %>% |
640 | ! |
dplyr::select( |
641 | ! |
categorical_var_name, |
642 | ! |
Outliers = display_str, Missings = display_str_na, Total = total_in_cat |
643 |
) %>% |
|
644 | ! |
dplyr::mutate_all(as.character) %>% |
645 | ! |
tidyr::pivot_longer(-categorical_var_name) %>% |
646 | ! |
tidyr::pivot_wider(names_from = categorical_var, values_from = value) %>% |
647 | ! |
tibble::column_to_rownames("name") |
648 | ! |
summary_table |
649 |
}, |
|
650 | ! |
env = list( |
651 | ! |
categorical_var = categorical_var, |
652 | ! |
categorical_var_name = as.name(categorical_var) |
653 |
) |
|
654 |
) |
|
655 |
) |
|
656 |
} |
|
657 | ||
658 | ! |
if (length(categorical_var) > 0 && nrow(qenv[["ANL_OUTLIER"]]) > 0) { |
659 | ! |
shinyjs::show("order_by_outlier") |
660 |
} else { |
|
661 | ! |
shinyjs::hide("order_by_outlier") |
662 |
} |
|
663 | ||
664 | ! |
qenv |
665 |
}) |
|
666 | ||
667 | ! |
output$summary_table <- DT::renderDataTable( |
668 | ! |
expr = { |
669 | ! |
if (iv_r()$is_valid()) { |
670 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
671 | ! |
if (!is.null(categorical_var)) { |
672 | ! |
DT::datatable( |
673 | ! |
common_code_q()[["summary_table"]], |
674 | ! |
options = list( |
675 | ! |
dom = "t", |
676 | ! |
autoWidth = TRUE, |
677 | ! |
columnDefs = list(list(width = "200px", targets = "_all")) |
678 |
) |
|
679 |
) |
|
680 |
} |
|
681 |
} |
|
682 |
} |
|
683 |
) |
|
684 | ||
685 |
# boxplot/violinplot # nolint commented_code |
|
686 | ! |
boxplot_q <- reactive({ |
687 | ! |
req(common_code_q()) |
688 | ! |
ANL <- common_code_q()[["ANL"]] |
689 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
690 | ||
691 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
692 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
693 | ||
694 |
# validation |
|
695 | ! |
teal::validate_has_data(ANL, 1) |
696 | ||
697 |
# boxplot |
|
698 | ! |
plot_call <- quote(ANL %>% ggplot()) |
699 | ||
700 | ! |
plot_call <- if (input$boxplot_alts == "Box plot") { |
701 | ! |
substitute(expr = plot_call + geom_boxplot(outlier.shape = NA), env = list(plot_call = plot_call)) |
702 | ! |
} else if (input$boxplot_alts == "Violin plot") { |
703 | ! |
substitute(expr = plot_call + geom_violin(), env = list(plot_call = plot_call)) |
704 |
} else { |
|
705 | ! |
NULL |
706 |
} |
|
707 | ||
708 | ! |
plot_call <- if (identical(categorical_var, character(0)) || is.null(categorical_var)) { |
709 | ! |
inner_call <- substitute( |
710 | ! |
expr = plot_call + |
711 | ! |
aes(x = "Entire dataset", y = outlier_var_name) + |
712 | ! |
scale_x_discrete(), |
713 | ! |
env = list(plot_call = plot_call, outlier_var_name = as.name(outlier_var)) |
714 |
) |
|
715 | ! |
if (nrow(ANL_OUTLIER) > 0) { |
716 | ! |
substitute( |
717 | ! |
expr = inner_call + geom_point( |
718 | ! |
data = ANL_OUTLIER, |
719 | ! |
aes(x = "Entire dataset", y = outlier_var_name, color = is_outlier_selected) |
720 |
), |
|
721 | ! |
env = list(inner_call = inner_call, outlier_var_name = as.name(outlier_var)) |
722 |
) |
|
723 |
} else { |
|
724 | ! |
inner_call |
725 |
} |
|
726 |
} else { |
|
727 | ! |
substitute( |
728 | ! |
expr = plot_call + |
729 | ! |
aes(y = outlier_var_name, x = reorder(categorical_var_name, order)) + |
730 | ! |
xlab(categorical_var) + |
731 | ! |
scale_x_discrete() + |
732 | ! |
geom_point( |
733 | ! |
data = ANL_OUTLIER, |
734 | ! |
aes(x = as.factor(categorical_var_name), y = outlier_var_name, color = is_outlier_selected) |
735 |
), |
|
736 | ! |
env = list( |
737 | ! |
plot_call = plot_call, |
738 | ! |
outlier_var_name = as.name(outlier_var), |
739 | ! |
categorical_var_name = as.name(categorical_var), |
740 | ! |
categorical_var = categorical_var |
741 |
) |
|
742 |
) |
|
743 |
} |
|
744 | ||
745 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
746 | ! |
labs = list(color = "Is outlier?"), |
747 | ! |
theme = list(legend.position = "top") |
748 |
) |
|
749 | ||
750 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
751 | ! |
user_plot = ggplot2_args[["Boxplot"]], |
752 | ! |
user_default = ggplot2_args$default, |
753 | ! |
module_plot = dev_ggplot2_args |
754 |
) |
|
755 | ||
756 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
757 | ! |
all_ggplot2_args, |
758 | ! |
ggtheme = input$ggtheme |
759 |
) |
|
760 | ||
761 | ! |
teal.code::eval_code( |
762 | ! |
common_code_q(), |
763 | ! |
substitute( |
764 | ! |
expr = g <- plot_call + |
765 | ! |
scale_color_manual(values = c("TRUE" = "red", "FALSE" = "black")) + |
766 | ! |
labs + ggthemes + themes, |
767 | ! |
env = list( |
768 | ! |
plot_call = plot_call, |
769 | ! |
labs = parsed_ggplot2_args$labs, |
770 | ! |
ggthemes = parsed_ggplot2_args$ggtheme, |
771 | ! |
themes = parsed_ggplot2_args$theme |
772 |
) |
|
773 |
) |
|
774 |
) %>% |
|
775 | ! |
teal.code::eval_code(quote(print(g))) |
776 |
}) |
|
777 | ||
778 |
# density plot |
|
779 | ! |
density_plot_q <- reactive({ |
780 | ! |
ANL <- common_code_q()[["ANL"]] |
781 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
782 | ||
783 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
784 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
785 | ||
786 |
# validation |
|
787 | ! |
teal::validate_has_data(ANL, 1) |
788 |
# plot |
|
789 | ! |
plot_call <- substitute( |
790 | ! |
expr = ANL %>% |
791 | ! |
ggplot(aes(x = outlier_var_name)) + |
792 | ! |
geom_density() + |
793 | ! |
geom_rug(data = ANL_OUTLIER, aes(x = outlier_var_name, color = is_outlier_selected)) + |
794 | ! |
scale_color_manual(values = c("TRUE" = "red", "FALSE" = "black")), |
795 | ! |
env = list(outlier_var_name = as.name(outlier_var)) |
796 |
) |
|
797 | ||
798 | ! |
plot_call <- if (identical(categorical_var, character(0)) || is.null(categorical_var)) { |
799 | ! |
substitute(expr = plot_call, env = list(plot_call = plot_call)) |
800 |
} else { |
|
801 | ! |
substitute( |
802 | ! |
expr = plot_call + facet_grid(~ reorder(categorical_var_name, order)), |
803 | ! |
env = list(plot_call = plot_call, categorical_var_name = as.name(categorical_var)) |
804 |
) |
|
805 |
} |
|
806 | ||
807 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
808 | ! |
labs = list(color = "Is outlier?"), |
809 | ! |
theme = list(legend.position = "top") |
810 |
) |
|
811 | ||
812 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
813 | ! |
user_plot = ggplot2_args[["Density Plot"]], |
814 | ! |
user_default = ggplot2_args$default, |
815 | ! |
module_plot = dev_ggplot2_args |
816 |
) |
|
817 | ||
818 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
819 | ! |
all_ggplot2_args, |
820 | ! |
ggtheme = input$ggtheme |
821 |
) |
|
822 | ||
823 | ! |
teal.code::eval_code( |
824 | ! |
common_code_q(), |
825 | ! |
substitute( |
826 | ! |
expr = g <- plot_call + labs + ggthemes + themes, |
827 | ! |
env = list( |
828 | ! |
plot_call = plot_call, |
829 | ! |
labs = parsed_ggplot2_args$labs, |
830 | ! |
themes = parsed_ggplot2_args$theme, |
831 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
832 |
) |
|
833 |
) |
|
834 |
) %>% |
|
835 | ! |
teal.code::eval_code(quote(print(g))) |
836 |
}) |
|
837 | ||
838 |
# Cumulative distribution plot |
|
839 | ! |
cumulative_plot_q <- reactive({ |
840 | ! |
ANL <- common_code_q()[["ANL"]] |
841 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
842 | ||
843 | ! |
qenv <- common_code_q() |
844 | ||
845 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
846 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
847 | ||
848 |
# validation |
|
849 | ! |
teal::validate_has_data(ANL, 1) |
850 | ||
851 |
# plot |
|
852 | ! |
plot_call <- substitute( |
853 | ! |
expr = ANL %>% ggplot(aes(x = outlier_var_name)) + |
854 | ! |
stat_ecdf(), |
855 | ! |
env = list(outlier_var_name = as.name(outlier_var)) |
856 |
) |
|
857 | ! |
if (length(categorical_var) == 0) { |
858 | ! |
qenv <- teal.code::eval_code( |
859 | ! |
qenv, |
860 | ! |
substitute( |
861 | ! |
expr = { |
862 | ! |
ecdf_df <- ANL %>% |
863 | ! |
dplyr::mutate( |
864 | ! |
y = stats::ecdf(ANL[[outlier_var]])(ANL[[outlier_var]]) |
865 |
) |
|
866 | ||
867 | ! |
outlier_points <- dplyr::left_join( |
868 | ! |
ecdf_df, |
869 | ! |
ANL_OUTLIER, |
870 | ! |
by = dplyr::setdiff(names(ecdf_df), "y") |
871 |
) %>% |
|
872 | ! |
dplyr::filter(!is.na(is_outlier_selected)) |
873 |
}, |
|
874 | ! |
env = list(outlier_var = outlier_var) |
875 |
) |
|
876 |
) |
|
877 |
} else { |
|
878 | ! |
qenv <- teal.code::eval_code( |
879 | ! |
qenv, |
880 | ! |
substitute( |
881 | ! |
expr = { |
882 | ! |
all_categories <- lapply( |
883 | ! |
unique(ANL[[categorical_var]]), |
884 | ! |
function(x) { |
885 | ! |
ANL <- ANL %>% dplyr::filter(get(categorical_var) == x) |
886 | ! |
anl_outlier2 <- ANL_OUTLIER %>% dplyr::filter(get(categorical_var) == x) |
887 | ! |
ecdf_df <- ANL %>% |
888 | ! |
dplyr::mutate(y = stats::ecdf(ANL[[outlier_var]])(ANL[[outlier_var]])) |
889 | ||
890 | ! |
dplyr::left_join( |
891 | ! |
ecdf_df, |
892 | ! |
anl_outlier2, |
893 | ! |
by = dplyr::setdiff(names(ecdf_df), "y") |
894 |
) %>% |
|
895 | ! |
dplyr::filter(!is.na(is_outlier_selected)) |
896 |
} |
|
897 |
) |
|
898 | ! |
outlier_points <- do.call(rbind, all_categories) |
899 |
}, |
|
900 | ! |
env = list(categorical_var = categorical_var, outlier_var = outlier_var) |
901 |
) |
|
902 |
) |
|
903 | ! |
plot_call <- substitute( |
904 | ! |
expr = plot_call + facet_grid(~ reorder(categorical_var_name, order)), |
905 | ! |
env = list(plot_call = plot_call, categorical_var_name = as.name(categorical_var)) |
906 |
) |
|
907 |
} |
|
908 | ||
909 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
910 | ! |
labs = list(color = "Is outlier?"), |
911 | ! |
theme = list(legend.position = "top") |
912 |
) |
|
913 | ||
914 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
915 | ! |
user_plot = ggplot2_args[["Cumulative Distribution Plot"]], |
916 | ! |
user_default = ggplot2_args$default, |
917 | ! |
module_plot = dev_ggplot2_args |
918 |
) |
|
919 | ||
920 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
921 | ! |
all_ggplot2_args, |
922 | ! |
ggtheme = input$ggtheme |
923 |
) |
|
924 | ||
925 | ! |
teal.code::eval_code( |
926 | ! |
qenv, |
927 | ! |
substitute( |
928 | ! |
expr = g <- plot_call + |
929 | ! |
geom_point(data = outlier_points, aes(x = outlier_var_name, y = y, color = is_outlier_selected)) + |
930 | ! |
scale_color_manual(values = c("TRUE" = "red", "FALSE" = "black")) + |
931 | ! |
labs + ggthemes + themes, |
932 | ! |
env = list( |
933 | ! |
plot_call = plot_call, |
934 | ! |
outlier_var_name = as.name(outlier_var), |
935 | ! |
labs = parsed_ggplot2_args$labs, |
936 | ! |
themes = parsed_ggplot2_args$theme, |
937 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
938 |
) |
|
939 |
) |
|
940 |
) %>% |
|
941 | ! |
teal.code::eval_code(quote(print(g))) |
942 |
}) |
|
943 | ||
944 | ! |
final_q <- reactive({ |
945 | ! |
req(input$tabs) |
946 | ! |
tab_type <- input$tabs |
947 | ! |
result_q <- if (tab_type == "Boxplot") { |
948 | ! |
boxplot_q() |
949 | ! |
} else if (tab_type == "Density Plot") { |
950 | ! |
density_plot_q() |
951 | ! |
} else if (tab_type == "Cumulative Distribution Plot") { |
952 | ! |
cumulative_plot_q() |
953 |
} |
|
954 |
# used to display table when running show-r-code code |
|
955 |
# added after the plots so that a change in selected columns doesn't affect |
|
956 |
# brush selection. |
|
957 | ! |
teal.code::eval_code( |
958 | ! |
result_q, |
959 | ! |
substitute( |
960 | ! |
expr = { |
961 | ! |
columns_index <- union( |
962 | ! |
setdiff(names(ANL_OUTLIER), c("is_outlier_selected", "order")), |
963 | ! |
table_columns |
964 |
) |
|
965 | ! |
ANL_OUTLIER_EXTENDED[ANL_OUTLIER_EXTENDED$is_outlier_selected, columns_index] |
966 |
}, |
|
967 | ! |
env = list( |
968 | ! |
table_columns = input$table_ui_columns |
969 |
) |
|
970 |
) |
|
971 |
) |
|
972 |
}) |
|
973 | ||
974 |
# slider text |
|
975 | ! |
output$ui_outlier_help <- renderUI({ |
976 | ! |
req(input$method) |
977 | ! |
if (input$method == "IQR") { |
978 | ! |
req(input$iqr_slider) |
979 | ! |
tags$small( |
980 | ! |
withMathJax( |
981 | ! |
helpText( |
982 | ! |
"Outlier data points (\\(x \\lt Q1 - ", input$iqr_slider, "\\times IQR\\) or \\( |
983 | ! |
Q3 + ", input$iqr_slider, "\\times IQR \\lt x\\)) |
984 | ! |
are displayed in red on the plot and can be visualized in the table below." |
985 |
), |
|
986 | ! |
if (input$split_outliers) { |
987 | ! |
withMathJax(helpText("Note: Quantiles are calculated per group.")) |
988 |
} |
|
989 |
) |
|
990 |
) |
|
991 | ! |
} else if (input$method == "Z-score") { |
992 | ! |
req(input$zscore_slider) |
993 | ! |
tags$small( |
994 | ! |
withMathJax( |
995 | ! |
helpText( |
996 | ! |
"Outlier data points (\\(Zscore(x) < -", input$zscore_slider, |
997 | ! |
"\\) or \\(", input$zscore_slider, "< Zscore(x) \\)) |
998 | ! |
are displayed in red on the plot and can be visualized in the table below." |
999 |
), |
|
1000 | ! |
if (input$split_outliers) { |
1001 | ! |
withMathJax(helpText(" Note: Z-scores are calculated per group.")) |
1002 |
} |
|
1003 |
) |
|
1004 |
) |
|
1005 | ! |
} else if (input$method == "Percentile") { |
1006 | ! |
req(input$percentile_slider) |
1007 | ! |
tags$small( |
1008 | ! |
withMathJax( |
1009 | ! |
helpText( |
1010 | ! |
"Outlier/extreme data points (\\( Percentile(x) <", input$percentile_slider, |
1011 | ! |
"\\) or \\(", 1 - input$percentile_slider, " < Percentile(x) \\)) |
1012 | ! |
are displayed in red on the plot and can be visualized in the table below." |
1013 |
), |
|
1014 | ! |
if (input$split_outliers) { |
1015 | ! |
withMathJax(helpText("Note: Percentiles are calculated per group.")) |
1016 |
} |
|
1017 |
) |
|
1018 |
) |
|
1019 |
} |
|
1020 |
}) |
|
1021 | ||
1022 | ! |
boxplot_r <- reactive({ |
1023 | ! |
teal::validate_inputs(iv_r()) |
1024 | ! |
boxplot_q()[["g"]] |
1025 |
}) |
|
1026 | ! |
density_plot_r <- reactive({ |
1027 | ! |
teal::validate_inputs(iv_r()) |
1028 | ! |
density_plot_q()[["g"]] |
1029 |
}) |
|
1030 | ! |
cumulative_plot_r <- reactive({ |
1031 | ! |
teal::validate_inputs(iv_r()) |
1032 | ! |
cumulative_plot_q()[["g"]] |
1033 |
}) |
|
1034 | ||
1035 | ! |
box_pws <- teal.widgets::plot_with_settings_srv( |
1036 | ! |
id = "box_plot", |
1037 | ! |
plot_r = boxplot_r, |
1038 | ! |
height = plot_height, |
1039 | ! |
width = plot_width, |
1040 | ! |
brushing = TRUE |
1041 |
) |
|
1042 | ||
1043 | ! |
density_pws <- teal.widgets::plot_with_settings_srv( |
1044 | ! |
id = "density_plot", |
1045 | ! |
plot_r = density_plot_r, |
1046 | ! |
height = plot_height, |
1047 | ! |
width = plot_width, |
1048 | ! |
brushing = TRUE |
1049 |
) |
|
1050 | ||
1051 | ! |
cum_density_pws <- teal.widgets::plot_with_settings_srv( |
1052 | ! |
id = "cum_density_plot", |
1053 | ! |
plot_r = cumulative_plot_r, |
1054 | ! |
height = plot_height, |
1055 | ! |
width = plot_width, |
1056 | ! |
brushing = TRUE |
1057 |
) |
|
1058 | ||
1059 | ! |
choices <- reactive(teal.transform::variable_choices(data()[[dataname_first]])) |
1060 | ||
1061 | ! |
observeEvent(common_code_q(), { |
1062 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
1063 | ! |
teal.widgets::updateOptionalSelectInput( |
1064 | ! |
session, |
1065 | ! |
inputId = "table_ui_columns", |
1066 | ! |
choices = dplyr::setdiff(choices(), names(ANL_OUTLIER)), |
1067 | ! |
selected = restoreInput(ns("table_ui_columns"), isolate(input$table_ui_columns)) |
1068 |
) |
|
1069 |
}) |
|
1070 | ||
1071 | ! |
output$table_ui <- DT::renderDataTable( |
1072 | ! |
expr = { |
1073 | ! |
tab <- input$tabs |
1074 | ! |
req(tab) # tab is NULL upon app launch, hence will crash without this statement |
1075 | ! |
req(iv_r()$is_valid()) # Same validation as output$table_ui_wrap |
1076 | ! |
outlier_var <- as.vector(merged$anl_input_r()$columns_source$outlier_var) |
1077 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
1078 | ||
1079 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
1080 | ! |
ANL_OUTLIER_EXTENDED <- common_code_q()[["ANL_OUTLIER_EXTENDED"]] |
1081 | ! |
ANL <- common_code_q()[["ANL"]] |
1082 | ||
1083 | ! |
plot_brush <- if (tab == "Boxplot") { |
1084 | ! |
boxplot_r() |
1085 | ! |
box_pws$brush() |
1086 | ! |
} else if (tab == "Density Plot") { |
1087 | ! |
density_plot_r() |
1088 | ! |
density_pws$brush() |
1089 | ! |
} else if (tab == "Cumulative Distribution Plot") { |
1090 | ! |
cumulative_plot_r() |
1091 | ! |
cum_density_pws$brush() |
1092 |
} |
|
1093 | ||
1094 |
# removing unused column ASAP |
|
1095 | ! |
ANL_OUTLIER$order <- ANL$order <- NULL |
1096 | ||
1097 | ! |
display_table <- if (!is.null(plot_brush)) { |
1098 | ! |
if (length(categorical_var) > 0) { |
1099 |
# due to reordering, the x-axis label may be changed to something like "reorder(categorical_var, order)" |
|
1100 | ! |
if (tab == "Boxplot") { |
1101 | ! |
plot_brush$mapping$x <- categorical_var |
1102 |
} else { |
|
1103 |
# the other plots use facetting |
|
1104 |
# so it is panelvar1 that gets relabelled to "reorder(categorical_var, order)" |
|
1105 | ! |
plot_brush$mapping$panelvar1 <- categorical_var |
1106 |
} |
|
1107 |
} else { |
|
1108 | ! |
if (tab == "Boxplot") { |
1109 |
# in boxplot with no categorical variable, there is no column in ANL that would correspond to x-axis |
|
1110 |
# so a column needs to be inserted with the value "Entire dataset" because that's the label used in plot |
|
1111 | ! |
ANL[[plot_brush$mapping$x]] <- "Entire dataset" |
1112 |
} |
|
1113 |
} |
|
1114 | ||
1115 |
# in density and cumulative plots, ANL does not have a column corresponding to y-axis. |
|
1116 |
# so they need to be computed and attached to ANL |
|
1117 | ! |
if (tab == "Density Plot") { |
1118 | ! |
plot_brush$mapping$y <- "density" |
1119 | ! |
ANL$density <- plot_brush$ymin |
1120 |
# either ymin or ymax will work |
|
1121 | ! |
} else if (tab == "Cumulative Distribution Plot") { |
1122 | ! |
plot_brush$mapping$y <- "cdf" |
1123 | ! |
if (length(categorical_var) > 0) { |
1124 | ! |
ANL <- ANL %>% |
1125 | ! |
dplyr::group_by(!!as.name(plot_brush$mapping$panelvar1)) %>% |
1126 | ! |
dplyr::mutate(cdf = stats::ecdf(!!as.name(outlier_var))(!!as.name(outlier_var))) |
1127 |
} else { |
|
1128 | ! |
ANL$cdf <- stats::ecdf(ANL[[outlier_var]])(ANL[[outlier_var]]) |
1129 |
} |
|
1130 |
} |
|
1131 | ||
1132 | ! |
brushed_rows <- brushedPoints(ANL, plot_brush) |
1133 | ! |
if (nrow(brushed_rows) > 0) { |
1134 |
# now we need to remove extra column from ANL so that it will have the same columns as ANL_OUTLIER |
|
1135 |
# so that dplyr::intersect will work |
|
1136 | ! |
if (tab == "Density Plot") { |
1137 | ! |
brushed_rows$density <- NULL |
1138 | ! |
} else if (tab == "Cumulative Distribution Plot") { |
1139 | ! |
brushed_rows$cdf <- NULL |
1140 | ! |
} else if (tab == "Boxplot" && length(categorical_var) == 0) { |
1141 | ! |
brushed_rows[[plot_brush$mapping$x]] <- NULL |
1142 |
} |
|
1143 |
# is_outlier_selected is part of ANL_OUTLIER so needed here |
|
1144 | ! |
brushed_rows$is_outlier_selected <- TRUE |
1145 | ! |
dplyr::intersect(ANL_OUTLIER, brushed_rows) |
1146 |
} else { |
|
1147 | ! |
ANL_OUTLIER[0, ] |
1148 |
} |
|
1149 |
} else { |
|
1150 | ! |
ANL_OUTLIER[ANL_OUTLIER$is_outlier_selected, ] |
1151 |
} |
|
1152 | ||
1153 | ! |
display_table$is_outlier_selected <- NULL |
1154 | ||
1155 |
# Extend the brushed ANL_OUTLIER with additional columns |
|
1156 | ! |
dplyr::left_join( |
1157 | ! |
display_table, |
1158 | ! |
dplyr::select(ANL_OUTLIER_EXTENDED, -"is_outlier_selected"), |
1159 | ! |
by = names(display_table) |
1160 |
) %>% |
|
1161 | ! |
dplyr::select(union(names(display_table), input$table_ui_columns)) |
1162 |
}, |
|
1163 | ! |
options = list( |
1164 | ! |
searching = FALSE, language = list( |
1165 | ! |
zeroRecords = "The brushed area does not contain outlier observations for the currently defined threshold" |
1166 |
), |
|
1167 | ! |
pageLength = input$table_ui_rows |
1168 |
) |
|
1169 |
) |
|
1170 | ||
1171 | ! |
output$total_outliers <- renderUI({ |
1172 | ! |
req(iv_r()$is_valid()) |
1173 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
1174 | ! |
ANL_OUTLIER <- common_code_q()[["ANL_OUTLIER"]] |
1175 | ! |
teal::validate_has_data(ANL, 1) |
1176 | ! |
ANL_OUTLIER_SELECTED <- ANL_OUTLIER[ANL_OUTLIER$is_outlier_selected, ] |
1177 | ! |
tags$h5( |
1178 | ! |
sprintf( |
1179 | ! |
"%s %d / %d [%.02f%%]", |
1180 | ! |
"Total number of outlier(s):", |
1181 | ! |
nrow(ANL_OUTLIER_SELECTED), |
1182 | ! |
nrow(ANL), |
1183 | ! |
100 * nrow(ANL_OUTLIER_SELECTED) / nrow(ANL) |
1184 |
) |
|
1185 |
) |
|
1186 |
}) |
|
1187 | ||
1188 | ! |
output$total_missing <- renderUI({ |
1189 | ! |
if (n_outlier_missing() > 0) { |
1190 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
1191 | ! |
helpText( |
1192 | ! |
sprintf( |
1193 | ! |
"%s %d / %d [%.02f%%]", |
1194 | ! |
"Total number of row(s) with missing values:", |
1195 | ! |
n_outlier_missing(), |
1196 | ! |
nrow(ANL), |
1197 | ! |
100 * (n_outlier_missing()) / nrow(ANL) |
1198 |
) |
|
1199 |
) |
|
1200 |
} |
|
1201 |
}) |
|
1202 | ||
1203 | ! |
output$table_ui_wrap <- renderUI({ |
1204 | ! |
req(iv_r()$is_valid()) |
1205 | ! |
tagList( |
1206 | ! |
teal.widgets::optionalSelectInput( |
1207 | ! |
inputId = ns("table_ui_columns"), |
1208 | ! |
label = "Choose additional columns", |
1209 | ! |
choices = NULL, |
1210 | ! |
selected = NULL, |
1211 | ! |
multiple = TRUE |
1212 |
), |
|
1213 | ! |
tags$h4("Outlier Table"), |
1214 | ! |
teal.widgets::get_dt_rows(ns("table_ui"), ns("table_ui_rows")) |
1215 |
) |
|
1216 |
}) |
|
1217 | ||
1218 | ! |
teal.widgets::verbatim_popup_srv( |
1219 | ! |
id = "rcode", |
1220 | ! |
verbatim_content = reactive(teal.code::get_code(final_q())), |
1221 | ! |
title = "Show R Code for Outlier" |
1222 |
) |
|
1223 | ||
1224 |
### REPORTER |
|
1225 | ! |
if (with_reporter) { |
1226 | ! |
card_fun <- function(comment, label) { |
1227 | ! |
tab_type <- input$tabs |
1228 | ! |
card <- teal::report_card_template( |
1229 | ! |
title = paste0("Outliers - ", tab_type), |
1230 | ! |
label = label, |
1231 | ! |
with_filter = with_filter, |
1232 | ! |
filter_panel_api = filter_panel_api |
1233 |
) |
|
1234 | ! |
categorical_var <- as.vector(merged$anl_input_r()$columns_source$categorical_var) |
1235 | ! |
if (length(categorical_var) > 0) { |
1236 | ! |
summary_table <- common_code_q()[["summary_table"]] |
1237 | ! |
card$append_text("Summary Table", "header3") |
1238 | ! |
card$append_table(summary_table) |
1239 |
} |
|
1240 | ! |
card$append_text("Plot", "header3") |
1241 | ! |
if (tab_type == "Boxplot") { |
1242 | ! |
card$append_plot(boxplot_r(), dim = box_pws$dim()) |
1243 | ! |
} else if (tab_type == "Density Plot") { |
1244 | ! |
card$append_plot(density_plot_r(), dim = density_pws$dim()) |
1245 | ! |
} else if (tab_type == "Cumulative Distribution Plot") { |
1246 | ! |
card$append_plot(cumulative_plot_r(), dim = cum_density_pws$dim()) |
1247 |
} |
|
1248 | ! |
if (!comment == "") { |
1249 | ! |
card$append_text("Comment", "header3") |
1250 | ! |
card$append_text(comment) |
1251 |
} |
|
1252 | ! |
card$append_src(teal.code::get_code(final_q())) |
1253 | ! |
card |
1254 |
} |
|
1255 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
1256 |
} |
|
1257 |
### |
|
1258 |
}) |
|
1259 |
} |
1 |
#' `teal` module: Data table viewer |
|
2 |
#' |
|
3 |
#' Module provides a dynamic and interactive way to view `data.frame`s in a `teal` application. |
|
4 |
#' It uses the `DT` package to display data tables in a paginated, searchable, and sortable format, |
|
5 |
#' which helps to enhance data exploration and analysis. |
|
6 |
#' |
|
7 |
#' The `DT` package has an option `DT.TOJSON_ARGS` to show `Inf` and `NA` in data tables. |
|
8 |
#' Configure the `DT.TOJSON_ARGS` option via |
|
9 |
#' `options(DT.TOJSON_ARGS = list(na = "string"))` before running the module. |
|
10 |
#' Note though that sorting of numeric columns with `NA`/`Inf` will be lexicographic not numerical. |
|
11 |
#' |
|
12 |
#' @inheritParams teal::module |
|
13 |
#' @inheritParams shared_params |
|
14 |
#' @param variables_selected (`named list`) Character vectors of the variables (i.e. columns) |
|
15 |
#' which should be initially shown for each dataset. |
|
16 |
#' Names of list elements should correspond to the names of the datasets available in the app. |
|
17 |
#' If no entry is specified for a dataset, the first six variables from that |
|
18 |
#' dataset will initially be shown. |
|
19 |
#' @param datasets_selected (`character`) A vector of datasets which should be |
|
20 |
#' shown and in what order. Names in the vector have to correspond with datasets names. |
|
21 |
#' If vector of `length == 0` (default) then all datasets are shown. |
|
22 |
#' Note: Only datasets of the `data.frame` class are compatible. |
|
23 |
#' @param dt_args (`named list`) Additional arguments to be passed to [DT::datatable()] |
|
24 |
#' (must not include `data` or `options`). |
|
25 |
#' @param dt_options (`named list`) The `options` argument to `DT::datatable`. By default |
|
26 |
#' `list(searching = FALSE, pageLength = 30, lengthMenu = c(5, 15, 30, 100), scrollX = TRUE)` |
|
27 |
#' @param server_rendering (`logical`) should the data table be rendered server side |
|
28 |
#' (see `server` argument of [DT::renderDataTable()]) |
|
29 |
#' |
|
30 |
#' @inherit shared_params return |
|
31 |
#' |
|
32 |
#' @examplesShinylive |
|
33 |
#' library(teal.modules.general) |
|
34 |
#' interactive <- function() TRUE |
|
35 |
#' {{ next_example }} |
|
36 |
#' @examples |
|
37 |
#' # general data example |
|
38 |
#' data <- teal_data() |
|
39 |
#' data <- within(data, { |
|
40 |
#' require(nestcolor) |
|
41 |
#' iris <- iris |
|
42 |
#' }) |
|
43 |
#' |
|
44 |
#' app <- init( |
|
45 |
#' data = data, |
|
46 |
#' modules = modules( |
|
47 |
#' tm_data_table( |
|
48 |
#' variables_selected = list( |
|
49 |
#' iris = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species") |
|
50 |
#' ), |
|
51 |
#' dt_args = list(caption = "IRIS Table Caption") |
|
52 |
#' ) |
|
53 |
#' ) |
|
54 |
#' ) |
|
55 |
#' if (interactive()) { |
|
56 |
#' shinyApp(app$ui, app$server) |
|
57 |
#' } |
|
58 |
#' |
|
59 |
#' @examplesShinylive |
|
60 |
#' library(teal.modules.general) |
|
61 |
#' interactive <- function() TRUE |
|
62 |
#' {{ next_example }} |
|
63 |
#' @examples |
|
64 |
#' # CDISC data example |
|
65 |
#' data <- teal_data() |
|
66 |
#' data <- within(data, { |
|
67 |
#' require(nestcolor) |
|
68 |
#' ADSL <- rADSL |
|
69 |
#' }) |
|
70 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
71 |
#' |
|
72 |
#' app <- init( |
|
73 |
#' data = data, |
|
74 |
#' modules = modules( |
|
75 |
#' tm_data_table( |
|
76 |
#' variables_selected = list(ADSL = c("STUDYID", "USUBJID", "SUBJID", "SITEID", "AGE", "SEX")), |
|
77 |
#' dt_args = list(caption = "ADSL Table Caption") |
|
78 |
#' ) |
|
79 |
#' ) |
|
80 |
#' ) |
|
81 |
#' if (interactive()) { |
|
82 |
#' shinyApp(app$ui, app$server) |
|
83 |
#' } |
|
84 |
#' |
|
85 |
#' @export |
|
86 |
#' |
|
87 |
tm_data_table <- function(label = "Data Table", |
|
88 |
variables_selected = list(), |
|
89 |
datasets_selected = character(0), |
|
90 |
dt_args = list(), |
|
91 |
dt_options = list( |
|
92 |
searching = FALSE, |
|
93 |
pageLength = 30, |
|
94 |
lengthMenu = c(5, 15, 30, 100), |
|
95 |
scrollX = TRUE |
|
96 |
), |
|
97 |
server_rendering = FALSE, |
|
98 |
pre_output = NULL, |
|
99 |
post_output = NULL) { |
|
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 | ||
115 | ! |
checkmate::assert_character(datasets_selected, min.len = 0, min.chars = 1) |
116 | ! |
checkmate::assert( |
117 | ! |
checkmate::check_list(dt_args, len = 0), |
118 | ! |
checkmate::check_subset(names(dt_args), choices = names(formals(DT::datatable))) |
119 |
) |
|
120 | ! |
checkmate::assert_list(dt_options, names = "named") |
121 | ! |
checkmate::assert_flag(server_rendering) |
122 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
123 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
124 |
# End of assertions |
|
125 | ||
126 | ! |
ans <- module( |
127 | ! |
label, |
128 | ! |
server = srv_page_data_table, |
129 | ! |
ui = ui_page_data_table, |
130 | ! |
datanames = if (length(datasets_selected) == 0) "all" else datasets_selected, |
131 | ! |
server_args = list( |
132 | ! |
variables_selected = variables_selected, |
133 | ! |
datasets_selected = datasets_selected, |
134 | ! |
dt_args = dt_args, |
135 | ! |
dt_options = dt_options, |
136 | ! |
server_rendering = server_rendering |
137 |
), |
|
138 | ! |
ui_args = list( |
139 | ! |
pre_output = pre_output, |
140 | ! |
post_output = post_output |
141 |
) |
|
142 |
) |
|
143 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
144 | ! |
ans |
145 |
} |
|
146 | ||
147 |
# UI page module |
|
148 |
ui_page_data_table <- function(id, |
|
149 |
pre_output = NULL, |
|
150 |
post_output = NULL) { |
|
151 | ! |
ns <- NS(id) |
152 | ||
153 | ! |
tagList( |
154 | ! |
include_css_files("custom"), |
155 | ! |
teal.widgets::standard_layout( |
156 | ! |
output = teal.widgets::white_small_well( |
157 | ! |
fluidRow( |
158 | ! |
column( |
159 | ! |
width = 12, |
160 | ! |
checkboxInput( |
161 | ! |
ns("if_distinct"), |
162 | ! |
"Show only distinct rows:", |
163 | ! |
value = FALSE |
164 |
) |
|
165 |
) |
|
166 |
), |
|
167 | ! |
fluidRow( |
168 | ! |
class = "mb-8", |
169 | ! |
column( |
170 | ! |
width = 12, |
171 | ! |
uiOutput(ns("dataset_table")) |
172 |
) |
|
173 |
) |
|
174 |
), |
|
175 | ! |
pre_output = pre_output, |
176 | ! |
post_output = post_output |
177 |
) |
|
178 |
) |
|
179 |
} |
|
180 | ||
181 |
# Server page module |
|
182 |
srv_page_data_table <- function(id, |
|
183 |
data, |
|
184 |
datasets_selected, |
|
185 |
variables_selected, |
|
186 |
dt_args, |
|
187 |
dt_options, |
|
188 |
server_rendering) { |
|
189 | ! |
checkmate::assert_class(data, "reactive") |
190 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
191 | ! |
moduleServer(id, function(input, output, session) { |
192 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
193 | ||
194 | ! |
if_filtered <- reactive(as.logical(input$if_filtered)) |
195 | ! |
if_distinct <- reactive(as.logical(input$if_distinct)) |
196 | ||
197 | ! |
datanames <- isolate(names(data())) |
198 | ! |
datanames <- Filter(function(name) { |
199 | ! |
is.data.frame(isolate(data())[[name]]) |
200 | ! |
}, datanames) |
201 | ||
202 | ! |
if (!identical(datasets_selected, character(0))) { |
203 | ! |
checkmate::assert_subset(datasets_selected, datanames) |
204 | ! |
datanames <- datasets_selected |
205 |
} |
|
206 | ||
207 | ! |
output$dataset_table <- renderUI({ |
208 | ! |
do.call( |
209 | ! |
tabsetPanel, |
210 | ! |
c( |
211 | ! |
list(id = session$ns("dataname_tab")), |
212 | ! |
lapply( |
213 | ! |
datanames, |
214 | ! |
function(x) { |
215 | ! |
dataset <- isolate(data()[[x]]) |
216 | ! |
choices <- names(dataset) |
217 | ! |
labels <- vapply( |
218 | ! |
dataset, |
219 | ! |
function(x) ifelse(is.null(attr(x, "label")), "", attr(x, "label")), |
220 | ! |
character(1) |
221 |
) |
|
222 | ! |
names(choices) <- ifelse( |
223 | ! |
is.na(labels) | labels == "", |
224 | ! |
choices, |
225 | ! |
paste(choices, labels, sep = ": ") |
226 |
) |
|
227 | ! |
variables_selected <- if (!is.null(variables_selected[[x]])) { |
228 | ! |
variables_selected[[x]] |
229 |
} else { |
|
230 | ! |
utils::head(choices) |
231 |
} |
|
232 | ! |
tabPanel( |
233 | ! |
title = x, |
234 | ! |
column( |
235 | ! |
width = 12, |
236 | ! |
div( |
237 | ! |
class = "mt-4", |
238 | ! |
ui_data_table( |
239 | ! |
id = session$ns(x), |
240 | ! |
choices = choices, |
241 | ! |
selected = variables_selected |
242 |
) |
|
243 |
) |
|
244 |
) |
|
245 |
) |
|
246 |
} |
|
247 |
) |
|
248 |
) |
|
249 |
) |
|
250 |
}) |
|
251 | ||
252 | ! |
lapply( |
253 | ! |
datanames, |
254 | ! |
function(x) { |
255 | ! |
srv_data_table( |
256 | ! |
id = x, |
257 | ! |
data = data, |
258 | ! |
dataname = x, |
259 | ! |
if_filtered = if_filtered, |
260 | ! |
if_distinct = if_distinct, |
261 | ! |
dt_args = dt_args, |
262 | ! |
dt_options = dt_options, |
263 | ! |
server_rendering = server_rendering |
264 |
) |
|
265 |
} |
|
266 |
) |
|
267 |
}) |
|
268 |
} |
|
269 | ||
270 |
# UI function for the data_table module |
|
271 |
ui_data_table <- function(id, |
|
272 |
choices, |
|
273 |
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 | ! |
output$data_table <- DT::renderDataTable(server = server_rendering, { |
318 | ! |
teal::validate_inputs(iv) |
319 | ||
320 | ! |
df <- data()[[dataname]] |
321 | ! |
variables <- input$variables |
322 | ||
323 | ! |
teal::validate_has_data(df, min_nrow = 1L, msg = paste("data", dataname, "is empty")) |
324 | ||
325 | ! |
dataframe_selected <- if (if_distinct()) { |
326 | ! |
dplyr::count(df, dplyr::across(dplyr::all_of(variables))) |
327 |
} else { |
|
328 | ! |
df[variables] |
329 |
} |
|
330 | ||
331 | ! |
dt_args$options <- dt_options |
332 | ! |
if (!is.null(input$dt_rows)) { |
333 | ! |
dt_args$options$pageLength <- input$dt_rows |
334 |
} |
|
335 | ! |
dt_args$data <- dataframe_selected |
336 | ||
337 | ! |
do.call(DT::datatable, dt_args) |
338 |
}) |
|
339 |
}) |
|
340 |
} |
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 |
#' @examplesShinylive |
|
22 |
#' library(teal.modules.general) |
|
23 |
#' interactive <- function() TRUE |
|
24 |
#' {{ next_example }} |
|
25 |
#' @examplesIf require("lattice", quietly = TRUE) |
|
26 |
#' # general data example |
|
27 |
#' data <- teal_data() |
|
28 |
#' data <- within(data, { |
|
29 |
#' countries <- data.frame( |
|
30 |
#' id = c("DE", "FR", "IT", "ES", "PT", "GR", "NL", "BE", "LU", "AT"), |
|
31 |
#' government = factor( |
|
32 |
#' c(2, 2, 2, 1, 2, 2, 1, 1, 1, 2), |
|
33 |
#' labels = c("Monarchy", "Republic") |
|
34 |
#' ), |
|
35 |
#' language_family = factor( |
|
36 |
#' c(1, 3, 3, 3, 3, 2, 1, 1, 3, 1), |
|
37 |
#' labels = c("Germanic", "Hellenic", "Romance") |
|
38 |
#' ), |
|
39 |
#' population = c(83, 67, 60, 47, 10, 11, 17, 11, 0.6, 9), |
|
40 |
#' area = c(357, 551, 301, 505, 92, 132, 41, 30, 2.6, 83), |
|
41 |
#' gdp = c(3.4, 2.7, 2.1, 1.4, 0.3, 0.2, 0.7, 0.5, 0.1, 0.4), |
|
42 |
#' debt = c(2.1, 2.3, 2.4, 2.6, 2.3, 2.4, 2.3, 2.4, 2.3, 2.4) |
|
43 |
#' ) |
|
44 |
#' sales <- data.frame( |
|
45 |
#' id = 1:50, |
|
46 |
#' country_id = sample( |
|
47 |
#' c("DE", "FR", "IT", "ES", "PT", "GR", "NL", "BE", "LU", "AT"), |
|
48 |
#' size = 50, |
|
49 |
#' replace = TRUE |
|
50 |
#' ), |
|
51 |
#' year = sort(sample(2010:2020, 50, replace = TRUE)), |
|
52 |
#' venue = sample(c("small", "medium", "large", "online"), 50, replace = TRUE), |
|
53 |
#' cancelled = sample(c(TRUE, FALSE), 50, replace = TRUE), |
|
54 |
#' quantity = rnorm(50, 100, 20), |
|
55 |
#' costs = rnorm(50, 80, 20), |
|
56 |
#' profit = rnorm(50, 20, 10) |
|
57 |
#' ) |
|
58 |
#' }) |
|
59 |
#' join_keys(data) <- join_keys( |
|
60 |
#' join_key("countries", "countries", "id"), |
|
61 |
#' join_key("sales", "sales", "id"), |
|
62 |
#' join_key("countries", "sales", c("id" = "country_id")) |
|
63 |
#' ) |
|
64 |
#' |
|
65 |
#' app <- init( |
|
66 |
#' data = data, |
|
67 |
#' modules = modules( |
|
68 |
#' tm_g_scatterplotmatrix( |
|
69 |
#' label = "Scatterplot matrix", |
|
70 |
#' variables = list( |
|
71 |
#' data_extract_spec( |
|
72 |
#' dataname = "countries", |
|
73 |
#' select = select_spec( |
|
74 |
#' label = "Select variables:", |
|
75 |
#' choices = variable_choices(data[["countries"]]), |
|
76 |
#' selected = c("area", "gdp", "debt"), |
|
77 |
#' multiple = TRUE, |
|
78 |
#' ordered = TRUE, |
|
79 |
#' fixed = FALSE |
|
80 |
#' ) |
|
81 |
#' ), |
|
82 |
#' data_extract_spec( |
|
83 |
#' dataname = "sales", |
|
84 |
#' filter = filter_spec( |
|
85 |
#' label = "Select variable:", |
|
86 |
#' vars = "country_id", |
|
87 |
#' choices = value_choices(data[["sales"]], "country_id"), |
|
88 |
#' selected = c("DE", "FR", "IT", "ES", "PT", "GR", "NL", "BE", "LU", "AT"), |
|
89 |
#' multiple = TRUE |
|
90 |
#' ), |
|
91 |
#' select = select_spec( |
|
92 |
#' label = "Select variables:", |
|
93 |
#' choices = variable_choices(data[["sales"]], c("quantity", "costs", "profit")), |
|
94 |
#' selected = c("quantity", "costs", "profit"), |
|
95 |
#' multiple = TRUE, |
|
96 |
#' ordered = TRUE, |
|
97 |
#' fixed = FALSE |
|
98 |
#' ) |
|
99 |
#' ) |
|
100 |
#' ) |
|
101 |
#' ) |
|
102 |
#' ) |
|
103 |
#' ) |
|
104 |
#' if (interactive()) { |
|
105 |
#' shinyApp(app$ui, app$server) |
|
106 |
#' } |
|
107 |
#' |
|
108 |
#' @examplesShinylive |
|
109 |
#' library(teal.modules.general) |
|
110 |
#' interactive <- function() TRUE |
|
111 |
#' {{ next_example }} |
|
112 |
#' @examplesIf require("lattice", quietly = TRUE) |
|
113 |
#' # CDISC data example |
|
114 |
#' data <- teal_data() |
|
115 |
#' data <- within(data, { |
|
116 |
#' ADSL <- rADSL |
|
117 |
#' ADRS <- rADRS |
|
118 |
#' }) |
|
119 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
120 |
#' |
|
121 |
#' app <- init( |
|
122 |
#' data = data, |
|
123 |
#' modules = modules( |
|
124 |
#' tm_g_scatterplotmatrix( |
|
125 |
#' label = "Scatterplot matrix", |
|
126 |
#' variables = list( |
|
127 |
#' data_extract_spec( |
|
128 |
#' dataname = "ADSL", |
|
129 |
#' select = select_spec( |
|
130 |
#' label = "Select variables:", |
|
131 |
#' choices = variable_choices(data[["ADSL"]]), |
|
132 |
#' selected = c("AGE", "RACE", "SEX"), |
|
133 |
#' multiple = TRUE, |
|
134 |
#' ordered = TRUE, |
|
135 |
#' fixed = FALSE |
|
136 |
#' ) |
|
137 |
#' ), |
|
138 |
#' data_extract_spec( |
|
139 |
#' dataname = "ADRS", |
|
140 |
#' filter = filter_spec( |
|
141 |
#' label = "Select endpoints:", |
|
142 |
#' vars = c("PARAMCD", "AVISIT"), |
|
143 |
#' choices = value_choices(data[["ADRS"]], c("PARAMCD", "AVISIT"), c("PARAM", "AVISIT")), |
|
144 |
#' selected = "INVET - END OF INDUCTION", |
|
145 |
#' multiple = TRUE |
|
146 |
#' ), |
|
147 |
#' select = select_spec( |
|
148 |
#' label = "Select variables:", |
|
149 |
#' choices = variable_choices(data[["ADRS"]]), |
|
150 |
#' selected = c("AGE", "AVAL", "ADY"), |
|
151 |
#' multiple = TRUE, |
|
152 |
#' ordered = TRUE, |
|
153 |
#' fixed = FALSE |
|
154 |
#' ) |
|
155 |
#' ) |
|
156 |
#' ) |
|
157 |
#' ) |
|
158 |
#' ) |
|
159 |
#' ) |
|
160 |
#' if (interactive()) { |
|
161 |
#' shinyApp(app$ui, app$server) |
|
162 |
#' } |
|
163 |
#' |
|
164 |
#' @export |
|
165 |
#' |
|
166 |
tm_g_scatterplotmatrix <- function(label = "Scatterplot Matrix", |
|
167 |
variables, |
|
168 |
plot_height = c(600, 200, 2000), |
|
169 |
plot_width = NULL, |
|
170 |
pre_output = NULL, |
|
171 |
post_output = NULL) { |
|
172 | ! |
message("Initializing tm_g_scatterplotmatrix") |
173 | ||
174 |
# Requires Suggested packages |
|
175 | ! |
if (!requireNamespace("lattice", quietly = TRUE)) { |
176 | ! |
stop("Cannot load lattice - please install the package or restart your session.") |
177 |
} |
|
178 | ||
179 |
# Normalize the parameters |
|
180 | ! |
if (inherits(variables, "data_extract_spec")) variables <- list(variables) |
181 | ||
182 |
# Start of assertions |
|
183 | ! |
checkmate::assert_string(label) |
184 | ! |
checkmate::assert_list(variables, types = "data_extract_spec") |
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 |
# End of assertions |
|
197 | ||
198 |
# Make UI args |
|
199 | ! |
args <- as.list(environment()) |
200 | ||
201 | ! |
ans <- module( |
202 | ! |
label = label, |
203 | ! |
server = srv_g_scatterplotmatrix, |
204 | ! |
ui = ui_g_scatterplotmatrix, |
205 | ! |
ui_args = args, |
206 | ! |
server_args = list(variables = variables, plot_height = plot_height, plot_width = plot_width), |
207 | ! |
datanames = teal.transform::get_extract_datanames(variables) |
208 |
) |
|
209 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
210 | ! |
ans |
211 |
} |
|
212 | ||
213 |
# UI function for the scatterplot matrix module |
|
214 |
ui_g_scatterplotmatrix <- function(id, ...) { |
|
215 | ! |
args <- list(...) |
216 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$variables) |
217 | ! |
ns <- NS(id) |
218 | ! |
teal.widgets::standard_layout( |
219 | ! |
output = teal.widgets::white_small_well( |
220 | ! |
textOutput(ns("message")), |
221 | ! |
tags$br(), |
222 | ! |
teal.widgets::plot_with_settings_ui(id = ns("myplot")) |
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(args$variables), |
230 | ! |
teal.transform::data_extract_ui( |
231 | ! |
id = ns("variables"), |
232 | ! |
label = "Variables", |
233 | ! |
data_extract_spec = args$variables, |
234 | ! |
is_single_dataset = is_single_dataset_value |
235 |
), |
|
236 | ! |
tags$hr(), |
237 | ! |
teal.widgets::panel_group( |
238 | ! |
teal.widgets::panel_item( |
239 | ! |
title = "Plot settings", |
240 | ! |
sliderInput( |
241 | ! |
ns("alpha"), "Opacity:", |
242 | ! |
min = 0, max = 1, |
243 | ! |
step = .05, value = .5, ticks = FALSE |
244 |
), |
|
245 | ! |
sliderInput( |
246 | ! |
ns("cex"), "Points size:", |
247 | ! |
min = 0.2, max = 3, |
248 | ! |
step = .05, value = .65, ticks = FALSE |
249 |
), |
|
250 | ! |
checkboxInput(ns("cor"), "Add Correlation", value = FALSE), |
251 | ! |
radioButtons( |
252 | ! |
ns("cor_method"), "Select Correlation Method", |
253 | ! |
choiceNames = c("Pearson", "Kendall", "Spearman"), |
254 | ! |
choiceValues = c("pearson", "kendall", "spearman"), |
255 | ! |
inline = TRUE |
256 |
), |
|
257 | ! |
checkboxInput(ns("cor_na_omit"), "Omit Missing Values", value = TRUE) |
258 |
) |
|
259 |
) |
|
260 |
), |
|
261 | ! |
forms = tagList( |
262 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
263 |
), |
|
264 | ! |
pre_output = args$pre_output, |
265 | ! |
post_output = args$post_output |
266 |
) |
|
267 |
} |
|
268 | ||
269 |
# Server function for the scatterplot matrix module |
|
270 |
srv_g_scatterplotmatrix <- function(id, data, reporter, filter_panel_api, variables, plot_height, plot_width) { |
|
271 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
272 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
273 | ! |
checkmate::assert_class(data, "reactive") |
274 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
275 | ! |
moduleServer(id, function(input, output, session) { |
276 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
277 | ||
278 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
279 | ! |
data_extract = list(variables = variables), |
280 | ! |
datasets = data, |
281 | ! |
select_validation_rule = list( |
282 | ! |
variables = ~ if (length(.) <= 1) "Please select at least 2 columns." |
283 |
) |
|
284 |
) |
|
285 | ||
286 | ! |
iv_r <- reactive({ |
287 | ! |
iv <- shinyvalidate::InputValidator$new() |
288 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
289 |
}) |
|
290 | ||
291 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
292 | ! |
datasets = data, |
293 | ! |
selector_list = selector_list |
294 |
) |
|
295 | ||
296 | ! |
anl_merged_q <- reactive({ |
297 | ! |
req(anl_merged_input()) |
298 | ! |
data() %>% |
299 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
300 |
}) |
|
301 | ||
302 | ! |
merged <- list( |
303 | ! |
anl_input_r = anl_merged_input, |
304 | ! |
anl_q_r = anl_merged_q |
305 |
) |
|
306 | ||
307 |
# plot |
|
308 | ! |
output_q <- reactive({ |
309 | ! |
teal::validate_inputs(iv_r()) |
310 | ||
311 | ! |
qenv <- merged$anl_q_r() |
312 | ! |
ANL <- qenv[["ANL"]] |
313 | ||
314 | ! |
cols_names <- merged$anl_input_r()$columns_source$variables |
315 | ! |
alpha <- input$alpha |
316 | ! |
cex <- input$cex |
317 | ! |
add_cor <- input$cor |
318 | ! |
cor_method <- input$cor_method |
319 | ! |
cor_na_omit <- input$cor_na_omit |
320 | ||
321 | ! |
cor_na_action <- if (isTruthy(cor_na_omit)) { |
322 | ! |
"na.omit" |
323 |
} else { |
|
324 | ! |
"na.fail" |
325 |
} |
|
326 | ||
327 | ! |
teal::validate_has_data(ANL, 10) |
328 | ! |
teal::validate_has_data(ANL[, cols_names, drop = FALSE], 10, complete = TRUE, allow_inf = FALSE) |
329 | ||
330 |
# get labels and proper variable names |
|
331 | ! |
varnames <- varname_w_label(cols_names, ANL, wrap_width = 20) |
332 | ||
333 |
# check character columns. If any, then those are converted to factors |
|
334 | ! |
check_char <- vapply(ANL[, cols_names], is.character, logical(1)) |
335 | ! |
if (any(check_char)) { |
336 | ! |
qenv <- teal.code::eval_code( |
337 | ! |
qenv, |
338 | ! |
substitute( |
339 | ! |
expr = ANL <- ANL[, cols_names] %>% |
340 | ! |
dplyr::mutate_if(is.character, as.factor) %>% |
341 | ! |
droplevels(), |
342 | ! |
env = list(cols_names = cols_names) |
343 |
) |
|
344 |
) |
|
345 |
} else { |
|
346 | ! |
qenv <- teal.code::eval_code( |
347 | ! |
qenv, |
348 | ! |
substitute( |
349 | ! |
expr = ANL <- ANL[, cols_names] %>% |
350 | ! |
droplevels(), |
351 | ! |
env = list(cols_names = cols_names) |
352 |
) |
|
353 |
) |
|
354 |
} |
|
355 | ||
356 | ||
357 |
# create plot |
|
358 | ! |
if (add_cor) { |
359 | ! |
shinyjs::show("cor_method") |
360 | ! |
shinyjs::show("cor_use") |
361 | ! |
shinyjs::show("cor_na_omit") |
362 | ||
363 | ! |
qenv <- teal.code::eval_code( |
364 | ! |
qenv, |
365 | ! |
substitute( |
366 | ! |
expr = { |
367 | ! |
g <- lattice::splom( |
368 | ! |
ANL, |
369 | ! |
varnames = varnames_value, |
370 | ! |
panel = function(x, y, ...) { |
371 | ! |
lattice::panel.splom(x = x, y = y, ...) |
372 | ! |
cpl <- lattice::current.panel.limits() |
373 | ! |
lattice::panel.text( |
374 | ! |
mean(cpl$xlim), |
375 | ! |
mean(cpl$ylim), |
376 | ! |
get_scatterplotmatrix_stats( |
377 | ! |
x, |
378 | ! |
y, |
379 | ! |
.f = stats::cor.test, |
380 | ! |
.f_args = list(method = cor_method, na.action = cor_na_action) |
381 |
), |
|
382 | ! |
alpha = 0.6, |
383 | ! |
fontsize = 18, |
384 | ! |
fontface = "bold" |
385 |
) |
|
386 |
}, |
|
387 | ! |
pch = 16, |
388 | ! |
alpha = alpha_value, |
389 | ! |
cex = cex_value |
390 |
) |
|
391 | ! |
print(g) |
392 |
}, |
|
393 | ! |
env = list( |
394 | ! |
varnames_value = varnames, |
395 | ! |
cor_method = cor_method, |
396 | ! |
cor_na_action = cor_na_action, |
397 | ! |
alpha_value = alpha, |
398 | ! |
cex_value = cex |
399 |
) |
|
400 |
) |
|
401 |
) |
|
402 |
} else { |
|
403 | ! |
shinyjs::hide("cor_method") |
404 | ! |
shinyjs::hide("cor_use") |
405 | ! |
shinyjs::hide("cor_na_omit") |
406 | ! |
qenv <- teal.code::eval_code( |
407 | ! |
qenv, |
408 | ! |
substitute( |
409 | ! |
expr = { |
410 | ! |
g <- lattice::splom(ANL, varnames = varnames_value, pch = 16, alpha = alpha_value, cex = cex_value) |
411 | ! |
g |
412 |
}, |
|
413 | ! |
env = list(varnames_value = varnames, alpha_value = alpha, cex_value = cex) |
414 |
) |
|
415 |
) |
|
416 |
} |
|
417 | ! |
qenv |
418 |
}) |
|
419 | ||
420 | ! |
plot_r <- reactive(output_q()[["g"]]) |
421 | ||
422 |
# Insert the plot into a plot_with_settings module |
|
423 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
424 | ! |
id = "myplot", |
425 | ! |
plot_r = plot_r, |
426 | ! |
height = plot_height, |
427 | ! |
width = plot_width |
428 |
) |
|
429 | ||
430 |
# show a message if conversion to factors took place |
|
431 | ! |
output$message <- renderText({ |
432 | ! |
req(iv_r()$is_valid()) |
433 | ! |
req(selector_list()$variables()) |
434 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
435 | ! |
cols_names <- unique(unname(do.call(c, merged$anl_input_r()$columns_source))) |
436 | ! |
check_char <- vapply(ANL[, cols_names], is.character, logical(1)) |
437 | ! |
if (any(check_char)) { |
438 | ! |
is_single <- sum(check_char) == 1 |
439 | ! |
paste( |
440 | ! |
"Character", |
441 | ! |
ifelse(is_single, "variable", "variables"), |
442 | ! |
paste0("(", paste(cols_names[check_char], collapse = ", "), ")"), |
443 | ! |
ifelse(is_single, "was", "were"), |
444 | ! |
"converted to", |
445 | ! |
ifelse(is_single, "factor.", "factors.") |
446 |
) |
|
447 |
} else { |
|
448 |
"" |
|
449 |
} |
|
450 |
}) |
|
451 | ||
452 | ! |
teal.widgets::verbatim_popup_srv( |
453 | ! |
id = "rcode", |
454 | ! |
verbatim_content = reactive(teal.code::get_code(output_q())), |
455 | ! |
title = "Show R Code for Scatterplotmatrix" |
456 |
) |
|
457 | ||
458 |
### REPORTER |
|
459 | ! |
if (with_reporter) { |
460 | ! |
card_fun <- function(comment, label) { |
461 | ! |
card <- teal::report_card_template( |
462 | ! |
title = "Scatter Plot Matrix", |
463 | ! |
label = label, |
464 | ! |
with_filter = with_filter, |
465 | ! |
filter_panel_api = filter_panel_api |
466 |
) |
|
467 | ! |
card$append_text("Plot", "header3") |
468 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
469 | ! |
if (!comment == "") { |
470 | ! |
card$append_text("Comment", "header3") |
471 | ! |
card$append_text(comment) |
472 |
} |
|
473 | ! |
card$append_src(teal.code::get_code(output_q())) |
474 | ! |
card |
475 |
} |
|
476 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
477 |
} |
|
478 |
### |
|
479 |
}) |
|
480 |
} |
|
481 | ||
482 |
#' Get stats for x-y pairs in scatterplot matrix |
|
483 |
#' |
|
484 |
#' Uses [stats::cor.test()] per default for all numerical input variables and converts results |
|
485 |
#' to character vector. |
|
486 |
#' Could be extended if different stats for different variable types are needed. |
|
487 |
#' Meant to be called from [lattice::panel.text()]. |
|
488 |
#' |
|
489 |
#' Presently we need to use a formula input for `stats::cor.test` because |
|
490 |
#' `na.fail` only gets evaluated when a formula is passed (see below). |
|
491 |
#' ``` |
|
492 |
#' x = c(1,3,5,7,NA) |
|
493 |
#' y = c(3,6,7,8,1) |
|
494 |
#' stats::cor.test(x, y, na.action = "na.fail") |
|
495 |
#' stats::cor.test(~ x + y, na.action = "na.fail") |
|
496 |
#' ``` |
|
497 |
#' |
|
498 |
#' @param x,y (`numeric`) vectors of data values. `x` and `y` must have the same length. |
|
499 |
#' @param .f (`function`) function that accepts x and y as formula input `~ x + y`. |
|
500 |
#' Default `stats::cor.test`. |
|
501 |
#' @param .f_args (`list`) of arguments to be passed to `.f`. |
|
502 |
#' @param round_stat (`integer(1)`) optional, number of decimal places to use when rounding the estimate. |
|
503 |
#' @param round_pval (`integer(1)`) optional, number of decimal places to use when rounding the p-value. |
|
504 |
#' |
|
505 |
#' @return Character with stats. For [stats::cor.test()] correlation coefficient and p-value. |
|
506 |
#' |
|
507 |
#' @examples |
|
508 |
#' set.seed(1) |
|
509 |
#' x <- runif(25, 0, 1) |
|
510 |
#' y <- runif(25, 0, 1) |
|
511 |
#' x[c(3, 10, 18)] <- NA |
|
512 |
#' |
|
513 |
#' get_scatterplotmatrix_stats(x, y, .f = stats::cor.test, .f_args = list(method = "pearson")) |
|
514 |
#' get_scatterplotmatrix_stats(x, y, .f = stats::cor.test, .f_args = list( |
|
515 |
#' method = "pearson", |
|
516 |
#' na.action = na.fail |
|
517 |
#' )) |
|
518 |
#' |
|
519 |
#' @export |
|
520 |
#' |
|
521 |
get_scatterplotmatrix_stats <- function(x, y, |
|
522 |
.f = stats::cor.test, |
|
523 |
.f_args = list(), |
|
524 |
round_stat = 2, |
|
525 |
round_pval = 4) { |
|
526 | 6x |
if (is.numeric(x) && is.numeric(y)) { |
527 | 3x |
stat <- tryCatch(do.call(.f, c(list(~ x + y), .f_args)), error = function(e) NA) |
528 | ||
529 | 3x |
if (anyNA(stat)) { |
530 | 1x |
return("NA") |
531 | 2x |
} else if (all(c("estimate", "p.value") %in% names(stat))) { |
532 | 2x |
return(paste( |
533 | 2x |
c( |
534 | 2x |
paste0(names(stat$estimate), ":", round(stat$estimate, round_stat)), |
535 | 2x |
paste0("P:", round(stat$p.value, round_pval)) |
536 |
), |
|
537 | 2x |
collapse = "\n" |
538 |
)) |
|
539 |
} else { |
|
540 | ! |
stop("function not supported") |
541 |
} |
|
542 |
} else { |
|
543 | 3x |
if ("method" %in% names(.f_args)) { |
544 | 3x |
if (.f_args$method == "pearson") { |
545 | 1x |
return("cor:-") |
546 |
} |
|
547 | 2x |
if (.f_args$method == "kendall") { |
548 | 1x |
return("tau:-") |
549 |
} |
|
550 | 1x |
if (.f_args$method == "spearman") { |
551 | 1x |
return("rho:-") |
552 |
} |
|
553 |
} |
|
554 | ! |
return("-") |
555 |
} |
|
556 |
} |
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 |
#' @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 |
#' require(nestcolor) |
|
51 |
#' mtcars <- mtcars |
|
52 |
#' for (v in c("cyl", "vs", "am", "gear")) { |
|
53 |
#' mtcars[[v]] <- as.factor(mtcars[[v]]) |
|
54 |
#' } |
|
55 |
#' }) |
|
56 |
#' |
|
57 |
#' app <- init( |
|
58 |
#' data = data, |
|
59 |
#' modules = modules( |
|
60 |
#' tm_g_response( |
|
61 |
#' label = "Response Plots", |
|
62 |
#' response = data_extract_spec( |
|
63 |
#' dataname = "mtcars", |
|
64 |
#' select = select_spec( |
|
65 |
#' label = "Select variable:", |
|
66 |
#' choices = variable_choices(data[["mtcars"]], c("cyl", "gear")), |
|
67 |
#' selected = "cyl", |
|
68 |
#' multiple = FALSE, |
|
69 |
#' fixed = FALSE |
|
70 |
#' ) |
|
71 |
#' ), |
|
72 |
#' x = data_extract_spec( |
|
73 |
#' dataname = "mtcars", |
|
74 |
#' select = select_spec( |
|
75 |
#' label = "Select variable:", |
|
76 |
#' choices = variable_choices(data[["mtcars"]], c("vs", "am")), |
|
77 |
#' selected = "vs", |
|
78 |
#' multiple = FALSE, |
|
79 |
#' fixed = FALSE |
|
80 |
#' ) |
|
81 |
#' ) |
|
82 |
#' ) |
|
83 |
#' ) |
|
84 |
#' ) |
|
85 |
#' if (interactive()) { |
|
86 |
#' shinyApp(app$ui, app$server) |
|
87 |
#' } |
|
88 |
#' |
|
89 |
#' @examplesShinylive |
|
90 |
#' library(teal.modules.general) |
|
91 |
#' interactive <- function() TRUE |
|
92 |
#' {{ next_example }} |
|
93 |
#' @examples |
|
94 |
#' # CDISC data example |
|
95 |
#' data <- teal_data() |
|
96 |
#' data <- within(data, { |
|
97 |
#' require(nestcolor) |
|
98 |
#' ADSL <- rADSL |
|
99 |
#' }) |
|
100 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
101 |
#' |
|
102 |
#' app <- init( |
|
103 |
#' data = data, |
|
104 |
#' modules = modules( |
|
105 |
#' tm_g_response( |
|
106 |
#' label = "Response Plots", |
|
107 |
#' response = data_extract_spec( |
|
108 |
#' dataname = "ADSL", |
|
109 |
#' select = select_spec( |
|
110 |
#' label = "Select variable:", |
|
111 |
#' choices = variable_choices(data[["ADSL"]], c("BMRKR2", "COUNTRY")), |
|
112 |
#' selected = "BMRKR2", |
|
113 |
#' multiple = FALSE, |
|
114 |
#' fixed = FALSE |
|
115 |
#' ) |
|
116 |
#' ), |
|
117 |
#' x = data_extract_spec( |
|
118 |
#' dataname = "ADSL", |
|
119 |
#' select = select_spec( |
|
120 |
#' label = "Select variable:", |
|
121 |
#' choices = variable_choices(data[["ADSL"]], c("SEX", "RACE")), |
|
122 |
#' selected = "RACE", |
|
123 |
#' multiple = FALSE, |
|
124 |
#' fixed = FALSE |
|
125 |
#' ) |
|
126 |
#' ) |
|
127 |
#' ) |
|
128 |
#' ) |
|
129 |
#' ) |
|
130 |
#' if (interactive()) { |
|
131 |
#' shinyApp(app$ui, app$server) |
|
132 |
#' } |
|
133 |
#' |
|
134 |
#' @export |
|
135 |
#' |
|
136 |
tm_g_response <- function(label = "Response Plot", |
|
137 |
response, |
|
138 |
x, |
|
139 |
row_facet = NULL, |
|
140 |
col_facet = NULL, |
|
141 |
coord_flip = FALSE, |
|
142 |
count_labels = TRUE, |
|
143 |
rotate_xaxis_labels = FALSE, |
|
144 |
freq = FALSE, |
|
145 |
plot_height = c(600, 400, 5000), |
|
146 |
plot_width = NULL, |
|
147 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
148 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
149 |
pre_output = NULL, |
|
150 |
post_output = NULL) { |
|
151 | ! |
message("Initializing tm_g_response") |
152 | ||
153 |
# Normalize the parameters |
|
154 | ! |
if (inherits(response, "data_extract_spec")) response <- list(response) |
155 | ! |
if (inherits(x, "data_extract_spec")) x <- list(x) |
156 | ! |
if (inherits(row_facet, "data_extract_spec")) row_facet <- list(row_facet) |
157 | ! |
if (inherits(col_facet, "data_extract_spec")) col_facet <- list(col_facet) |
158 | ||
159 |
# Start of assertions |
|
160 | ! |
checkmate::assert_string(label) |
161 | ||
162 | ! |
checkmate::assert_list(response, types = "data_extract_spec") |
163 | ! |
if (!all(vapply(response, function(x) !("" %in% x$select$choices), logical(1)))) { |
164 | ! |
stop("'response' should not allow empty values") |
165 |
} |
|
166 | ! |
assert_single_selection(response) |
167 | ||
168 | ! |
checkmate::assert_list(x, types = "data_extract_spec") |
169 | ! |
if (!all(vapply(x, function(x) !("" %in% x$select$choices), logical(1)))) { |
170 | ! |
stop("'x' should not allow empty values") |
171 |
} |
|
172 | ! |
assert_single_selection(x) |
173 | ||
174 | ! |
checkmate::assert_list(row_facet, types = "data_extract_spec", null.ok = TRUE) |
175 | ! |
checkmate::assert_list(col_facet, types = "data_extract_spec", null.ok = TRUE) |
176 | ! |
checkmate::assert_flag(coord_flip) |
177 | ! |
checkmate::assert_flag(count_labels) |
178 | ! |
checkmate::assert_flag(rotate_xaxis_labels) |
179 | ! |
checkmate::assert_flag(freq) |
180 | ||
181 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
182 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
183 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
184 | ! |
checkmate::assert_numeric( |
185 | ! |
plot_width[1], |
186 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
187 |
) |
|
188 | ||
189 | ! |
ggtheme <- match.arg(ggtheme) |
190 | ! |
checkmate::assert_class(ggplot2_args, "ggplot2_args") |
191 | ||
192 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
193 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
194 |
# End of assertions |
|
195 | ||
196 |
# Make UI args |
|
197 | ! |
args <- as.list(environment()) |
198 | ||
199 | ! |
data_extract_list <- list( |
200 | ! |
response = response, |
201 | ! |
x = x, |
202 | ! |
row_facet = row_facet, |
203 | ! |
col_facet = col_facet |
204 |
) |
|
205 | ||
206 | ! |
ans <- module( |
207 | ! |
label = label, |
208 | ! |
server = srv_g_response, |
209 | ! |
ui = ui_g_response, |
210 | ! |
ui_args = args, |
211 | ! |
server_args = c( |
212 | ! |
data_extract_list, |
213 | ! |
list(plot_height = plot_height, plot_width = plot_width, ggplot2_args = ggplot2_args) |
214 |
), |
|
215 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
216 |
) |
|
217 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
218 | ! |
ans |
219 |
} |
|
220 | ||
221 |
# UI function for the response module |
|
222 |
ui_g_response <- function(id, ...) { |
|
223 | ! |
ns <- NS(id) |
224 | ! |
args <- list(...) |
225 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$response, args$x, args$row_facet, args$col_facet) |
226 | ||
227 | ! |
teal.widgets::standard_layout( |
228 | ! |
output = teal.widgets::white_small_well( |
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("response", "x", "row_facet", "col_facet")]), |
237 | ! |
teal.transform::data_extract_ui( |
238 | ! |
id = ns("response"), |
239 | ! |
label = "Response variable", |
240 | ! |
data_extract_spec = args$response, |
241 | ! |
is_single_dataset = is_single_dataset_value |
242 |
), |
|
243 | ! |
teal.transform::data_extract_ui( |
244 | ! |
id = ns("x"), |
245 | ! |
label = "X variable", |
246 | ! |
data_extract_spec = args$x, |
247 | ! |
is_single_dataset = is_single_dataset_value |
248 |
), |
|
249 | ! |
if (!is.null(args$row_facet)) { |
250 | ! |
teal.transform::data_extract_ui( |
251 | ! |
id = ns("row_facet"), |
252 | ! |
label = "Row facetting", |
253 | ! |
data_extract_spec = args$row_facet, |
254 | ! |
is_single_dataset = is_single_dataset_value |
255 |
) |
|
256 |
}, |
|
257 | ! |
if (!is.null(args$col_facet)) { |
258 | ! |
teal.transform::data_extract_ui( |
259 | ! |
id = ns("col_facet"), |
260 | ! |
label = "Column facetting", |
261 | ! |
data_extract_spec = args$col_facet, |
262 | ! |
is_single_dataset = is_single_dataset_value |
263 |
) |
|
264 |
}, |
|
265 | ! |
shinyWidgets::radioGroupButtons( |
266 | ! |
inputId = ns("freq"), |
267 | ! |
label = NULL, |
268 | ! |
choices = c("frequency", "density"), |
269 | ! |
selected = ifelse(args$freq, "frequency", "density"), |
270 | ! |
justified = TRUE |
271 |
), |
|
272 | ! |
teal.widgets::panel_group( |
273 | ! |
teal.widgets::panel_item( |
274 | ! |
title = "Plot settings", |
275 | ! |
checkboxInput(ns("count_labels"), "Add count labels", value = args$count_labels), |
276 | ! |
checkboxInput(ns("coord_flip"), "Swap axes", value = args$coord_flip), |
277 | ! |
checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = args$rotate_xaxis_labels), |
278 | ! |
selectInput( |
279 | ! |
inputId = ns("ggtheme"), |
280 | ! |
label = "Theme (by ggplot):", |
281 | ! |
choices = ggplot_themes, |
282 | ! |
selected = args$ggtheme, |
283 | ! |
multiple = FALSE |
284 |
) |
|
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 response module |
|
297 |
srv_g_response <- function(id, |
|
298 |
data, |
|
299 |
reporter, |
|
300 |
filter_panel_api, |
|
301 |
response, |
|
302 |
x, |
|
303 |
row_facet, |
|
304 |
col_facet, |
|
305 |
plot_height, |
|
306 |
plot_width, |
|
307 |
ggplot2_args) { |
|
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 | ! |
moduleServer(id, function(input, output, session) { |
313 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
314 | ||
315 | ! |
data_extract <- list(response = response, x = x, row_facet = row_facet, col_facet = col_facet) |
316 | ||
317 | ! |
rule_diff <- function(other) { |
318 | ! |
function(value) { |
319 | ! |
if (other %in% names(selector_list())) { |
320 | ! |
othervalue <- selector_list()[[other]]()[["select"]] |
321 | ! |
if (!is.null(othervalue)) { |
322 | ! |
if (identical(value, othervalue)) { |
323 | ! |
"Row and column facetting variables must be different." |
324 |
} |
|
325 |
} |
|
326 |
} |
|
327 |
} |
|
328 |
} |
|
329 | ||
330 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
331 | ! |
data_extract = data_extract, |
332 | ! |
datasets = data, |
333 | ! |
select_validation_rule = list( |
334 | ! |
response = shinyvalidate::sv_required("Please define a column for the response variable"), |
335 | ! |
x = shinyvalidate::sv_required("Please define a column for X variable"), |
336 | ! |
row_facet = shinyvalidate::compose_rules( |
337 | ! |
shinyvalidate::sv_optional(), |
338 | ! |
~ if (length(.) > 1) "There must be 1 or no row facetting variable.", |
339 | ! |
rule_diff("col_facet") |
340 |
), |
|
341 | ! |
col_facet = shinyvalidate::compose_rules( |
342 | ! |
shinyvalidate::sv_optional(), |
343 | ! |
~ if (length(.) > 1) "There must be 1 or no column facetting variable.", |
344 | ! |
rule_diff("row_facet") |
345 |
) |
|
346 |
) |
|
347 |
) |
|
348 | ||
349 | ! |
iv_r <- reactive({ |
350 | ! |
iv <- shinyvalidate::InputValidator$new() |
351 | ! |
iv$add_rule("ggtheme", shinyvalidate::sv_required("Please select a theme")) |
352 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
353 |
}) |
|
354 | ||
355 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
356 | ! |
selector_list = selector_list, |
357 | ! |
datasets = data |
358 |
) |
|
359 | ||
360 | ! |
anl_merged_q <- reactive({ |
361 | ! |
req(anl_merged_input()) |
362 | ! |
data() %>% |
363 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
364 |
}) |
|
365 | ||
366 | ! |
merged <- list( |
367 | ! |
anl_input_r = anl_merged_input, |
368 | ! |
anl_q_r = anl_merged_q |
369 |
) |
|
370 | ||
371 | ! |
output_q <- reactive({ |
372 | ! |
teal::validate_inputs(iv_r()) |
373 | ||
374 | ! |
qenv <- merged$anl_q_r() |
375 | ! |
ANL <- qenv[["ANL"]] |
376 | ! |
resp_var <- as.vector(merged$anl_input_r()$columns_source$response) |
377 | ! |
x <- as.vector(merged$anl_input_r()$columns_source$x) |
378 | ||
379 | ! |
validate(need(is.factor(ANL[[resp_var]]), "Please select a factor variable as the response.")) |
380 | ! |
validate(need(is.factor(ANL[[x]]), "Please select a factor variable as the X-Variable.")) |
381 | ! |
teal::validate_has_data(ANL, 10) |
382 | ! |
teal::validate_has_data(ANL[, c(resp_var, x)], 10, complete = TRUE, allow_inf = FALSE) |
383 | ||
384 | ! |
row_facet_name <- if (length(merged$anl_input_r()$columns_source$row_facet) == 0) { |
385 | ! |
character(0) |
386 |
} else { |
|
387 | ! |
as.vector(merged$anl_input_r()$columns_source$row_facet) |
388 |
} |
|
389 | ! |
col_facet_name <- if (length(merged$anl_input_r()$columns_source$col_facet) == 0) { |
390 | ! |
character(0) |
391 |
} else { |
|
392 | ! |
as.vector(merged$anl_input_r()$columns_source$col_facet) |
393 |
} |
|
394 | ||
395 | ! |
freq <- input$freq == "frequency" |
396 | ! |
swap_axes <- input$coord_flip |
397 | ! |
counts <- input$count_labels |
398 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
399 | ! |
ggtheme <- input$ggtheme |
400 | ||
401 | ! |
arg_position <- if (freq) "stack" else "fill" |
402 | ||
403 | ! |
rowf <- if (length(row_facet_name) != 0) as.name(row_facet_name) |
404 | ! |
colf <- if (length(col_facet_name) != 0) as.name(col_facet_name) |
405 | ! |
resp_cl <- as.name(resp_var) |
406 | ! |
x_cl <- as.name(x) |
407 | ||
408 | ! |
if (swap_axes) { |
409 | ! |
qenv <- teal.code::eval_code( |
410 | ! |
qenv, |
411 | ! |
substitute( |
412 | ! |
expr = ANL[[x]] <- with(ANL, forcats::fct_rev(x_cl)), |
413 | ! |
env = list(x = x, x_cl = x_cl) |
414 |
) |
|
415 |
) |
|
416 |
} |
|
417 | ||
418 | ! |
qenv <- teal.code::eval_code( |
419 | ! |
qenv, |
420 | ! |
substitute( |
421 | ! |
expr = ANL[[resp_var]] <- factor(ANL[[resp_var]]), |
422 | ! |
env = list(resp_var = resp_var) |
423 |
) |
|
424 |
) %>% |
|
425 |
# rowf and colf will be a NULL if not set by a user |
|
426 | ! |
teal.code::eval_code( |
427 | ! |
substitute( |
428 | ! |
expr = ANL2 <- ANL %>% |
429 | ! |
dplyr::group_by_at(dplyr::vars(x_cl, resp_cl, rowf, colf)) %>% |
430 | ! |
dplyr::summarise(ns = dplyr::n()) %>% |
431 | ! |
dplyr::group_by_at(dplyr::vars(x_cl, rowf, colf)) %>% |
432 | ! |
dplyr::mutate(sums = sum(ns), percent = round(ns / sums * 100, 1)), |
433 | ! |
env = list(x_cl = x_cl, resp_cl = resp_cl, rowf = rowf, colf = colf) |
434 |
) |
|
435 |
) %>% |
|
436 | ! |
teal.code::eval_code( |
437 | ! |
substitute( |
438 | ! |
expr = ANL3 <- ANL %>% |
439 | ! |
dplyr::group_by_at(dplyr::vars(x_cl, rowf, colf)) %>% |
440 | ! |
dplyr::summarise(ns = dplyr::n()), |
441 | ! |
env = list(x_cl = x_cl, rowf = rowf, colf = colf) |
442 |
) |
|
443 |
) |
|
444 | ||
445 | ! |
plot_call <- substitute( |
446 | ! |
expr = ggplot(ANL2, aes(x = x_cl, y = ns)) + |
447 | ! |
geom_bar(aes(fill = resp_cl), stat = "identity", position = arg_position), |
448 | ! |
env = list( |
449 | ! |
x_cl = x_cl, |
450 | ! |
resp_cl = resp_cl, |
451 | ! |
arg_position = arg_position |
452 |
) |
|
453 |
) |
|
454 | ||
455 | ! |
if (!freq) { |
456 | ! |
plot_call <- substitute( |
457 | ! |
plot_call + expand_limits(y = c(0, 1.1)), |
458 | ! |
env = list(plot_call = plot_call) |
459 |
) |
|
460 |
} |
|
461 | ||
462 | ! |
if (counts) { |
463 | ! |
plot_call <- substitute( |
464 | ! |
expr = plot_call + |
465 | ! |
geom_text( |
466 | ! |
data = ANL2, |
467 | ! |
aes(label = ns, x = x_cl, y = ns, group = resp_cl), |
468 | ! |
col = "white", |
469 | ! |
vjust = "middle", |
470 | ! |
hjust = "middle", |
471 | ! |
position = position_anl2_value |
472 |
) + |
|
473 | ! |
geom_text( |
474 | ! |
data = ANL3, aes(label = ns, x = x_cl, y = anl3_y), |
475 | ! |
hjust = hjust_value, |
476 | ! |
vjust = vjust_value, |
477 | ! |
position = position_anl3_value |
478 |
), |
|
479 | ! |
env = list( |
480 | ! |
plot_call = plot_call, |
481 | ! |
x_cl = x_cl, |
482 | ! |
resp_cl = resp_cl, |
483 | ! |
hjust_value = if (swap_axes) "left" else "middle", |
484 | ! |
vjust_value = if (swap_axes) "middle" else -1, |
485 | ! |
position_anl2_value = if (!freq) quote(position_fill(0.5)) else quote(position_stack(0.5)), # nolint: line_length. |
486 | ! |
anl3_y = if (!freq) 1.1 else as.name("ns"), |
487 | ! |
position_anl3_value = if (!freq) "fill" else "stack" |
488 |
) |
|
489 |
) |
|
490 |
} |
|
491 | ||
492 | ! |
if (swap_axes) { |
493 | ! |
plot_call <- substitute(plot_call + coord_flip(), env = list(plot_call = plot_call)) |
494 |
} |
|
495 | ||
496 | ! |
facet_cl <- facet_ggplot_call(row_facet_name, col_facet_name) |
497 | ||
498 | ! |
if (!is.null(facet_cl)) { |
499 | ! |
plot_call <- substitute(expr = plot_call + facet_cl, env = list(plot_call = plot_call, facet_cl = facet_cl)) |
500 |
} |
|
501 | ||
502 | ! |
dev_ggplot2_args <- teal.widgets::ggplot2_args( |
503 | ! |
labs = list( |
504 | ! |
x = varname_w_label(x, ANL), |
505 | ! |
y = varname_w_label(resp_var, ANL, prefix = "Proportion of "), |
506 | ! |
fill = varname_w_label(resp_var, ANL) |
507 |
), |
|
508 | ! |
theme = list(legend.position = "bottom") |
509 |
) |
|
510 | ||
511 | ! |
if (rotate_xaxis_labels) { |
512 | ! |
dev_ggplot2_args$theme[["axis.text.x"]] <- quote(element_text(angle = 45, hjust = 1)) |
513 |
} |
|
514 | ||
515 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
516 | ! |
user_plot = ggplot2_args, |
517 | ! |
module_plot = dev_ggplot2_args |
518 |
) |
|
519 | ||
520 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
521 | ! |
all_ggplot2_args, |
522 | ! |
ggtheme = ggtheme |
523 |
) |
|
524 | ||
525 | ! |
plot_call <- substitute(expr = { |
526 | ! |
p <- plot_call + labs + ggthemes + themes |
527 | ! |
print(p) |
528 | ! |
}, env = list( |
529 | ! |
plot_call = plot_call, |
530 | ! |
labs = parsed_ggplot2_args$labs, |
531 | ! |
themes = parsed_ggplot2_args$theme, |
532 | ! |
ggthemes = parsed_ggplot2_args$ggtheme |
533 |
)) |
|
534 | ||
535 | ! |
teal.code::eval_code(qenv, plot_call) |
536 |
}) |
|
537 | ||
538 | ! |
plot_r <- reactive(output_q()[["p"]]) |
539 | ||
540 |
# Insert the plot into a plot_with_settings module from teal.widgets |
|
541 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
542 | ! |
id = "myplot", |
543 | ! |
plot_r = plot_r, |
544 | ! |
height = plot_height, |
545 | ! |
width = plot_width |
546 |
) |
|
547 | ||
548 | ! |
teal.widgets::verbatim_popup_srv( |
549 | ! |
id = "rcode", |
550 | ! |
verbatim_content = reactive(teal.code::get_code(output_q())), |
551 | ! |
title = "Show R Code for Response" |
552 |
) |
|
553 | ||
554 |
### REPORTER |
|
555 | ! |
if (with_reporter) { |
556 | ! |
card_fun <- function(comment, label) { |
557 | ! |
card <- teal::report_card_template( |
558 | ! |
title = "Response Plot", |
559 | ! |
label = label, |
560 | ! |
with_filter = with_filter, |
561 | ! |
filter_panel_api = filter_panel_api |
562 |
) |
|
563 | ! |
card$append_text("Plot", "header3") |
564 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
565 | ! |
if (!comment == "") { |
566 | ! |
card$append_text("Comment", "header3") |
567 | ! |
card$append_text(comment) |
568 |
} |
|
569 | ! |
card$append_src(teal.code::get_code(output_q())) |
570 | ! |
card |
571 |
} |
|
572 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
573 |
} |
|
574 |
### |
|
575 |
}) |
|
576 |
} |
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 |
#' @templateVar ggnames "Bivariate1", "Bivariate2" |
|
24 |
#' @template ggplot2_args_multi |
|
25 |
#' |
|
26 |
#' @inherit shared_params return |
|
27 |
#' |
|
28 |
#' @examplesShinylive |
|
29 |
#' library(teal.modules.general) |
|
30 |
#' interactive <- function() TRUE |
|
31 |
#' {{ next_example }} |
|
32 |
#' @examples |
|
33 |
#' # general data example |
|
34 |
#' data <- teal_data() |
|
35 |
#' data <- within(data, { |
|
36 |
#' require(nestcolor) |
|
37 |
#' CO2 <- CO2 |
|
38 |
#' factors <- names(Filter(isTRUE, vapply(CO2, is.factor, logical(1L)))) |
|
39 |
#' CO2[factors] <- lapply(CO2[factors], as.character) |
|
40 |
#' }) |
|
41 |
#' |
|
42 |
#' app <- init( |
|
43 |
#' data = data, |
|
44 |
#' modules = modules( |
|
45 |
#' tm_g_association( |
|
46 |
#' ref = data_extract_spec( |
|
47 |
#' dataname = "CO2", |
|
48 |
#' select = select_spec( |
|
49 |
#' label = "Select variable:", |
|
50 |
#' choices = variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment")), |
|
51 |
#' selected = "Plant", |
|
52 |
#' fixed = FALSE |
|
53 |
#' ) |
|
54 |
#' ), |
|
55 |
#' vars = data_extract_spec( |
|
56 |
#' dataname = "CO2", |
|
57 |
#' select = select_spec( |
|
58 |
#' label = "Select variables:", |
|
59 |
#' choices = variable_choices(data[["CO2"]], c("Plant", "Type", "Treatment")), |
|
60 |
#' selected = "Treatment", |
|
61 |
#' multiple = TRUE, |
|
62 |
#' fixed = FALSE |
|
63 |
#' ) |
|
64 |
#' ) |
|
65 |
#' ) |
|
66 |
#' ) |
|
67 |
#' ) |
|
68 |
#' if (interactive()) { |
|
69 |
#' shinyApp(app$ui, app$server) |
|
70 |
#' } |
|
71 |
#' |
|
72 |
#' @examplesShinylive |
|
73 |
#' library(teal.modules.general) |
|
74 |
#' interactive <- function() TRUE |
|
75 |
#' {{ next_example }} |
|
76 |
#' @examples |
|
77 |
#' # CDISC data example |
|
78 |
#' data <- teal_data() |
|
79 |
#' data <- within(data, { |
|
80 |
#' require(nestcolor) |
|
81 |
#' ADSL <- rADSL |
|
82 |
#' }) |
|
83 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
84 |
#' |
|
85 |
#' app <- init( |
|
86 |
#' data = data, |
|
87 |
#' modules = modules( |
|
88 |
#' tm_g_association( |
|
89 |
#' ref = data_extract_spec( |
|
90 |
#' dataname = "ADSL", |
|
91 |
#' select = select_spec( |
|
92 |
#' label = "Select variable:", |
|
93 |
#' choices = variable_choices( |
|
94 |
#' data[["ADSL"]], |
|
95 |
#' c("SEX", "RACE", "COUNTRY", "ARM", "STRATA1", "STRATA2", "ITTFL", "BMRKR2") |
|
96 |
#' ), |
|
97 |
#' selected = "RACE", |
|
98 |
#' fixed = FALSE |
|
99 |
#' ) |
|
100 |
#' ), |
|
101 |
#' vars = data_extract_spec( |
|
102 |
#' dataname = "ADSL", |
|
103 |
#' select = select_spec( |
|
104 |
#' label = "Select variables:", |
|
105 |
#' choices = variable_choices( |
|
106 |
#' data[["ADSL"]], |
|
107 |
#' c("SEX", "RACE", "COUNTRY", "ARM", "STRATA1", "STRATA2", "ITTFL", "BMRKR2") |
|
108 |
#' ), |
|
109 |
#' selected = "BMRKR2", |
|
110 |
#' multiple = TRUE, |
|
111 |
#' fixed = FALSE |
|
112 |
#' ) |
|
113 |
#' ) |
|
114 |
#' ) |
|
115 |
#' ) |
|
116 |
#' ) |
|
117 |
#' if (interactive()) { |
|
118 |
#' shinyApp(app$ui, app$server) |
|
119 |
#' } |
|
120 |
#' |
|
121 |
#' @export |
|
122 |
#' |
|
123 |
tm_g_association <- function(label = "Association", |
|
124 |
ref, |
|
125 |
vars, |
|
126 |
show_association = TRUE, |
|
127 |
plot_height = c(600, 400, 5000), |
|
128 |
plot_width = NULL, |
|
129 |
distribution_theme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), # nolint: line_length. |
|
130 |
association_theme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), # nolint: line_length. |
|
131 |
pre_output = NULL, |
|
132 |
post_output = NULL, |
|
133 |
ggplot2_args = teal.widgets::ggplot2_args()) { |
|
134 | ! |
message("Initializing tm_g_association") |
135 | ||
136 |
# Normalize the parameters |
|
137 | ! |
if (inherits(ref, "data_extract_spec")) ref <- list(ref) |
138 | ! |
if (inherits(vars, "data_extract_spec")) vars <- list(vars) |
139 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
140 | ||
141 |
# Start of assertions |
|
142 | ! |
checkmate::assert_string(label) |
143 | ||
144 | ! |
checkmate::assert_list(ref, types = "data_extract_spec") |
145 | ! |
if (!all(vapply(ref, function(x) !x$select$multiple, logical(1)))) { |
146 | ! |
stop("'ref' should not allow multiple selection") |
147 |
} |
|
148 | ||
149 | ! |
checkmate::assert_list(vars, types = "data_extract_spec") |
150 | ! |
checkmate::assert_flag(show_association) |
151 | ||
152 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
153 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
154 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
155 | ! |
checkmate::assert_numeric( |
156 | ! |
plot_width[1], |
157 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
158 |
) |
|
159 | ||
160 | ! |
distribution_theme <- match.arg(distribution_theme) |
161 | ! |
association_theme <- match.arg(association_theme) |
162 | ||
163 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
164 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
165 | ||
166 | ! |
plot_choices <- c("Bivariate1", "Bivariate2") |
167 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
168 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
169 |
# End of assertions |
|
170 | ||
171 |
# Make UI args |
|
172 | ! |
args <- as.list(environment()) |
173 | ||
174 | ! |
data_extract_list <- list( |
175 | ! |
ref = ref, |
176 | ! |
vars = vars |
177 |
) |
|
178 | ||
179 | ! |
ans <- module( |
180 | ! |
label = label, |
181 | ! |
server = srv_tm_g_association, |
182 | ! |
ui = ui_tm_g_association, |
183 | ! |
ui_args = args, |
184 | ! |
server_args = c( |
185 | ! |
data_extract_list, |
186 | ! |
list(plot_height = plot_height, plot_width = plot_width, ggplot2_args = ggplot2_args) |
187 |
), |
|
188 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
189 |
) |
|
190 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
191 | ! |
ans |
192 |
} |
|
193 | ||
194 |
# UI function for the association module |
|
195 |
ui_tm_g_association <- function(id, ...) { |
|
196 | ! |
ns <- NS(id) |
197 | ! |
args <- list(...) |
198 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$ref, args$vars) |
199 | ||
200 | ! |
teal.widgets::standard_layout( |
201 | ! |
output = teal.widgets::white_small_well( |
202 | ! |
textOutput(ns("title")), |
203 | ! |
tags$br(), |
204 | ! |
teal.widgets::plot_with_settings_ui(id = ns("myplot")) |
205 |
), |
|
206 | ! |
encoding = tags$div( |
207 |
### Reporter |
|
208 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
209 |
### |
|
210 | ! |
tags$label("Encodings", class = "text-primary"), |
211 | ! |
teal.transform::datanames_input(args[c("ref", "vars")]), |
212 | ! |
teal.transform::data_extract_ui( |
213 | ! |
id = ns("ref"), |
214 | ! |
label = "Reference variable", |
215 | ! |
data_extract_spec = args$ref, |
216 | ! |
is_single_dataset = is_single_dataset_value |
217 |
), |
|
218 | ! |
teal.transform::data_extract_ui( |
219 | ! |
id = ns("vars"), |
220 | ! |
label = "Associated variables", |
221 | ! |
data_extract_spec = args$vars, |
222 | ! |
is_single_dataset = is_single_dataset_value |
223 |
), |
|
224 | ! |
checkboxInput( |
225 | ! |
ns("association"), |
226 | ! |
"Association with reference variable", |
227 | ! |
value = args$show_association |
228 |
), |
|
229 | ! |
checkboxInput( |
230 | ! |
ns("show_dist"), |
231 | ! |
"Scaled frequencies", |
232 | ! |
value = FALSE |
233 |
), |
|
234 | ! |
checkboxInput( |
235 | ! |
ns("log_transformation"), |
236 | ! |
"Log transformed", |
237 | ! |
value = FALSE |
238 |
), |
|
239 | ! |
teal.widgets::panel_group( |
240 | ! |
teal.widgets::panel_item( |
241 | ! |
title = "Plot settings", |
242 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("alpha"), "Scatterplot opacity:", c(0.5, 0, 1), ticks = FALSE), |
243 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("size"), "Scatterplot points size:", c(2, 1, 8), ticks = FALSE), |
244 | ! |
checkboxInput(ns("swap_axes"), "Swap axes", value = FALSE), |
245 | ! |
checkboxInput(ns("rotate_xaxis_labels"), "Rotate X axis labels", value = FALSE), |
246 | ! |
selectInput( |
247 | ! |
inputId = ns("distribution_theme"), |
248 | ! |
label = "Distribution theme (by ggplot):", |
249 | ! |
choices = ggplot_themes, |
250 | ! |
selected = args$distribution_theme, |
251 | ! |
multiple = FALSE |
252 |
), |
|
253 | ! |
selectInput( |
254 | ! |
inputId = ns("association_theme"), |
255 | ! |
label = "Association theme (by ggplot):", |
256 | ! |
choices = ggplot_themes, |
257 | ! |
selected = args$association_theme, |
258 | ! |
multiple = FALSE |
259 |
) |
|
260 |
) |
|
261 |
) |
|
262 |
), |
|
263 | ! |
forms = tagList( |
264 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
265 |
), |
|
266 | ! |
pre_output = args$pre_output, |
267 | ! |
post_output = args$post_output |
268 |
) |
|
269 |
} |
|
270 | ||
271 |
# Server function for the association module |
|
272 |
srv_tm_g_association <- function(id, |
|
273 |
data, |
|
274 |
reporter, |
|
275 |
filter_panel_api, |
|
276 |
ref, |
|
277 |
vars, |
|
278 |
plot_height, |
|
279 |
plot_width, |
|
280 |
ggplot2_args) { |
|
281 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
282 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
283 | ! |
checkmate::assert_class(data, "reactive") |
284 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
285 | ||
286 | ! |
moduleServer(id, function(input, output, session) { |
287 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
288 | ||
289 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
290 | ! |
data_extract = list(ref = ref, vars = vars), |
291 | ! |
datasets = data, |
292 | ! |
select_validation_rule = list( |
293 | ! |
ref = shinyvalidate::compose_rules( |
294 | ! |
shinyvalidate::sv_required("A reference variable needs to be selected."), |
295 | ! |
~ if ((.) %in% selector_list()$vars()$select) { |
296 | ! |
"Associated variables and reference variable cannot overlap" |
297 |
} |
|
298 |
), |
|
299 | ! |
vars = shinyvalidate::compose_rules( |
300 | ! |
shinyvalidate::sv_required("An associated variable needs to be selected."), |
301 | ! |
~ if (length(selector_list()$ref()$select) != 0 && selector_list()$ref()$select %in% (.)) { |
302 | ! |
"Associated variables and reference variable cannot overlap" |
303 |
} |
|
304 |
) |
|
305 |
) |
|
306 |
) |
|
307 | ||
308 | ! |
iv_r <- reactive({ |
309 | ! |
iv <- shinyvalidate::InputValidator$new() |
310 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
311 |
}) |
|
312 | ||
313 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
314 | ! |
datasets = data, |
315 | ! |
selector_list = selector_list |
316 |
) |
|
317 | ||
318 | ! |
anl_merged_q <- reactive({ |
319 | ! |
req(anl_merged_input()) |
320 | ! |
data() %>% teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
321 |
}) |
|
322 | ||
323 | ! |
merged <- list( |
324 | ! |
anl_input_r = anl_merged_input, |
325 | ! |
anl_q_r = anl_merged_q |
326 |
) |
|
327 | ||
328 | ! |
output_q <- reactive({ |
329 | ! |
teal::validate_inputs(iv_r()) |
330 | ||
331 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
332 | ! |
teal::validate_has_data(ANL, 3) |
333 | ||
334 | ! |
vars_names <- merged$anl_input_r()$columns_source$vars |
335 | ||
336 | ! |
ref_name <- as.vector(merged$anl_input_r()$columns_source$ref) |
337 | ! |
association <- input$association |
338 | ! |
show_dist <- input$show_dist |
339 | ! |
log_transformation <- input$log_transformation |
340 | ! |
rotate_xaxis_labels <- input$rotate_xaxis_labels |
341 | ! |
swap_axes <- input$swap_axes |
342 | ! |
distribution_theme <- input$distribution_theme |
343 | ! |
association_theme <- input$association_theme |
344 | ||
345 | ! |
is_scatterplot <- is.numeric(ANL[[ref_name]]) && any(vapply(ANL[vars_names], is.numeric, logical(1))) |
346 | ! |
if (is_scatterplot) { |
347 | ! |
shinyjs::show("alpha") |
348 | ! |
shinyjs::show("size") |
349 | ! |
alpha <- input$alpha |
350 | ! |
size <- input$size |
351 |
} else { |
|
352 | ! |
shinyjs::hide("alpha") |
353 | ! |
shinyjs::hide("size") |
354 | ! |
alpha <- 0.5 |
355 | ! |
size <- 2 |
356 |
} |
|
357 | ||
358 | ! |
teal::validate_has_data(ANL[, c(ref_name, vars_names)], 3, complete = TRUE, allow_inf = FALSE) |
359 | ||
360 |
# reference |
|
361 | ! |
ref_class <- class(ANL[[ref_name]])[1] |
362 | ! |
if (is.numeric(ANL[[ref_name]]) && log_transformation) { |
363 |
# works for both integers and doubles |
|
364 | ! |
ref_cl_name <- call("log", as.name(ref_name)) |
365 | ! |
ref_cl_lbl <- varname_w_label(ref_name, ANL, prefix = "Log of ") |
366 |
} else { |
|
367 |
# silently ignore when non-numeric even if `log` is selected because some |
|
368 |
# variables may be numeric and others not |
|
369 | ! |
ref_cl_name <- as.name(ref_name) |
370 | ! |
ref_cl_lbl <- varname_w_label(ref_name, ANL) |
371 |
} |
|
372 | ||
373 | ! |
user_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
374 | ! |
user_plot = ggplot2_args[["Bivariate1"]], |
375 | ! |
user_default = ggplot2_args$default |
376 |
) |
|
377 | ||
378 | ! |
ref_call <- bivariate_plot_call( |
379 | ! |
data_name = "ANL", |
380 | ! |
x = ref_cl_name, |
381 | ! |
x_class = ref_class, |
382 | ! |
x_label = ref_cl_lbl, |
383 | ! |
freq = !show_dist, |
384 | ! |
theme = distribution_theme, |
385 | ! |
rotate_xaxis_labels = rotate_xaxis_labels, |
386 | ! |
swap_axes = FALSE, |
387 | ! |
size = size, |
388 | ! |
alpha = alpha, |
389 | ! |
ggplot2_args = user_ggplot2_args |
390 |
) |
|
391 | ||
392 |
# association |
|
393 | ! |
ref_class_cov <- ifelse(association, ref_class, "NULL") |
394 | ||
395 | ! |
print_call <- quote(print(p)) |
396 | ||
397 | ! |
var_calls <- lapply(vars_names, function(var_i) { |
398 | ! |
var_class <- class(ANL[[var_i]])[1] |
399 | ! |
if (is.numeric(ANL[[var_i]]) && log_transformation) { |
400 |
# works for both integers and doubles |
|
401 | ! |
var_cl_name <- call("log", as.name(var_i)) |
402 | ! |
var_cl_lbl <- varname_w_label(var_i, ANL, prefix = "Log of ") |
403 |
} else { |
|
404 |
# silently ignore when non-numeric even if `log` is selected because some |
|
405 |
# variables may be numeric and others not |
|
406 | ! |
var_cl_name <- as.name(var_i) |
407 | ! |
var_cl_lbl <- varname_w_label(var_i, ANL) |
408 |
} |
|
409 | ||
410 | ! |
user_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
411 | ! |
user_plot = ggplot2_args[["Bivariate2"]], |
412 | ! |
user_default = ggplot2_args$default |
413 |
) |
|
414 | ||
415 | ! |
bivariate_plot_call( |
416 | ! |
data_name = "ANL", |
417 | ! |
x = ref_cl_name, |
418 | ! |
y = var_cl_name, |
419 | ! |
x_class = ref_class_cov, |
420 | ! |
y_class = var_class, |
421 | ! |
x_label = ref_cl_lbl, |
422 | ! |
y_label = var_cl_lbl, |
423 | ! |
theme = association_theme, |
424 | ! |
freq = !show_dist, |
425 | ! |
rotate_xaxis_labels = rotate_xaxis_labels, |
426 | ! |
swap_axes = swap_axes, |
427 | ! |
alpha = alpha, |
428 | ! |
size = size, |
429 | ! |
ggplot2_args = user_ggplot2_args |
430 |
) |
|
431 |
}) |
|
432 | ||
433 |
# helper function to format variable name |
|
434 | ! |
format_varnames <- function(x) { |
435 | ! |
if (is.numeric(ANL[[x]]) && log_transformation) { |
436 | ! |
varname_w_label(x, ANL, prefix = "Log of ") |
437 |
} else { |
|
438 | ! |
varname_w_label(x, ANL) |
439 |
} |
|
440 |
} |
|
441 | ! |
new_title <- |
442 | ! |
if (association) { |
443 | ! |
switch(as.character(length(vars_names)), |
444 | ! |
"0" = sprintf("Value distribution for %s", ref_cl_lbl), |
445 | ! |
"1" = sprintf( |
446 | ! |
"Association between %s and %s", |
447 | ! |
ref_cl_lbl, |
448 | ! |
format_varnames(vars_names) |
449 |
), |
|
450 | ! |
sprintf( |
451 | ! |
"Associations between %s and: %s", |
452 | ! |
ref_cl_lbl, |
453 | ! |
paste(lapply(vars_names, format_varnames), collapse = ", ") |
454 |
) |
|
455 |
) |
|
456 |
} else { |
|
457 | ! |
switch(as.character(length(vars_names)), |
458 | ! |
"0" = sprintf("Value distribution for %s", ref_cl_lbl), |
459 | ! |
sprintf( |
460 | ! |
"Value distributions for %s and %s", |
461 | ! |
ref_cl_lbl, |
462 | ! |
paste(lapply(vars_names, format_varnames), collapse = ", ") |
463 |
) |
|
464 |
) |
|
465 |
} |
|
466 | ||
467 | ! |
teal.code::eval_code( |
468 | ! |
merged$anl_q_r(), |
469 | ! |
substitute( |
470 | ! |
expr = title <- new_title, |
471 | ! |
env = list(new_title = new_title) |
472 |
) |
|
473 |
) %>% |
|
474 | ! |
teal.code::eval_code( |
475 | ! |
substitute( |
476 | ! |
expr = { |
477 | ! |
plots <- plot_calls |
478 | ! |
p <- tern::stack_grobs(grobs = lapply(plots, ggplotGrob)) |
479 | ! |
grid::grid.newpage() |
480 | ! |
grid::grid.draw(p) |
481 |
}, |
|
482 | ! |
env = list( |
483 | ! |
plot_calls = do.call( |
484 | ! |
"call", |
485 | ! |
c(list("list", ref_call), var_calls), |
486 | ! |
quote = TRUE |
487 |
) |
|
488 |
) |
|
489 |
) |
|
490 |
) |
|
491 |
}) |
|
492 | ||
493 | ! |
plot_r <- reactive({ |
494 | ! |
req(iv_r()$is_valid()) |
495 | ! |
output_q()[["p"]] |
496 |
}) |
|
497 | ||
498 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
499 | ! |
id = "myplot", |
500 | ! |
plot_r = plot_r, |
501 | ! |
height = plot_height, |
502 | ! |
width = plot_width |
503 |
) |
|
504 | ||
505 | ! |
output$title <- renderText({ |
506 | ! |
teal.code::dev_suppress(output_q()[["title"]]) |
507 |
}) |
|
508 | ||
509 | ! |
teal.widgets::verbatim_popup_srv( |
510 | ! |
id = "rcode", |
511 | ! |
verbatim_content = reactive(teal.code::get_code(output_q())), |
512 | ! |
title = "Association Plot" |
513 |
) |
|
514 | ||
515 |
### REPORTER |
|
516 | ! |
if (with_reporter) { |
517 | ! |
card_fun <- function(comment, label) { |
518 | ! |
card <- teal::report_card_template( |
519 | ! |
title = "Association Plot", |
520 | ! |
label = label, |
521 | ! |
with_filter = with_filter, |
522 | ! |
filter_panel_api = filter_panel_api |
523 |
) |
|
524 | ! |
card$append_text("Plot", "header3") |
525 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
526 | ! |
if (!comment == "") { |
527 | ! |
card$append_text("Comment", "header3") |
528 | ! |
card$append_text(comment) |
529 |
} |
|
530 | ! |
card$append_src(teal.code::get_code(output_q())) |
531 | ! |
card |
532 |
} |
|
533 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
534 |
} |
|
535 |
### |
|
536 |
}) |
|
537 |
} |
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 |
#' @templateVar ggnames "Histogram", "QQplot" |
|
26 |
#' @template ggplot2_args_multi |
|
27 |
#' |
|
28 |
#' @inherit shared_params return |
|
29 |
#' |
|
30 |
#' @examplesShinylive |
|
31 |
#' library(teal.modules.general) |
|
32 |
#' interactive <- function() TRUE |
|
33 |
#' {{ next_example }} |
|
34 |
# nolint start: line_length_linter. |
|
35 |
#' @examplesIf require("ggpmisc", quietly = TRUE) && require("ggpp", quietly = TRUE) && require("goftest", quietly = TRUE) && require("MASS", quietly = TRUE) && require("broom", quietly = TRUE) |
|
36 |
# nolint end: line_length_linter. |
|
37 |
#' # general data example |
|
38 |
#' data <- teal_data() |
|
39 |
#' data <- within(data, { |
|
40 |
#' iris <- iris |
|
41 |
#' }) |
|
42 |
#' |
|
43 |
#' app <- init( |
|
44 |
#' data = data, |
|
45 |
#' modules = list( |
|
46 |
#' tm_g_distribution( |
|
47 |
#' dist_var = data_extract_spec( |
|
48 |
#' dataname = "iris", |
|
49 |
#' select = select_spec(variable_choices("iris"), "Petal.Length") |
|
50 |
#' ) |
|
51 |
#' ) |
|
52 |
#' ) |
|
53 |
#' ) |
|
54 |
#' if (interactive()) { |
|
55 |
#' shinyApp(app$ui, app$server) |
|
56 |
#' } |
|
57 |
#' |
|
58 |
#' @examplesShinylive |
|
59 |
#' library(teal.modules.general) |
|
60 |
#' interactive <- function() TRUE |
|
61 |
#' {{ next_example }} |
|
62 |
# nolint start: line_length_linter. |
|
63 |
#' @examplesIf require("ggpmisc", quietly = TRUE) && require("ggpp", quietly = TRUE) && require("goftest", quietly = TRUE) && require("MASS", quietly = TRUE) && require("broom", quietly = TRUE) |
|
64 |
# nolint end: line_length_linter. |
|
65 |
#' # CDISC data example |
|
66 |
#' data <- teal_data() |
|
67 |
#' data <- within(data, { |
|
68 |
#' ADSL <- rADSL |
|
69 |
#' }) |
|
70 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
71 |
#' |
|
72 |
#' vars1 <- choices_selected( |
|
73 |
#' variable_choices(data[["ADSL"]], c("ARM", "COUNTRY", "SEX")), |
|
74 |
#' selected = NULL |
|
75 |
#' ) |
|
76 |
#' |
|
77 |
#' app <- init( |
|
78 |
#' data = data, |
|
79 |
#' modules = modules( |
|
80 |
#' tm_g_distribution( |
|
81 |
#' dist_var = data_extract_spec( |
|
82 |
#' dataname = "ADSL", |
|
83 |
#' select = select_spec( |
|
84 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "BMRKR1")), |
|
85 |
#' selected = "BMRKR1", |
|
86 |
#' multiple = FALSE, |
|
87 |
#' fixed = FALSE |
|
88 |
#' ) |
|
89 |
#' ), |
|
90 |
#' strata_var = data_extract_spec( |
|
91 |
#' dataname = "ADSL", |
|
92 |
#' filter = filter_spec( |
|
93 |
#' vars = vars1, |
|
94 |
#' multiple = TRUE |
|
95 |
#' ) |
|
96 |
#' ), |
|
97 |
#' group_var = data_extract_spec( |
|
98 |
#' dataname = "ADSL", |
|
99 |
#' filter = filter_spec( |
|
100 |
#' vars = vars1, |
|
101 |
#' multiple = TRUE |
|
102 |
#' ) |
|
103 |
#' ) |
|
104 |
#' ) |
|
105 |
#' ) |
|
106 |
#' ) |
|
107 |
#' if (interactive()) { |
|
108 |
#' shinyApp(app$ui, app$server) |
|
109 |
#' } |
|
110 |
#' |
|
111 |
#' @export |
|
112 |
#' |
|
113 |
tm_g_distribution <- function(label = "Distribution Module", |
|
114 |
dist_var, |
|
115 |
strata_var = NULL, |
|
116 |
group_var = NULL, |
|
117 |
freq = FALSE, |
|
118 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
119 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
120 |
bins = c(30L, 1L, 100L), |
|
121 |
plot_height = c(600, 200, 2000), |
|
122 |
plot_width = NULL, |
|
123 |
pre_output = NULL, |
|
124 |
post_output = NULL) { |
|
125 | ! |
message("Initializing tm_g_distribution") |
126 | ||
127 |
# Requires Suggested packages |
|
128 | ! |
extra_packages <- c("ggpmisc", "ggpp", "goftest", "MASS", "broom") |
129 | ! |
missing_packages <- Filter(function(x) !requireNamespace(x, quietly = TRUE), extra_packages) |
130 | ! |
if (length(missing_packages) > 0L) { |
131 | ! |
stop(sprintf( |
132 | ! |
"Cannot load package(s): %s.\nInstall or restart your session.", |
133 | ! |
toString(missing_packages) |
134 |
)) |
|
135 |
} |
|
136 | ||
137 |
# Normalize the parameters |
|
138 | ! |
if (inherits(dist_var, "data_extract_spec")) dist_var <- list(dist_var) |
139 | ! |
if (inherits(strata_var, "data_extract_spec")) strata_var <- list(strata_var) |
140 | ! |
if (inherits(group_var, "data_extract_spec")) group_var <- list(group_var) |
141 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
142 | ||
143 |
# Start of assertions |
|
144 | ! |
checkmate::assert_string(label) |
145 | ||
146 | ! |
checkmate::assert_list(dist_var, "data_extract_spec") |
147 | ! |
checkmate::assert_false(dist_var[[1L]]$select$multiple) |
148 | ||
149 | ! |
checkmate::assert_list(strata_var, types = "data_extract_spec", null.ok = TRUE) |
150 | ! |
checkmate::assert_list(group_var, types = "data_extract_spec", null.ok = TRUE) |
151 | ! |
checkmate::assert_flag(freq) |
152 | ! |
ggtheme <- match.arg(ggtheme) |
153 | ||
154 | ! |
plot_choices <- c("Histogram", "QQplot") |
155 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
156 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
157 | ||
158 | ! |
if (length(bins) == 1) { |
159 | ! |
checkmate::assert_numeric(bins, any.missing = FALSE, lower = 1) |
160 |
} else { |
|
161 | ! |
checkmate::assert_numeric(bins, len = 3, any.missing = FALSE, lower = 1) |
162 | ! |
checkmate::assert_numeric(bins[1], lower = bins[2], upper = bins[3], .var.name = "bins") |
163 |
} |
|
164 | ||
165 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
166 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
167 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
168 | ! |
checkmate::assert_numeric( |
169 | ! |
plot_width[1], |
170 | ! |
lower = plot_width[2], upper = plot_width[3], null.ok = TRUE, .var.name = "plot_width" |
171 |
) |
|
172 | ||
173 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
174 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
175 |
# End of assertions |
|
176 | ||
177 |
# Make UI args |
|
178 | ! |
args <- as.list(environment()) |
179 | ||
180 | ! |
data_extract_list <- list( |
181 | ! |
dist_var = dist_var, |
182 | ! |
strata_var = strata_var, |
183 | ! |
group_var = group_var |
184 |
) |
|
185 | ||
186 | ! |
ans <- module( |
187 | ! |
label = label, |
188 | ! |
server = srv_distribution, |
189 | ! |
server_args = c( |
190 | ! |
data_extract_list, |
191 | ! |
list(plot_height = plot_height, plot_width = plot_width, ggplot2_args = ggplot2_args) |
192 |
), |
|
193 | ! |
ui = ui_distribution, |
194 | ! |
ui_args = args, |
195 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
196 |
) |
|
197 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
198 | ! |
ans |
199 |
} |
|
200 | ||
201 |
# UI function for the distribution module |
|
202 |
ui_distribution <- function(id, ...) { |
|
203 | ! |
args <- list(...) |
204 | ! |
ns <- NS(id) |
205 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$dist_var, args$strata_var, args$group_var) |
206 | ||
207 | ! |
teal.widgets::standard_layout( |
208 | ! |
output = teal.widgets::white_small_well( |
209 | ! |
tabsetPanel( |
210 | ! |
id = ns("tabs"), |
211 | ! |
tabPanel("Histogram", teal.widgets::plot_with_settings_ui(id = ns("hist_plot"))), |
212 | ! |
tabPanel("QQplot", teal.widgets::plot_with_settings_ui(id = ns("qq_plot"))) |
213 |
), |
|
214 | ! |
tags$h3("Statistics Table"), |
215 | ! |
DT::dataTableOutput(ns("summary_table")), |
216 | ! |
tags$h3("Tests"), |
217 | ! |
DT::dataTableOutput(ns("t_stats")) |
218 |
), |
|
219 | ! |
encoding = tags$div( |
220 |
### Reporter |
|
221 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
222 |
### |
|
223 | ! |
tags$label("Encodings", class = "text-primary"), |
224 | ! |
teal.transform::datanames_input(args[c("dist_var", "strata_var")]), |
225 | ! |
teal.transform::data_extract_ui( |
226 | ! |
id = ns("dist_i"), |
227 | ! |
label = "Variable", |
228 | ! |
data_extract_spec = args$dist_var, |
229 | ! |
is_single_dataset = is_single_dataset_value |
230 |
), |
|
231 | ! |
if (!is.null(args$group_var)) { |
232 | ! |
tagList( |
233 | ! |
teal.transform::data_extract_ui( |
234 | ! |
id = ns("group_i"), |
235 | ! |
label = "Group by", |
236 | ! |
data_extract_spec = args$group_var, |
237 | ! |
is_single_dataset = is_single_dataset_value |
238 |
), |
|
239 | ! |
uiOutput(ns("scales_types_ui")) |
240 |
) |
|
241 |
}, |
|
242 | ! |
if (!is.null(args$strata_var)) { |
243 | ! |
teal.transform::data_extract_ui( |
244 | ! |
id = ns("strata_i"), |
245 | ! |
label = "Stratify by", |
246 | ! |
data_extract_spec = args$strata_var, |
247 | ! |
is_single_dataset = is_single_dataset_value |
248 |
) |
|
249 |
}, |
|
250 | ! |
teal.widgets::panel_group( |
251 | ! |
conditionalPanel( |
252 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'Histogram'"), |
253 | ! |
teal.widgets::panel_item( |
254 | ! |
"Histogram", |
255 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("bins"), "Bins", args$bins, ticks = FALSE, step = 1), |
256 | ! |
shinyWidgets::prettyRadioButtons( |
257 | ! |
ns("main_type"), |
258 | ! |
label = "Plot Type:", |
259 | ! |
choices = c("Density", "Frequency"), |
260 | ! |
selected = if (!args$freq) "Density" else "Frequency", |
261 | ! |
bigger = FALSE, |
262 | ! |
inline = TRUE |
263 |
), |
|
264 | ! |
checkboxInput(ns("add_dens"), label = "Overlay Density", value = TRUE), |
265 | ! |
collapsed = FALSE |
266 |
) |
|
267 |
), |
|
268 | ! |
conditionalPanel( |
269 | ! |
condition = paste0("input['", ns("tabs"), "'] == 'QQplot'"), |
270 | ! |
teal.widgets::panel_item( |
271 | ! |
"QQ Plot", |
272 | ! |
checkboxInput(ns("qq_line"), label = "Add diagonal line(s)", TRUE), |
273 | ! |
collapsed = FALSE |
274 |
) |
|
275 |
), |
|
276 | ! |
conditionalPanel( |
277 | ! |
condition = paste0("input['", ns("main_type"), "'] == 'Density'"), |
278 | ! |
teal.widgets::panel_item( |
279 | ! |
"Theoretical Distribution", |
280 | ! |
teal.widgets::optionalSelectInput( |
281 | ! |
ns("t_dist"), |
282 | ! |
tags$div( |
283 | ! |
class = "teal-tooltip", |
284 | ! |
tagList( |
285 | ! |
"Distribution:", |
286 | ! |
icon("circle-info"), |
287 | ! |
tags$span( |
288 | ! |
class = "tooltiptext", |
289 | ! |
"Default parameters are optimized with MASS::fitdistr function." |
290 |
) |
|
291 |
) |
|
292 |
), |
|
293 | ! |
choices = c("normal", "lognormal", "gamma", "unif"), |
294 | ! |
selected = NULL, |
295 | ! |
multiple = FALSE |
296 |
), |
|
297 | ! |
numericInput(ns("dist_param1"), label = "param1", value = NULL), |
298 | ! |
numericInput(ns("dist_param2"), label = "param2", value = NULL), |
299 | ! |
tags$span(actionButton(ns("params_reset"), "Default params")), |
300 | ! |
collapsed = FALSE |
301 |
) |
|
302 |
) |
|
303 |
), |
|
304 | ! |
teal.widgets::panel_item( |
305 | ! |
"Tests", |
306 | ! |
teal.widgets::optionalSelectInput( |
307 | ! |
ns("dist_tests"), |
308 | ! |
"Tests:", |
309 | ! |
choices = c( |
310 | ! |
"Shapiro-Wilk", |
311 | ! |
if (!is.null(args$strata_var)) "t-test (two-samples, not paired)", |
312 | ! |
if (!is.null(args$strata_var)) "one-way ANOVA", |
313 | ! |
if (!is.null(args$strata_var)) "Fligner-Killeen", |
314 | ! |
if (!is.null(args$strata_var)) "F-test", |
315 | ! |
"Kolmogorov-Smirnov (one-sample)", |
316 | ! |
"Anderson-Darling (one-sample)", |
317 | ! |
"Cramer-von Mises (one-sample)", |
318 | ! |
if (!is.null(args$strata_var)) "Kolmogorov-Smirnov (two-samples)" |
319 |
), |
|
320 | ! |
selected = NULL |
321 |
) |
|
322 |
), |
|
323 | ! |
teal.widgets::panel_item( |
324 | ! |
"Statistics Table", |
325 | ! |
sliderInput(ns("roundn"), "Round to n digits", min = 0, max = 10, value = 2) |
326 |
), |
|
327 | ! |
teal.widgets::panel_item( |
328 | ! |
title = "Plot settings", |
329 | ! |
selectInput( |
330 | ! |
inputId = ns("ggtheme"), |
331 | ! |
label = "Theme (by ggplot):", |
332 | ! |
choices = ggplot_themes, |
333 | ! |
selected = args$ggtheme, |
334 | ! |
multiple = FALSE |
335 |
) |
|
336 |
) |
|
337 |
), |
|
338 | ! |
forms = tagList( |
339 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
340 |
), |
|
341 | ! |
pre_output = args$pre_output, |
342 | ! |
post_output = args$post_output |
343 |
) |
|
344 |
} |
|
345 | ||
346 |
# Server function for the distribution module |
|
347 |
srv_distribution <- function(id, |
|
348 |
data, |
|
349 |
reporter, |
|
350 |
filter_panel_api, |
|
351 |
dist_var, |
|
352 |
strata_var, |
|
353 |
group_var, |
|
354 |
plot_height, |
|
355 |
plot_width, |
|
356 |
ggplot2_args) { |
|
357 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
358 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
359 | ! |
checkmate::assert_class(data, "reactive") |
360 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
361 | ! |
moduleServer(id, function(input, output, session) { |
362 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
363 | ||
364 | ! |
setBookmarkExclude("params_reset") |
365 | ||
366 | ! |
ns <- session$ns |
367 | ||
368 | ! |
rule_req <- function(value) { |
369 | ! |
if (isTRUE(input$dist_tests %in% c( |
370 | ! |
"Fligner-Killeen", |
371 | ! |
"t-test (two-samples, not paired)", |
372 | ! |
"F-test", |
373 | ! |
"Kolmogorov-Smirnov (two-samples)", |
374 | ! |
"one-way ANOVA" |
375 |
))) { |
|
376 | ! |
if (!shinyvalidate::input_provided(value)) { |
377 | ! |
"Please select stratify variable." |
378 |
} |
|
379 |
} |
|
380 |
} |
|
381 | ! |
rule_dupl <- function(...) { |
382 | ! |
if (identical(input$dist_tests, "Fligner-Killeen")) { |
383 | ! |
strata <- selector_list()$strata_i()$select |
384 | ! |
group <- selector_list()$group_i()$select |
385 | ! |
if (isTRUE(strata == group)) { |
386 | ! |
"Please select different variables for strata and group." |
387 |
} |
|
388 |
} |
|
389 |
} |
|
390 | ||
391 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
392 | ! |
data_extract = list( |
393 | ! |
dist_i = dist_var, |
394 | ! |
strata_i = strata_var, |
395 | ! |
group_i = group_var |
396 |
), |
|
397 | ! |
data, |
398 | ! |
select_validation_rule = list( |
399 | ! |
dist_i = shinyvalidate::sv_required("Please select a variable") |
400 |
), |
|
401 | ! |
filter_validation_rule = list( |
402 | ! |
strata_i = shinyvalidate::compose_rules( |
403 | ! |
rule_req, |
404 | ! |
rule_dupl |
405 |
), |
|
406 | ! |
group_i = rule_dupl |
407 |
) |
|
408 |
) |
|
409 | ||
410 | ! |
iv_r <- reactive({ |
411 | ! |
iv <- shinyvalidate::InputValidator$new() |
412 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list, validator_names = "dist_i") |
413 |
}) |
|
414 | ||
415 | ! |
iv_r_dist <- reactive({ |
416 | ! |
iv <- shinyvalidate::InputValidator$new() |
417 | ! |
teal.transform::compose_and_enable_validators( |
418 | ! |
iv, selector_list, |
419 | ! |
validator_names = c("strata_i", "group_i") |
420 |
) |
|
421 |
}) |
|
422 | ! |
rule_dist_1 <- function(value) { |
423 | ! |
if (!is.null(input$t_dist)) { |
424 | ! |
switch(input$t_dist, |
425 | ! |
"normal" = if (!shinyvalidate::input_provided(value)) "mean is required", |
426 | ! |
"lognormal" = if (!shinyvalidate::input_provided(value)) "meanlog is required", |
427 | ! |
"gamma" = { |
428 | ! |
if (!shinyvalidate::input_provided(value)) "shape is required" else if (value <= 0) "shape must be positive" |
429 |
}, |
|
430 | ! |
"unif" = NULL |
431 |
) |
|
432 |
} |
|
433 |
} |
|
434 | ! |
rule_dist_2 <- function(value) { |
435 | ! |
if (!is.null(input$t_dist)) { |
436 | ! |
switch(input$t_dist, |
437 | ! |
"normal" = { |
438 | ! |
if (!shinyvalidate::input_provided(value)) { |
439 | ! |
"sd is required" |
440 | ! |
} else if (value < 0) { |
441 | ! |
"sd must be non-negative" |
442 |
} |
|
443 |
}, |
|
444 | ! |
"lognormal" = { |
445 | ! |
if (!shinyvalidate::input_provided(value)) { |
446 | ! |
"sdlog is required" |
447 | ! |
} else if (value < 0) { |
448 | ! |
"sdlog must be non-negative" |
449 |
} |
|
450 |
}, |
|
451 | ! |
"gamma" = { |
452 | ! |
if (!shinyvalidate::input_provided(value)) { |
453 | ! |
"rate is required" |
454 | ! |
} else if (value <= 0) { |
455 | ! |
"rate must be positive" |
456 |
} |
|
457 |
}, |
|
458 | ! |
"unif" = NULL |
459 |
) |
|
460 |
} |
|
461 |
} |
|
462 | ! |
rule_dist <- function(value) { |
463 | ! |
if (isTRUE(input$tabs == "QQplot" || |
464 | ! |
input$dist_tests %in% c( |
465 | ! |
"Kolmogorov-Smirnov (one-sample)", |
466 | ! |
"Anderson-Darling (one-sample)", |
467 | ! |
"Cramer-von Mises (one-sample)" |
468 |
))) { |
|
469 | ! |
if (!shinyvalidate::input_provided(value)) { |
470 | ! |
"Please select the theoretical distribution." |
471 |
} |
|
472 |
} |
|
473 |
} |
|
474 | ! |
iv_dist <- shinyvalidate::InputValidator$new() |
475 | ! |
iv_dist$add_rule("t_dist", rule_dist) |
476 | ! |
iv_dist$add_rule("dist_param1", rule_dist_1) |
477 | ! |
iv_dist$add_rule("dist_param2", rule_dist_2) |
478 | ! |
iv_dist$enable() |
479 | ||
480 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
481 | ! |
selector_list = selector_list, |
482 | ! |
datasets = data |
483 |
) |
|
484 | ||
485 | ! |
anl_merged_q <- reactive({ |
486 | ! |
req(anl_merged_input()) |
487 | ! |
data() %>% |
488 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
489 |
}) |
|
490 | ||
491 | ! |
merged <- list( |
492 | ! |
anl_input_r = anl_merged_input, |
493 | ! |
anl_q_r = anl_merged_q |
494 |
) |
|
495 | ||
496 | ! |
output$scales_types_ui <- renderUI({ |
497 | ! |
if ("group_i" %in% names(selector_list()) && length(selector_list()$group_i()$filters[[1]]$selected) > 0) { |
498 | ! |
shinyWidgets::prettyRadioButtons( |
499 | ! |
ns("scales_type"), |
500 | ! |
label = "Scales:", |
501 | ! |
choices = c("Fixed", "Free"), |
502 | ! |
selected = "Fixed", |
503 | ! |
bigger = FALSE, |
504 | ! |
inline = TRUE |
505 |
) |
|
506 |
} |
|
507 |
}) |
|
508 | ||
509 | ! |
observeEvent( |
510 | ! |
eventExpr = list( |
511 | ! |
input$t_dist, |
512 | ! |
input$params_reset, |
513 | ! |
selector_list()$dist_i()$select |
514 |
), |
|
515 | ! |
handlerExpr = { |
516 | ! |
params <- |
517 | ! |
if (length(input$t_dist) != 0) { |
518 | ! |
get_dist_params <- function(x, dist) { |
519 | ! |
if (dist == "unif") { |
520 | ! |
return(stats::setNames(range(x, na.rm = TRUE), c("min", "max"))) |
521 |
} |
|
522 | ! |
tryCatch( |
523 | ! |
MASS::fitdistr(x, densfun = dist)$estimate, |
524 | ! |
error = function(e) c(param1 = NA_real_, param2 = NA_real_) |
525 |
) |
|
526 |
} |
|
527 | ||
528 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
529 | ! |
round(get_dist_params(as.numeric(stats::na.omit(ANL[[merge_vars()$dist_var]])), input$t_dist), 2) |
530 |
} else { |
|
531 | ! |
c("param1" = NA_real_, "param2" = NA_real_) |
532 |
} |
|
533 | ||
534 | ! |
params_vals <- unname(params) |
535 | ! |
params_names <- names(params) |
536 | ||
537 | ! |
updateNumericInput( |
538 | ! |
inputId = "dist_param1", |
539 | ! |
label = params_names[1], |
540 | ! |
value = restoreInput(ns("dist_param1"), params_vals[1]) |
541 |
) |
|
542 | ! |
updateNumericInput( |
543 | ! |
inputId = "dist_param2", |
544 | ! |
label = params_names[2], |
545 | ! |
value = restoreInput(ns("dist_param1"), params_vals[2]) |
546 |
) |
|
547 |
}, |
|
548 | ! |
ignoreInit = TRUE |
549 |
) |
|
550 | ||
551 | ! |
observeEvent(input$params_reset, { |
552 | ! |
updateActionButton(inputId = "params_reset", label = "Reset params") |
553 |
}) |
|
554 | ||
555 | ! |
merge_vars <- reactive({ |
556 | ! |
teal::validate_inputs(iv_r()) |
557 | ||
558 | ! |
dist_var <- as.vector(merged$anl_input_r()$columns_source$dist_i) |
559 | ! |
s_var <- as.vector(merged$anl_input_r()$columns_source$strata_i) |
560 | ! |
g_var <- as.vector(merged$anl_input_r()$columns_source$group_i) |
561 | ||
562 | ! |
dist_var_name <- if (length(dist_var)) as.name(dist_var) else NULL |
563 | ! |
s_var_name <- if (length(s_var)) as.name(s_var) else NULL |
564 | ! |
g_var_name <- if (length(g_var)) as.name(g_var) else NULL |
565 | ||
566 | ! |
list( |
567 | ! |
dist_var = dist_var, |
568 | ! |
s_var = s_var, |
569 | ! |
g_var = g_var, |
570 | ! |
dist_var_name = dist_var_name, |
571 | ! |
s_var_name = s_var_name, |
572 | ! |
g_var_name = g_var_name |
573 |
) |
|
574 |
}) |
|
575 | ||
576 |
# common qenv |
|
577 | ! |
common_q <- reactive({ |
578 |
# Create a private stack for this function only. |
|
579 | ||
580 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
581 | ! |
dist_var <- merge_vars()$dist_var |
582 | ! |
s_var <- merge_vars()$s_var |
583 | ! |
g_var <- merge_vars()$g_var |
584 | ||
585 | ! |
dist_var_name <- merge_vars()$dist_var_name |
586 | ! |
s_var_name <- merge_vars()$s_var_name |
587 | ! |
g_var_name <- merge_vars()$g_var_name |
588 | ||
589 | ! |
roundn <- input$roundn |
590 | ! |
dist_param1 <- input$dist_param1 |
591 | ! |
dist_param2 <- input$dist_param2 |
592 |
# isolated as dist_param1/dist_param2 already triggered the reactivity |
|
593 | ! |
t_dist <- isolate(input$t_dist) |
594 | ||
595 | ! |
qenv <- merged$anl_q_r() |
596 | ||
597 | ! |
if (length(g_var) > 0) { |
598 | ! |
validate( |
599 | ! |
need( |
600 | ! |
inherits(ANL[[g_var]], c("integer", "factor", "character")), |
601 | ! |
"Group by variable must be `factor`, `character`, or `integer`" |
602 |
) |
|
603 |
) |
|
604 | ! |
qenv <- teal.code::eval_code( |
605 | ! |
qenv, |
606 | ! |
substitute( |
607 | ! |
expr = ANL[[g_var]] <- forcats::fct_na_value_to_level(as.factor(ANL[[g_var]]), "NA"), |
608 | ! |
env = list(g_var = g_var) |
609 |
) |
|
610 |
) |
|
611 |
} |
|
612 | ||
613 | ! |
if (length(s_var) > 0) { |
614 | ! |
validate( |
615 | ! |
need( |
616 | ! |
inherits(ANL[[s_var]], c("integer", "factor", "character")), |
617 | ! |
"Stratify by variable must be `factor`, `character`, or `integer`" |
618 |
) |
|
619 |
) |
|
620 | ! |
qenv <- teal.code::eval_code( |
621 | ! |
qenv, |
622 | ! |
substitute( |
623 | ! |
expr = ANL[[s_var]] <- forcats::fct_na_value_to_level(as.factor(ANL[[s_var]]), "NA"), |
624 | ! |
env = list(s_var = s_var) |
625 |
) |
|
626 |
) |
|
627 |
} |
|
628 | ||
629 | ! |
validate(need(is.numeric(ANL[[dist_var]]), "Please select a numeric variable.")) |
630 | ! |
teal::validate_has_data(ANL, 1, complete = TRUE) |
631 | ||
632 | ! |
if (length(t_dist) != 0) { |
633 | ! |
map_distr_nams <- list( |
634 | ! |
normal = c("mean", "sd"), |
635 | ! |
lognormal = c("meanlog", "sdlog"), |
636 | ! |
gamma = c("shape", "rate"), |
637 | ! |
unif = c("min", "max") |
638 |
) |
|
639 | ! |
params_names_raw <- map_distr_nams[[t_dist]] |
640 | ||
641 | ! |
qenv <- teal.code::eval_code( |
642 | ! |
qenv, |
643 | ! |
substitute( |
644 | ! |
expr = { |
645 | ! |
params <- as.list(c(dist_param1, dist_param2)) |
646 | ! |
names(params) <- params_names_raw |
647 |
}, |
|
648 | ! |
env = list( |
649 | ! |
dist_param1 = dist_param1, |
650 | ! |
dist_param2 = dist_param2, |
651 | ! |
params_names_raw = params_names_raw |
652 |
) |
|
653 |
) |
|
654 |
) |
|
655 |
} |
|
656 | ||
657 | ! |
if (length(s_var) == 0 && length(g_var) == 0) { |
658 | ! |
qenv <- teal.code::eval_code( |
659 | ! |
qenv, |
660 | ! |
substitute( |
661 | ! |
expr = { |
662 | ! |
summary_table <- ANL %>% |
663 | ! |
dplyr::summarise( |
664 | ! |
min = round(min(dist_var_name, na.rm = TRUE), roundn), |
665 | ! |
median = round(stats::median(dist_var_name, na.rm = TRUE), roundn), |
666 | ! |
mean = round(mean(dist_var_name, na.rm = TRUE), roundn), |
667 | ! |
max = round(max(dist_var_name, na.rm = TRUE), roundn), |
668 | ! |
sd = round(stats::sd(dist_var_name, na.rm = TRUE), roundn), |
669 | ! |
count = dplyr::n() |
670 |
) |
|
671 |
}, |
|
672 | ! |
env = list( |
673 | ! |
dist_var_name = as.name(dist_var), |
674 | ! |
roundn = roundn |
675 |
) |
|
676 |
) |
|
677 |
) |
|
678 |
} else { |
|
679 | ! |
qenv <- teal.code::eval_code( |
680 | ! |
qenv, |
681 | ! |
substitute( |
682 | ! |
expr = { |
683 | ! |
strata_vars <- strata_vars_raw |
684 | ! |
summary_table <- ANL %>% |
685 | ! |
dplyr::group_by_at(dplyr::vars(dplyr::any_of(strata_vars))) %>% |
686 | ! |
dplyr::summarise( |
687 | ! |
min = round(min(dist_var_name, na.rm = TRUE), roundn), |
688 | ! |
median = round(stats::median(dist_var_name, na.rm = TRUE), roundn), |
689 | ! |
mean = round(mean(dist_var_name, na.rm = TRUE), roundn), |
690 | ! |
max = round(max(dist_var_name, na.rm = TRUE), roundn), |
691 | ! |
sd = round(stats::sd(dist_var_name, na.rm = TRUE), roundn), |
692 | ! |
count = dplyr::n() |
693 |
) |
|
694 | ! |
summary_table # used to display table when running show-r-code code |
695 |
}, |
|
696 | ! |
env = list( |
697 | ! |
dist_var_name = dist_var_name, |
698 | ! |
strata_vars_raw = c(g_var, s_var), |
699 | ! |
roundn = roundn |
700 |
) |
|
701 |
) |
|
702 |
) |
|
703 |
} |
|
704 |
}) |
|
705 | ||
706 |
# distplot qenv ---- |
|
707 | ! |
dist_q <- eventReactive( |
708 | ! |
eventExpr = { |
709 | ! |
common_q() |
710 | ! |
input$scales_type |
711 | ! |
input$main_type |
712 | ! |
input$bins |
713 | ! |
input$add_dens |
714 | ! |
is.null(input$ggtheme) |
715 |
}, |
|
716 | ! |
valueExpr = { |
717 | ! |
dist_var <- merge_vars()$dist_var |
718 | ! |
s_var <- merge_vars()$s_var |
719 | ! |
g_var <- merge_vars()$g_var |
720 | ! |
dist_var_name <- merge_vars()$dist_var_name |
721 | ! |
s_var_name <- merge_vars()$s_var_name |
722 | ! |
g_var_name <- merge_vars()$g_var_name |
723 | ! |
t_dist <- input$t_dist |
724 | ! |
dist_param1 <- input$dist_param1 |
725 | ! |
dist_param2 <- input$dist_param2 |
726 | ||
727 | ! |
scales_type <- input$scales_type |
728 | ||
729 | ! |
ndensity <- 512 |
730 | ! |
main_type_var <- input$main_type |
731 | ! |
bins_var <- input$bins |
732 | ! |
add_dens_var <- input$add_dens |
733 | ! |
ggtheme <- input$ggtheme |
734 | ||
735 | ! |
teal::validate_inputs(iv_dist) |
736 | ||
737 | ! |
qenv <- common_q() |
738 | ||
739 | ! |
m_type <- if (main_type_var == "Density") "density" else "count" |
740 | ||
741 | ! |
plot_call <- if (length(s_var) == 0 && length(g_var) == 0) { |
742 | ! |
substitute( |
743 | ! |
expr = ggplot(ANL, aes(dist_var_name)) + |
744 | ! |
geom_histogram( |
745 | ! |
position = "identity", aes(y = after_stat(m_type)), bins = bins_var, alpha = 0.3 |
746 |
), |
|
747 | ! |
env = list( |
748 | ! |
m_type = as.name(m_type), bins_var = bins_var, dist_var_name = as.name(dist_var) |
749 |
) |
|
750 |
) |
|
751 | ! |
} else if (length(s_var) != 0 && length(g_var) == 0) { |
752 | ! |
substitute( |
753 | ! |
expr = ggplot(ANL, aes(dist_var_name, col = s_var_name)) + |
754 | ! |
geom_histogram( |
755 | ! |
position = "identity", aes(y = after_stat(m_type), fill = s_var), bins = bins_var, alpha = 0.3 |
756 |
), |
|
757 | ! |
env = list( |
758 | ! |
m_type = as.name(m_type), |
759 | ! |
bins_var = bins_var, |
760 | ! |
dist_var_name = dist_var_name, |
761 | ! |
s_var = as.name(s_var), |
762 | ! |
s_var_name = s_var_name |
763 |
) |
|
764 |
) |
|
765 | ! |
} else if (length(s_var) == 0 && length(g_var) != 0) { |
766 | ! |
req(scales_type) |
767 | ! |
substitute( |
768 | ! |
expr = ggplot(ANL[ANL[[g_var]] != "NA", ], aes(dist_var_name)) + |
769 | ! |
geom_histogram( |
770 | ! |
position = "identity", aes(y = after_stat(m_type)), bins = bins_var, alpha = 0.3 |
771 |
) + |
|
772 | ! |
facet_wrap(~g_var_name, ncol = 1, scales = scales_raw), |
773 | ! |
env = list( |
774 | ! |
m_type = as.name(m_type), |
775 | ! |
bins_var = bins_var, |
776 | ! |
dist_var_name = dist_var_name, |
777 | ! |
g_var = g_var, |
778 | ! |
g_var_name = g_var_name, |
779 | ! |
scales_raw = tolower(scales_type) |
780 |
) |
|
781 |
) |
|
782 |
} else { |
|
783 | ! |
req(scales_type) |
784 | ! |
substitute( |
785 | ! |
expr = ggplot(ANL[ANL[[g_var]] != "NA", ], aes(dist_var_name, col = s_var_name)) + |
786 | ! |
geom_histogram( |
787 | ! |
position = "identity", |
788 | ! |
aes(y = after_stat(m_type), fill = s_var), bins = bins_var, alpha = 0.3 |
789 |
) + |
|
790 | ! |
facet_wrap(~g_var_name, ncol = 1, scales = scales_raw), |
791 | ! |
env = list( |
792 | ! |
m_type = as.name(m_type), |
793 | ! |
bins_var = bins_var, |
794 | ! |
dist_var_name = dist_var_name, |
795 | ! |
g_var = g_var, |
796 | ! |
s_var = as.name(s_var), |
797 | ! |
g_var_name = g_var_name, |
798 | ! |
s_var_name = s_var_name, |
799 | ! |
scales_raw = tolower(scales_type) |
800 |
) |
|
801 |
) |
|
802 |
} |
|
803 | ||
804 | ! |
if (add_dens_var) { |
805 | ! |
plot_call <- substitute( |
806 | ! |
expr = plot_call + |
807 | ! |
stat_density( |
808 | ! |
aes(y = after_stat(const * m_type2)), |
809 | ! |
geom = "line", |
810 | ! |
position = "identity", |
811 | ! |
alpha = 0.5, |
812 | ! |
size = 2, |
813 | ! |
n = ndensity |
814 |
), |
|
815 | ! |
env = list( |
816 | ! |
plot_call = plot_call, |
817 | ! |
const = if (main_type_var == "Density") { |
818 | ! |
1 |
819 |
} else { |
|
820 | ! |
diff(range(qenv[["ANL"]][[dist_var]], na.rm = TRUE)) / bins_var |
821 |
}, |
|
822 | ! |
m_type2 = if (main_type_var == "Density") as.name("density") else as.name("count"), |
823 | ! |
ndensity = ndensity |
824 |
) |
|
825 |
) |
|
826 |
} |
|
827 | ||
828 | ! |
if (length(t_dist) != 0 && main_type_var == "Density" && length(g_var) == 0 && length(s_var) == 0) { |
829 | ! |
qenv <- teal.code::eval_code( |
830 | ! |
qenv, |
831 | ! |
substitute( |
832 | ! |
df_params <- as.data.frame(append(params, list(name = t_dist))), |
833 | ! |
env = list(t_dist = t_dist) |
834 |
) |
|
835 |
) |
|
836 | ! |
datas <- quote(data.frame(x = 0.7, y = 1, tb = I(list(df_params = df_params)))) |
837 | ! |
label <- quote(tb) |
838 | ||
839 | ! |
plot_call <- substitute( |
840 | ! |
expr = plot_call + ggpp::geom_table_npc( |
841 | ! |
data = data, |
842 | ! |
aes(npcx = x, npcy = y, label = label), |
843 | ! |
hjust = 0, vjust = 1, size = 4 |
844 |
), |
|
845 | ! |
env = list(plot_call = plot_call, data = datas, label = label) |
846 |
) |
|
847 |
} |
|
848 | ||
849 | ! |
if ( |
850 | ! |
length(s_var) == 0 && |
851 | ! |
length(g_var) == 0 && |
852 | ! |
main_type_var == "Density" && |
853 | ! |
length(t_dist) != 0 && |
854 | ! |
main_type_var == "Density" |
855 |
) { |
|
856 | ! |
map_dist <- stats::setNames( |
857 | ! |
c("dnorm", "dlnorm", "dgamma", "dunif"), |
858 | ! |
c("normal", "lognormal", "gamma", "unif") |
859 |
) |
|
860 | ! |
plot_call <- substitute( |
861 | ! |
expr = plot_call + stat_function( |
862 | ! |
data = data.frame(x = range(ANL[[dist_var]]), color = mapped_dist), |
863 | ! |
aes(x, color = color), |
864 | ! |
fun = mapped_dist_name, |
865 | ! |
n = ndensity, |
866 | ! |
size = 2, |
867 | ! |
args = params |
868 |
) + |
|
869 | ! |
scale_color_manual(values = stats::setNames("blue", mapped_dist), aesthetics = "color"), |
870 | ! |
env = list( |
871 | ! |
plot_call = plot_call, |
872 | ! |
dist_var = dist_var, |
873 | ! |
ndensity = ndensity, |
874 | ! |
mapped_dist = unname(map_dist[t_dist]), |
875 | ! |
mapped_dist_name = as.name(unname(map_dist[t_dist])) |
876 |
) |
|
877 |
) |
|
878 |
} |
|
879 | ||
880 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
881 | ! |
user_plot = ggplot2_args[["Histogram"]], |
882 | ! |
user_default = ggplot2_args$default |
883 |
) |
|
884 | ||
885 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
886 | ! |
all_ggplot2_args, |
887 | ! |
ggtheme = ggtheme |
888 |
) |
|
889 | ||
890 | ! |
teal.code::eval_code( |
891 | ! |
qenv, |
892 | ! |
substitute( |
893 | ! |
expr = { |
894 | ! |
g <- plot_call |
895 | ! |
print(g) |
896 |
}, |
|
897 | ! |
env = list(plot_call = Reduce(function(x, y) call("+", x, y), c(plot_call, parsed_ggplot2_args))) |
898 |
) |
|
899 |
) |
|
900 |
} |
|
901 |
) |
|
902 | ||
903 |
# qqplot qenv ---- |
|
904 | ! |
qq_q <- eventReactive( |
905 | ! |
eventExpr = { |
906 | ! |
common_q() |
907 | ! |
input$scales_type |
908 | ! |
input$qq_line |
909 | ! |
is.null(input$ggtheme) |
910 |
}, |
|
911 | ! |
valueExpr = { |
912 | ! |
dist_var <- merge_vars()$dist_var |
913 | ! |
s_var <- merge_vars()$s_var |
914 | ! |
g_var <- merge_vars()$g_var |
915 | ! |
dist_var_name <- merge_vars()$dist_var_name |
916 | ! |
s_var_name <- merge_vars()$s_var_name |
917 | ! |
g_var_name <- merge_vars()$g_var_name |
918 | ! |
t_dist <- input$t_dist |
919 | ! |
dist_param1 <- input$dist_param1 |
920 | ! |
dist_param2 <- input$dist_param2 |
921 | ||
922 | ! |
scales_type <- input$scales_type |
923 | ! |
ggtheme <- input$ggtheme |
924 | ||
925 | ! |
teal::validate_inputs(iv_r_dist(), iv_dist) |
926 | ||
927 | ! |
qenv <- common_q() |
928 | ||
929 | ! |
plot_call <- if (length(s_var) == 0 && length(g_var) == 0) { |
930 | ! |
substitute( |
931 | ! |
expr = ggplot(ANL, aes_string(sample = dist_var)), |
932 | ! |
env = list(dist_var = dist_var) |
933 |
) |
|
934 | ! |
} else if (length(s_var) != 0 && length(g_var) == 0) { |
935 | ! |
substitute( |
936 | ! |
expr = ggplot(ANL, aes_string(sample = dist_var, color = s_var)), |
937 | ! |
env = list(dist_var = dist_var, s_var = s_var) |
938 |
) |
|
939 | ! |
} else if (length(s_var) == 0 && length(g_var) != 0) { |
940 | ! |
substitute( |
941 | ! |
expr = ggplot(ANL[ANL[[g_var]] != "NA", ], aes_string(sample = dist_var)) + |
942 | ! |
facet_wrap(~g_var_name, ncol = 1, scales = scales_raw), |
943 | ! |
env = list( |
944 | ! |
dist_var = dist_var, |
945 | ! |
g_var = g_var, |
946 | ! |
g_var_name = g_var_name, |
947 | ! |
scales_raw = tolower(scales_type) |
948 |
) |
|
949 |
) |
|
950 |
} else { |
|
951 | ! |
substitute( |
952 | ! |
expr = ggplot(ANL[ANL[[g_var]] != "NA", ], aes_string(sample = dist_var, color = s_var)) + |
953 | ! |
facet_wrap(~g_var_name, ncol = 1, scales = scales_raw), |
954 | ! |
env = list( |
955 | ! |
dist_var = dist_var, |
956 | ! |
g_var = g_var, |
957 | ! |
s_var = s_var, |
958 | ! |
g_var_name = g_var_name, |
959 | ! |
scales_raw = tolower(scales_type) |
960 |
) |
|
961 |
) |
|
962 |
} |
|
963 | ||
964 | ! |
map_dist <- stats::setNames( |
965 | ! |
c("qnorm", "qlnorm", "qgamma", "qunif"), |
966 | ! |
c("normal", "lognormal", "gamma", "unif") |
967 |
) |
|
968 | ||
969 | ! |
plot_call <- substitute( |
970 | ! |
expr = plot_call + |
971 | ! |
stat_qq(distribution = mapped_dist, dparams = params), |
972 | ! |
env = list(plot_call = plot_call, mapped_dist = as.name(unname(map_dist[t_dist]))) |
973 |
) |
|
974 | ||
975 | ! |
if (length(t_dist) != 0 && length(g_var) == 0 && length(s_var) == 0) { |
976 | ! |
qenv <- teal.code::eval_code( |
977 | ! |
qenv, |
978 | ! |
substitute( |
979 | ! |
df_params <- as.data.frame(append(params, list(name = t_dist))), |
980 | ! |
env = list(t_dist = t_dist) |
981 |
) |
|
982 |
) |
|
983 | ! |
datas <- quote(data.frame(x = 0.7, y = 1, tb = I(list(df_params = df_params)))) |
984 | ! |
label <- quote(tb) |
985 | ||
986 | ! |
plot_call <- substitute( |
987 | ! |
expr = plot_call + |
988 | ! |
ggpp::geom_table_npc( |
989 | ! |
data = data, |
990 | ! |
aes(npcx = x, npcy = y, label = label), |
991 | ! |
hjust = 0, |
992 | ! |
vjust = 1, |
993 | ! |
size = 4 |
994 |
), |
|
995 | ! |
env = list( |
996 | ! |
plot_call = plot_call, |
997 | ! |
data = datas, |
998 | ! |
label = label |
999 |
) |
|
1000 |
) |
|
1001 |
} |
|
1002 | ||
1003 | ! |
if (isTRUE(input$qq_line)) { |
1004 | ! |
plot_call <- substitute( |
1005 | ! |
expr = plot_call + |
1006 | ! |
stat_qq_line(distribution = mapped_dist, dparams = params), |
1007 | ! |
env = list(plot_call = plot_call, mapped_dist = as.name(unname(map_dist[t_dist]))) |
1008 |
) |
|
1009 |
} |
|
1010 | ||
1011 | ! |
all_ggplot2_args <- teal.widgets::resolve_ggplot2_args( |
1012 | ! |
user_plot = ggplot2_args[["QQplot"]], |
1013 | ! |
user_default = ggplot2_args$default, |
1014 | ! |
module_plot = teal.widgets::ggplot2_args(labs = list(x = "theoretical", y = "sample")) |
1015 |
) |
|
1016 | ||
1017 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
1018 | ! |
all_ggplot2_args, |
1019 | ! |
ggtheme = ggtheme |
1020 |
) |
|
1021 | ||
1022 | ! |
teal.code::eval_code( |
1023 | ! |
qenv, |
1024 | ! |
substitute( |
1025 | ! |
expr = { |
1026 | ! |
g <- plot_call |
1027 | ! |
print(g) |
1028 |
}, |
|
1029 | ! |
env = list(plot_call = Reduce(function(x, y) call("+", x, y), c(plot_call, parsed_ggplot2_args))) |
1030 |
) |
|
1031 |
) |
|
1032 |
} |
|
1033 |
) |
|
1034 | ||
1035 |
# test qenv ---- |
|
1036 | ! |
test_q <- eventReactive( |
1037 | ! |
ignoreNULL = FALSE, |
1038 | ! |
eventExpr = { |
1039 | ! |
common_q() |
1040 | ! |
input$dist_param1 |
1041 | ! |
input$dist_param2 |
1042 | ! |
input$dist_tests |
1043 |
}, |
|
1044 | ! |
valueExpr = { |
1045 |
# Create a private stack for this function only. |
|
1046 | ! |
ANL <- common_q()[["ANL"]] |
1047 | ||
1048 | ! |
dist_var <- merge_vars()$dist_var |
1049 | ! |
s_var <- merge_vars()$s_var |
1050 | ! |
g_var <- merge_vars()$g_var |
1051 | ||
1052 | ! |
dist_var_name <- merge_vars()$dist_var_name |
1053 | ! |
s_var_name <- merge_vars()$s_var_name |
1054 | ! |
g_var_name <- merge_vars()$g_var_name |
1055 | ||
1056 | ! |
dist_param1 <- input$dist_param1 |
1057 | ! |
dist_param2 <- input$dist_param2 |
1058 | ! |
dist_tests <- input$dist_tests |
1059 | ! |
t_dist <- input$t_dist |
1060 | ||
1061 | ! |
validate(need(dist_tests, "Please select a test")) |
1062 | ||
1063 | ! |
teal::validate_inputs(iv_dist) |
1064 | ||
1065 | ! |
if (length(s_var) > 0 || length(g_var) > 0) { |
1066 | ! |
counts <- ANL %>% |
1067 | ! |
dplyr::group_by_at(dplyr::vars(dplyr::any_of(c(s_var, g_var)))) %>% |
1068 | ! |
dplyr::summarise(n = dplyr::n()) |
1069 | ||
1070 | ! |
validate(need(all(counts$n > 5), "Please select strata*group with at least 5 observation each.")) |
1071 |
} |
|
1072 | ||
1073 | ||
1074 | ! |
if (dist_tests %in% c( |
1075 | ! |
"t-test (two-samples, not paired)", |
1076 | ! |
"F-test", |
1077 | ! |
"Kolmogorov-Smirnov (two-samples)" |
1078 |
)) { |
|
1079 | ! |
if (length(g_var) == 0 && length(s_var) > 0) { |
1080 | ! |
validate(need( |
1081 | ! |
length(unique(ANL[[s_var]])) == 2, |
1082 | ! |
"Please select stratify variable with 2 levels." |
1083 |
)) |
|
1084 |
} |
|
1085 | ! |
if (length(g_var) > 0 && length(s_var) > 0) { |
1086 | ! |
validate(need( |
1087 | ! |
all(stats::na.omit(as.vector( |
1088 | ! |
tapply(ANL[[s_var]], list(ANL[[g_var]]), function(x) length(unique(x))) == 2 |
1089 |
))), |
|
1090 | ! |
"Please select stratify variable with 2 levels, per each group." |
1091 |
)) |
|
1092 |
} |
|
1093 |
} |
|
1094 | ||
1095 | ! |
map_dist <- stats::setNames( |
1096 | ! |
c("pnorm", "plnorm", "pgamma", "punif"), |
1097 | ! |
c("normal", "lognormal", "gamma", "unif") |
1098 |
) |
|
1099 | ! |
sks_args <- list( |
1100 | ! |
test = quote(stats::ks.test), |
1101 | ! |
args = bquote(append(list(.[[.(dist_var)]], .(map_dist[t_dist])), params)), |
1102 | ! |
groups = c(g_var, s_var) |
1103 |
) |
|
1104 | ! |
ssw_args <- list( |
1105 | ! |
test = quote(stats::shapiro.test), |
1106 | ! |
args = bquote(list(.[[.(dist_var)]])), |
1107 | ! |
groups = c(g_var, s_var) |
1108 |
) |
|
1109 | ! |
mfil_args <- list( |
1110 | ! |
test = quote(stats::fligner.test), |
1111 | ! |
args = bquote(list(.[[.(dist_var)]], .[[.(s_var)]])), |
1112 | ! |
groups = c(g_var) |
1113 |
) |
|
1114 | ! |
sad_args <- list( |
1115 | ! |
test = quote(goftest::ad.test), |
1116 | ! |
args = bquote(append(list(.[[.(dist_var)]], .(map_dist[t_dist])), params)), |
1117 | ! |
groups = c(g_var, s_var) |
1118 |
) |
|
1119 | ! |
scvm_args <- list( |
1120 | ! |
test = quote(goftest::cvm.test), |
1121 | ! |
args = bquote(append(list(.[[.(dist_var)]], .(map_dist[t_dist])), params)), |
1122 | ! |
groups = c(g_var, s_var) |
1123 |
) |
|
1124 | ! |
manov_args <- list( |
1125 | ! |
test = quote(stats::aov), |
1126 | ! |
args = bquote(list(stats::formula(.(dist_var_name) ~ .(s_var_name)), .)), |
1127 | ! |
groups = c(g_var) |
1128 |
) |
|
1129 | ! |
mt_args <- list( |
1130 | ! |
test = quote(stats::t.test), |
1131 | ! |
args = bquote(unname(split(.[[.(dist_var)]], .[[.(s_var)]], drop = TRUE))), |
1132 | ! |
groups = c(g_var) |
1133 |
) |
|
1134 | ! |
mv_args <- list( |
1135 | ! |
test = quote(stats::var.test), |
1136 | ! |
args = bquote(unname(split(.[[.(dist_var)]], .[[.(s_var)]], drop = TRUE))), |
1137 | ! |
groups = c(g_var) |
1138 |
) |
|
1139 | ! |
mks_args <- list( |
1140 | ! |
test = quote(stats::ks.test), |
1141 | ! |
args = bquote(unname(split(.[[.(dist_var)]], .[[.(s_var)]], drop = TRUE))), |
1142 | ! |
groups = c(g_var) |
1143 |
) |
|
1144 | ||
1145 | ! |
tests_base <- switch(dist_tests, |
1146 | ! |
"Kolmogorov-Smirnov (one-sample)" = sks_args, |
1147 | ! |
"Shapiro-Wilk" = ssw_args, |
1148 | ! |
"Fligner-Killeen" = mfil_args, |
1149 | ! |
"one-way ANOVA" = manov_args, |
1150 | ! |
"t-test (two-samples, not paired)" = mt_args, |
1151 | ! |
"F-test" = mv_args, |
1152 | ! |
"Kolmogorov-Smirnov (two-samples)" = mks_args, |
1153 | ! |
"Anderson-Darling (one-sample)" = sad_args, |
1154 | ! |
"Cramer-von Mises (one-sample)" = scvm_args |
1155 |
) |
|
1156 | ||
1157 | ! |
env <- list( |
1158 | ! |
t_test = t_dist, |
1159 | ! |
dist_var = dist_var, |
1160 | ! |
g_var = g_var, |
1161 | ! |
s_var = s_var, |
1162 | ! |
args = tests_base$args, |
1163 | ! |
groups = tests_base$groups, |
1164 | ! |
test = tests_base$test, |
1165 | ! |
dist_var_name = dist_var_name, |
1166 | ! |
g_var_name = g_var_name, |
1167 | ! |
s_var_name = s_var_name |
1168 |
) |
|
1169 | ||
1170 | ! |
qenv <- common_q() |
1171 | ||
1172 | ! |
if (length(s_var) == 0 && length(g_var) == 0) { |
1173 | ! |
qenv <- teal.code::eval_code( |
1174 | ! |
qenv, |
1175 | ! |
substitute( |
1176 | ! |
expr = { |
1177 | ! |
test_stats <- ANL %>% |
1178 | ! |
dplyr::select(dist_var) %>% |
1179 | ! |
with(., broom::glance(do.call(test, args))) %>% |
1180 | ! |
dplyr::mutate_if(is.numeric, round, 3) |
1181 |
}, |
|
1182 | ! |
env = env |
1183 |
) |
|
1184 |
) |
|
1185 |
} else { |
|
1186 | ! |
qenv <- teal.code::eval_code( |
1187 | ! |
qenv, |
1188 | ! |
substitute( |
1189 | ! |
expr = { |
1190 | ! |
test_stats <- ANL %>% |
1191 | ! |
dplyr::select(dist_var, s_var, g_var) %>% |
1192 | ! |
dplyr::group_by_at(dplyr::vars(dplyr::any_of(groups))) %>% |
1193 | ! |
dplyr::do(tests = broom::glance(do.call(test, args))) %>% |
1194 | ! |
tidyr::unnest(tests) %>% |
1195 | ! |
dplyr::mutate_if(is.numeric, round, 3) |
1196 |
}, |
|
1197 | ! |
env = env |
1198 |
) |
|
1199 |
) |
|
1200 |
} |
|
1201 | ! |
qenv %>% |
1202 |
# used to display table when running show-r-code code |
|
1203 | ! |
teal.code::eval_code(quote(test_stats)) |
1204 |
} |
|
1205 |
) |
|
1206 | ||
1207 |
# outputs ---- |
|
1208 |
## building main qenv |
|
1209 | ! |
output_q <- reactive({ |
1210 | ! |
tab <- input$tabs |
1211 | ! |
req(tab) # tab is NULL upon app launch, hence will crash without this statement |
1212 | ||
1213 | ! |
qenv_final <- common_q() |
1214 |
# wrapped in if since could lead into validate error - we do want to continue |
|
1215 | ! |
test_r_qenv_out <- try(test_q(), silent = TRUE) |
1216 | ! |
if (!inherits(test_r_qenv_out, c("try-error", "error"))) { |
1217 | ! |
qenv_final <- c(qenv_final, test_q()) |
1218 |
} |
|
1219 | ||
1220 | ! |
qenv_final <- if (tab == "Histogram") { |
1221 | ! |
req(dist_q()) |
1222 | ! |
c(qenv_final, dist_q()) |
1223 | ! |
} else if (tab == "QQplot") { |
1224 | ! |
req(qq_q()) |
1225 | ! |
c(qenv_final, qq_q()) |
1226 |
} |
|
1227 | ! |
qenv_final |
1228 |
}) |
|
1229 | ||
1230 | ! |
dist_r <- reactive(dist_q()[["g"]]) |
1231 | ||
1232 | ! |
qq_r <- reactive(qq_q()[["g"]]) |
1233 | ||
1234 | ! |
output$summary_table <- DT::renderDataTable( |
1235 | ! |
expr = if (iv_r()$is_valid()) common_q()[["summary_table"]] else NULL, |
1236 | ! |
options = list( |
1237 | ! |
autoWidth = TRUE, |
1238 | ! |
columnDefs = list(list(width = "200px", targets = "_all")) |
1239 |
), |
|
1240 | ! |
rownames = FALSE |
1241 |
) |
|
1242 | ||
1243 | ! |
tests_r <- reactive({ |
1244 | ! |
req(iv_r()$is_valid()) |
1245 | ! |
teal::validate_inputs(iv_r_dist()) |
1246 | ! |
test_q()[["test_stats"]] |
1247 |
}) |
|
1248 | ||
1249 | ! |
pws1 <- teal.widgets::plot_with_settings_srv( |
1250 | ! |
id = "hist_plot", |
1251 | ! |
plot_r = dist_r, |
1252 | ! |
height = plot_height, |
1253 | ! |
width = plot_width, |
1254 | ! |
brushing = FALSE |
1255 |
) |
|
1256 | ||
1257 | ! |
pws2 <- teal.widgets::plot_with_settings_srv( |
1258 | ! |
id = "qq_plot", |
1259 | ! |
plot_r = qq_r, |
1260 | ! |
height = plot_height, |
1261 | ! |
width = plot_width, |
1262 | ! |
brushing = FALSE |
1263 |
) |
|
1264 | ||
1265 | ! |
output$t_stats <- DT::renderDataTable( |
1266 | ! |
expr = tests_r(), |
1267 | ! |
options = list(scrollX = TRUE), |
1268 | ! |
rownames = FALSE |
1269 |
) |
|
1270 | ||
1271 | ! |
teal.widgets::verbatim_popup_srv( |
1272 | ! |
id = "rcode", |
1273 | ! |
verbatim_content = reactive(teal.code::get_code(output_q())), |
1274 | ! |
title = "R Code for distribution" |
1275 |
) |
|
1276 | ||
1277 |
### REPORTER |
|
1278 | ! |
if (with_reporter) { |
1279 | ! |
card_fun <- function(comment, label) { |
1280 | ! |
card <- teal::report_card_template( |
1281 | ! |
title = "Distribution Plot", |
1282 | ! |
label = label, |
1283 | ! |
with_filter = with_filter, |
1284 | ! |
filter_panel_api = filter_panel_api |
1285 |
) |
|
1286 | ! |
card$append_text("Plot", "header3") |
1287 | ! |
if (input$tabs == "Histogram") { |
1288 | ! |
card$append_plot(dist_r(), dim = pws1$dim()) |
1289 | ! |
} else if (input$tabs == "QQplot") { |
1290 | ! |
card$append_plot(qq_r(), dim = pws2$dim()) |
1291 |
} |
|
1292 | ! |
card$append_text("Statistics table", "header3") |
1293 | ||
1294 | ! |
card$append_table(common_q()[["summary_table"]]) |
1295 | ! |
tests_error <- tryCatch(expr = tests_r(), error = function(e) "error") |
1296 | ! |
if (inherits(tests_error, "data.frame")) { |
1297 | ! |
card$append_text("Tests table", "header3") |
1298 | ! |
card$append_table(tests_r()) |
1299 |
} |
|
1300 | ||
1301 | ! |
if (!comment == "") { |
1302 | ! |
card$append_text("Comment", "header3") |
1303 | ! |
card$append_text(comment) |
1304 |
} |
|
1305 | ! |
card$append_src(teal.code::get_code(output_q())) |
1306 | ! |
card |
1307 |
} |
|
1308 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
1309 |
} |
|
1310 |
### |
|
1311 |
}) |
|
1312 |
} |
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 |
#' @examplesShinylive |
|
29 |
#' library(teal.modules.general) |
|
30 |
#' interactive <- function() TRUE |
|
31 |
#' {{ next_example }} |
|
32 |
#' @examplesIf require("rtables", quietly = TRUE) |
|
33 |
#' # general data example |
|
34 |
#' data <- teal_data() |
|
35 |
#' data <- within(data, { |
|
36 |
#' mtcars <- mtcars |
|
37 |
#' for (v in c("cyl", "vs", "am", "gear")) { |
|
38 |
#' mtcars[[v]] <- as.factor(mtcars[[v]]) |
|
39 |
#' } |
|
40 |
#' mtcars[["primary_key"]] <- seq_len(nrow(mtcars)) |
|
41 |
#' }) |
|
42 |
#' join_keys(data) <- join_keys(join_key("mtcars", "mtcars", "primary_key")) |
|
43 |
#' |
|
44 |
#' app <- init( |
|
45 |
#' data = data, |
|
46 |
#' modules = modules( |
|
47 |
#' tm_t_crosstable( |
|
48 |
#' label = "Cross Table", |
|
49 |
#' x = data_extract_spec( |
|
50 |
#' dataname = "mtcars", |
|
51 |
#' select = select_spec( |
|
52 |
#' label = "Select variable:", |
|
53 |
#' choices = variable_choices(data[["mtcars"]], c("cyl", "vs", "am", "gear")), |
|
54 |
#' selected = c("cyl", "gear"), |
|
55 |
#' multiple = TRUE, |
|
56 |
#' ordered = TRUE, |
|
57 |
#' fixed = FALSE |
|
58 |
#' ) |
|
59 |
#' ), |
|
60 |
#' y = data_extract_spec( |
|
61 |
#' dataname = "mtcars", |
|
62 |
#' select = select_spec( |
|
63 |
#' label = "Select variable:", |
|
64 |
#' choices = variable_choices(data[["mtcars"]], c("cyl", "vs", "am", "gear")), |
|
65 |
#' selected = "vs", |
|
66 |
#' multiple = FALSE, |
|
67 |
#' fixed = FALSE |
|
68 |
#' ) |
|
69 |
#' ) |
|
70 |
#' ) |
|
71 |
#' ) |
|
72 |
#' ) |
|
73 |
#' if (interactive()) { |
|
74 |
#' shinyApp(app$ui, app$server) |
|
75 |
#' } |
|
76 |
#' |
|
77 |
#' @examplesShinylive |
|
78 |
#' library(teal.modules.general) |
|
79 |
#' interactive <- function() TRUE |
|
80 |
#' {{ next_example }} |
|
81 |
#' @examplesIf require("rtables", quietly = TRUE) |
|
82 |
#' # CDISC data example |
|
83 |
#' data <- teal_data() |
|
84 |
#' data <- within(data, { |
|
85 |
#' ADSL <- rADSL |
|
86 |
#' }) |
|
87 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
88 |
#' |
|
89 |
#' app <- init( |
|
90 |
#' data = data, |
|
91 |
#' modules = modules( |
|
92 |
#' tm_t_crosstable( |
|
93 |
#' label = "Cross Table", |
|
94 |
#' x = data_extract_spec( |
|
95 |
#' dataname = "ADSL", |
|
96 |
#' select = select_spec( |
|
97 |
#' label = "Select variable:", |
|
98 |
#' choices = variable_choices(data[["ADSL"]], subset = function(data) { |
|
99 |
#' idx <- !vapply(data, inherits, logical(1), c("Date", "POSIXct", "POSIXlt")) |
|
100 |
#' return(names(data)[idx]) |
|
101 |
#' }), |
|
102 |
#' selected = "COUNTRY", |
|
103 |
#' multiple = TRUE, |
|
104 |
#' ordered = TRUE, |
|
105 |
#' fixed = FALSE |
|
106 |
#' ) |
|
107 |
#' ), |
|
108 |
#' y = data_extract_spec( |
|
109 |
#' dataname = "ADSL", |
|
110 |
#' select = select_spec( |
|
111 |
#' label = "Select variable:", |
|
112 |
#' choices = variable_choices(data[["ADSL"]], subset = function(data) { |
|
113 |
#' idx <- vapply(data, is.factor, logical(1)) |
|
114 |
#' return(names(data)[idx]) |
|
115 |
#' }), |
|
116 |
#' selected = "SEX", |
|
117 |
#' multiple = FALSE, |
|
118 |
#' fixed = FALSE |
|
119 |
#' ) |
|
120 |
#' ) |
|
121 |
#' ) |
|
122 |
#' ) |
|
123 |
#' ) |
|
124 |
#' if (interactive()) { |
|
125 |
#' shinyApp(app$ui, app$server) |
|
126 |
#' } |
|
127 |
#' |
|
128 |
#' @export |
|
129 |
#' |
|
130 |
tm_t_crosstable <- function(label = "Cross Table", |
|
131 |
x, |
|
132 |
y, |
|
133 |
show_percentage = TRUE, |
|
134 |
show_total = TRUE, |
|
135 |
pre_output = NULL, |
|
136 |
post_output = NULL, |
|
137 |
basic_table_args = teal.widgets::basic_table_args()) { |
|
138 | ! |
message("Initializing tm_t_crosstable") |
139 | ||
140 |
# Requires Suggested packages |
|
141 | ! |
if (!requireNamespace("rtables", quietly = TRUE)) { |
142 | ! |
stop("Cannot load rtables - please install the package or restart your session.") |
143 |
} |
|
144 | ||
145 |
# Normalize the parameters |
|
146 | ! |
if (inherits(x, "data_extract_spec")) x <- list(x) |
147 | ! |
if (inherits(y, "data_extract_spec")) y <- list(y) |
148 | ||
149 |
# Start of assertions |
|
150 | ! |
checkmate::assert_string(label) |
151 | ! |
checkmate::assert_list(x, types = "data_extract_spec") |
152 | ||
153 | ! |
checkmate::assert_list(y, types = "data_extract_spec") |
154 | ! |
assert_single_selection(y) |
155 | ||
156 | ! |
checkmate::assert_flag(show_percentage) |
157 | ! |
checkmate::assert_flag(show_total) |
158 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
159 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
160 | ! |
checkmate::assert_class(basic_table_args, classes = "basic_table_args") |
161 |
# End of assertions |
|
162 | ||
163 |
# Make UI args |
|
164 | ! |
ui_args <- as.list(environment()) |
165 | ||
166 | ! |
server_args <- list( |
167 | ! |
label = label, |
168 | ! |
x = x, |
169 | ! |
y = y, |
170 | ! |
basic_table_args = basic_table_args |
171 |
) |
|
172 | ||
173 | ! |
ans <- module( |
174 | ! |
label = label, |
175 | ! |
server = srv_t_crosstable, |
176 | ! |
ui = ui_t_crosstable, |
177 | ! |
ui_args = ui_args, |
178 | ! |
server_args = server_args, |
179 | ! |
datanames = teal.transform::get_extract_datanames(list(x = x, y = y)) |
180 |
) |
|
181 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
182 | ! |
ans |
183 |
} |
|
184 | ||
185 |
# UI function for the cross-table module |
|
186 |
ui_t_crosstable <- function(id, x, y, show_percentage, show_total, pre_output, post_output, ...) { |
|
187 | ! |
ns <- NS(id) |
188 | ! |
is_single_dataset <- teal.transform::is_single_dataset(x, y) |
189 | ||
190 | ! |
join_default_options <- c( |
191 | ! |
"Full Join" = "dplyr::full_join", |
192 | ! |
"Inner Join" = "dplyr::inner_join", |
193 | ! |
"Left Join" = "dplyr::left_join", |
194 | ! |
"Right Join" = "dplyr::right_join" |
195 |
) |
|
196 | ||
197 | ! |
teal.widgets::standard_layout( |
198 | ! |
output = teal.widgets::white_small_well( |
199 | ! |
textOutput(ns("title")), |
200 | ! |
teal.widgets::table_with_settings_ui(ns("table")) |
201 |
), |
|
202 | ! |
encoding = tags$div( |
203 |
### Reporter |
|
204 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
205 |
### |
|
206 | ! |
tags$label("Encodings", class = "text-primary"), |
207 | ! |
teal.transform::datanames_input(list(x, y)), |
208 | ! |
teal.transform::data_extract_ui(ns("x"), label = "Row values", x, is_single_dataset = is_single_dataset), |
209 | ! |
teal.transform::data_extract_ui(ns("y"), label = "Column values", y, is_single_dataset = is_single_dataset), |
210 | ! |
teal.widgets::optionalSelectInput( |
211 | ! |
ns("join_fun"), |
212 | ! |
label = "Row to Column type of join", |
213 | ! |
choices = join_default_options, |
214 | ! |
selected = join_default_options[1], |
215 | ! |
multiple = FALSE |
216 |
), |
|
217 | ! |
tags$hr(), |
218 | ! |
teal.widgets::panel_group( |
219 | ! |
teal.widgets::panel_item( |
220 | ! |
title = "Table settings", |
221 | ! |
checkboxInput(ns("show_percentage"), "Show column percentage", value = show_percentage), |
222 | ! |
checkboxInput(ns("show_total"), "Show total column", value = show_total) |
223 |
) |
|
224 |
) |
|
225 |
), |
|
226 | ! |
forms = tagList( |
227 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
228 |
), |
|
229 | ! |
pre_output = pre_output, |
230 | ! |
post_output = post_output |
231 |
) |
|
232 |
} |
|
233 | ||
234 |
# Server function for the cross-table module |
|
235 |
srv_t_crosstable <- function(id, data, reporter, filter_panel_api, label, x, y, basic_table_args) { |
|
236 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
237 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
238 | ! |
checkmate::assert_class(data, "reactive") |
239 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
240 | ! |
moduleServer(id, function(input, output, session) { |
241 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
242 | ||
243 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
244 | ! |
data_extract = list(x = x, y = y), |
245 | ! |
datasets = data, |
246 | ! |
select_validation_rule = list( |
247 | ! |
x = shinyvalidate::sv_required("Please define column for row variable."), |
248 | ! |
y = shinyvalidate::sv_required("Please define column for column variable.") |
249 |
) |
|
250 |
) |
|
251 | ||
252 | ! |
iv_r <- reactive({ |
253 | ! |
iv <- shinyvalidate::InputValidator$new() |
254 | ! |
iv$add_rule("join_fun", function(value) { |
255 | ! |
if (!identical(selector_list()$x()$dataname, selector_list()$y()$dataname)) { |
256 | ! |
if (!shinyvalidate::input_provided(value)) { |
257 | ! |
"Please select a joining function." |
258 |
} |
|
259 |
} |
|
260 |
}) |
|
261 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
262 |
}) |
|
263 | ||
264 | ! |
observeEvent( |
265 | ! |
eventExpr = { |
266 | ! |
req(!is.null(selector_list()$x()) && !is.null(selector_list()$y())) |
267 | ! |
list(selector_list()$x(), selector_list()$y()) |
268 |
}, |
|
269 | ! |
handlerExpr = { |
270 | ! |
if (identical(selector_list()$x()$dataname, selector_list()$y()$dataname)) { |
271 | ! |
shinyjs::hide("join_fun") |
272 |
} else { |
|
273 | ! |
shinyjs::show("join_fun") |
274 |
} |
|
275 |
} |
|
276 |
) |
|
277 | ||
278 | ! |
merge_function <- reactive({ |
279 | ! |
if (is.null(input$join_fun)) { |
280 | ! |
"dplyr::full_join" |
281 |
} else { |
|
282 | ! |
input$join_fun |
283 |
} |
|
284 |
}) |
|
285 | ||
286 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
287 | ! |
datasets = data, |
288 | ! |
selector_list = selector_list, |
289 | ! |
merge_function = merge_function |
290 |
) |
|
291 | ||
292 | ! |
anl_merged_q <- reactive({ |
293 | ! |
req(anl_merged_input()) |
294 | ! |
data() %>% |
295 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
296 |
}) |
|
297 | ||
298 | ! |
merged <- list( |
299 | ! |
anl_input_r = anl_merged_input, |
300 | ! |
anl_q_r = anl_merged_q |
301 |
) |
|
302 | ||
303 | ! |
output_q <- reactive({ |
304 | ! |
teal::validate_inputs(iv_r()) |
305 | ! |
ANL <- merged$anl_q_r()[["ANL"]] |
306 | ||
307 |
# As this is a summary |
|
308 | ! |
x_name <- as.vector(merged$anl_input_r()$columns_source$x) |
309 | ! |
y_name <- as.vector(merged$anl_input_r()$columns_source$y) |
310 | ||
311 | ! |
teal::validate_has_data(ANL, 3) |
312 | ! |
teal::validate_has_data(ANL[, c(x_name, y_name)], 3, complete = TRUE, allow_inf = FALSE) |
313 | ||
314 | ! |
is_allowed_class <- function(x) is.numeric(x) || is.factor(x) || is.character(x) || is.logical(x) |
315 | ! |
validate(need( |
316 | ! |
all(vapply(ANL[x_name], is_allowed_class, logical(1))), |
317 | ! |
"Selected row variable has an unsupported data type." |
318 |
)) |
|
319 | ! |
validate(need( |
320 | ! |
is_allowed_class(ANL[[y_name]]), |
321 | ! |
"Selected column variable has an unsupported data type." |
322 |
)) |
|
323 | ||
324 | ! |
show_percentage <- input$show_percentage |
325 | ! |
show_total <- input$show_total |
326 | ||
327 | ! |
plot_title <- paste( |
328 | ! |
"Cross-Table of", |
329 | ! |
paste0(varname_w_label(x_name, ANL), collapse = ", "), |
330 | ! |
"(rows)", "vs.", |
331 | ! |
varname_w_label(y_name, ANL), |
332 | ! |
"(columns)" |
333 |
) |
|
334 | ||
335 | ! |
labels_vec <- vapply( |
336 | ! |
x_name, |
337 | ! |
varname_w_label, |
338 | ! |
character(1), |
339 | ! |
ANL |
340 |
) |
|
341 | ||
342 | ! |
teal.code::eval_code( |
343 | ! |
merged$anl_q_r(), |
344 | ! |
substitute( |
345 | ! |
expr = { |
346 | ! |
title <- plot_title |
347 |
}, |
|
348 | ! |
env = list(plot_title = plot_title) |
349 |
) |
|
350 |
) %>% |
|
351 | ! |
teal.code::eval_code( |
352 | ! |
substitute( |
353 | ! |
expr = { |
354 | ! |
lyt <- basic_tables %>% |
355 | ! |
split_call %>% # styler: off |
356 | ! |
rtables::add_colcounts() %>% |
357 | ! |
tern::analyze_vars( |
358 | ! |
vars = x_name, |
359 | ! |
var_labels = labels_vec, |
360 | ! |
na.rm = FALSE, |
361 | ! |
denom = "N_col", |
362 | ! |
.stats = c("mean_sd", "median", "range", count_value) |
363 |
) |
|
364 |
}, |
|
365 | ! |
env = list( |
366 | ! |
basic_tables = teal.widgets::parse_basic_table_args( |
367 | ! |
basic_table_args = teal.widgets::resolve_basic_table_args(basic_table_args) |
368 |
), |
|
369 | ! |
split_call = if (show_total) { |
370 | ! |
substitute( |
371 | ! |
expr = rtables::split_cols_by( |
372 | ! |
y_name, |
373 | ! |
split_fun = rtables::add_overall_level(label = "Total", first = FALSE) |
374 |
), |
|
375 | ! |
env = list(y_name = y_name) |
376 |
) |
|
377 |
} else { |
|
378 | ! |
substitute(rtables::split_cols_by(y_name), env = list(y_name = y_name)) |
379 |
}, |
|
380 | ! |
x_name = x_name, |
381 | ! |
labels_vec = labels_vec, |
382 | ! |
count_value = ifelse(show_percentage, "count_fraction", "count") |
383 |
) |
|
384 |
) |
|
385 |
) %>% |
|
386 | ! |
teal.code::eval_code( |
387 | ! |
substitute( |
388 | ! |
expr = { |
389 | ! |
ANL <- tern::df_explicit_na(ANL) |
390 | ! |
tbl <- rtables::build_table(lyt = lyt, df = ANL[order(ANL[[y_name]]), ]) |
391 | ! |
tbl |
392 |
}, |
|
393 | ! |
env = list(y_name = y_name) |
394 |
) |
|
395 |
) |
|
396 |
}) |
|
397 | ||
398 | ! |
output$title <- renderText(output_q()[["title"]]) |
399 | ||
400 | ! |
table_r <- reactive({ |
401 | ! |
req(iv_r()$is_valid()) |
402 | ! |
output_q()[["tbl"]] |
403 |
}) |
|
404 | ||
405 | ! |
teal.widgets::table_with_settings_srv( |
406 | ! |
id = "table", |
407 | ! |
table_r = table_r |
408 |
) |
|
409 | ||
410 | ! |
teal.widgets::verbatim_popup_srv( |
411 | ! |
id = "rcode", |
412 | ! |
verbatim_content = reactive(teal.code::get_code(output_q())), |
413 | ! |
title = "Show R Code for Cross-Table" |
414 |
) |
|
415 | ||
416 |
### REPORTER |
|
417 | ! |
if (with_reporter) { |
418 | ! |
card_fun <- function(comment, label) { |
419 | ! |
card <- teal::report_card_template( |
420 | ! |
title = "Cross Table", |
421 | ! |
label = label, |
422 | ! |
with_filter = with_filter, |
423 | ! |
filter_panel_api = filter_panel_api |
424 |
) |
|
425 | ! |
card$append_text("Table", "header3") |
426 | ! |
card$append_table(table_r()) |
427 | ! |
if (!comment == "") { |
428 | ! |
card$append_text("Comment", "header3") |
429 | ! |
card$append_text(comment) |
430 |
} |
|
431 | ! |
card$append_src(teal.code::get_code(output_q())) |
432 | ! |
card |
433 |
} |
|
434 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
435 |
} |
|
436 |
### |
|
437 |
}) |
|
438 |
} |
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 |
#' @templateVar ggnames `r regression_names` |
|
41 |
#' @template ggplot2_args_multi |
|
42 |
#' |
|
43 |
#' @inherit shared_params return |
|
44 |
#' |
|
45 |
#' @examplesShinylive |
|
46 |
#' library(teal.modules.general) |
|
47 |
#' interactive <- function() TRUE |
|
48 |
#' {{ next_example }} |
|
49 |
#' @examples |
|
50 |
#' # general data example |
|
51 |
#' data <- teal_data() |
|
52 |
#' data <- within(data, { |
|
53 |
#' require(nestcolor) |
|
54 |
#' CO2 <- CO2 |
|
55 |
#' }) |
|
56 |
#' |
|
57 |
#' app <- init( |
|
58 |
#' data = data, |
|
59 |
#' modules = modules( |
|
60 |
#' tm_a_regression( |
|
61 |
#' label = "Regression", |
|
62 |
#' response = data_extract_spec( |
|
63 |
#' dataname = "CO2", |
|
64 |
#' select = select_spec( |
|
65 |
#' label = "Select variable:", |
|
66 |
#' choices = "uptake", |
|
67 |
#' selected = "uptake", |
|
68 |
#' multiple = FALSE, |
|
69 |
#' fixed = TRUE |
|
70 |
#' ) |
|
71 |
#' ), |
|
72 |
#' regressor = data_extract_spec( |
|
73 |
#' dataname = "CO2", |
|
74 |
#' select = select_spec( |
|
75 |
#' label = "Select variables:", |
|
76 |
#' choices = variable_choices(data[["CO2"]], c("conc", "Treatment")), |
|
77 |
#' selected = "conc", |
|
78 |
#' multiple = TRUE, |
|
79 |
#' fixed = FALSE |
|
80 |
#' ) |
|
81 |
#' ) |
|
82 |
#' ) |
|
83 |
#' ) |
|
84 |
#' ) |
|
85 |
#' if (interactive()) { |
|
86 |
#' shinyApp(app$ui, app$server) |
|
87 |
#' } |
|
88 |
#' |
|
89 |
#' @examplesShinylive |
|
90 |
#' library(teal.modules.general) |
|
91 |
#' interactive <- function() TRUE |
|
92 |
#' {{ next_example }} |
|
93 |
#' @examples |
|
94 |
#' # CDISC data example |
|
95 |
#' data <- teal_data() |
|
96 |
#' data <- within(data, { |
|
97 |
#' require(nestcolor) |
|
98 |
#' ADSL <- rADSL |
|
99 |
#' }) |
|
100 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
101 |
#' |
|
102 |
#' app <- init( |
|
103 |
#' data = data, |
|
104 |
#' modules = modules( |
|
105 |
#' tm_a_regression( |
|
106 |
#' label = "Regression", |
|
107 |
#' response = data_extract_spec( |
|
108 |
#' dataname = "ADSL", |
|
109 |
#' select = select_spec( |
|
110 |
#' label = "Select variable:", |
|
111 |
#' choices = "BMRKR1", |
|
112 |
#' selected = "BMRKR1", |
|
113 |
#' multiple = FALSE, |
|
114 |
#' fixed = TRUE |
|
115 |
#' ) |
|
116 |
#' ), |
|
117 |
#' regressor = data_extract_spec( |
|
118 |
#' dataname = "ADSL", |
|
119 |
#' select = select_spec( |
|
120 |
#' label = "Select variables:", |
|
121 |
#' choices = variable_choices(data[["ADSL"]], c("AGE", "SEX", "RACE")), |
|
122 |
#' selected = "AGE", |
|
123 |
#' multiple = TRUE, |
|
124 |
#' fixed = FALSE |
|
125 |
#' ) |
|
126 |
#' ) |
|
127 |
#' ) |
|
128 |
#' ) |
|
129 |
#' ) |
|
130 |
#' if (interactive()) { |
|
131 |
#' shinyApp(app$ui, app$server) |
|
132 |
#' } |
|
133 |
#' |
|
134 |
#' @export |
|
135 |
#' |
|
136 |
tm_a_regression <- function(label = "Regression Analysis", |
|
137 |
regressor, |
|
138 |
response, |
|
139 |
plot_height = c(600, 200, 2000), |
|
140 |
plot_width = NULL, |
|
141 |
alpha = c(1, 0, 1), |
|
142 |
size = c(2, 1, 8), |
|
143 |
ggtheme = c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void"), |
|
144 |
ggplot2_args = teal.widgets::ggplot2_args(), |
|
145 |
pre_output = NULL, |
|
146 |
post_output = NULL, |
|
147 |
default_plot_type = 1, |
|
148 |
default_outlier_label = "USUBJID", |
|
149 |
label_segment_threshold = c(0.5, 0, 10)) { |
|
150 | ! |
message("Initializing tm_a_regression") |
151 | ||
152 |
# Normalize the parameters |
|
153 | ! |
if (inherits(regressor, "data_extract_spec")) regressor <- list(regressor) |
154 | ! |
if (inherits(response, "data_extract_spec")) response <- list(response) |
155 | ! |
if (inherits(ggplot2_args, "ggplot2_args")) ggplot2_args <- list(default = ggplot2_args) |
156 | ||
157 |
# Start of assertions |
|
158 | ! |
checkmate::assert_string(label) |
159 | ! |
checkmate::assert_list(regressor, types = "data_extract_spec") |
160 | ||
161 | ! |
checkmate::assert_list(response, types = "data_extract_spec") |
162 | ! |
assert_single_selection(response) |
163 | ||
164 | ! |
checkmate::assert_numeric(plot_height, len = 3, any.missing = FALSE, finite = TRUE) |
165 | ! |
checkmate::assert_numeric(plot_height[1], lower = plot_height[2], upper = plot_height[3], .var.name = "plot_height") |
166 | ||
167 | ! |
checkmate::assert_numeric(plot_width, len = 3, any.missing = FALSE, null.ok = TRUE, finite = TRUE) |
168 | ! |
checkmate::assert_numeric( |
169 | ! |
plot_width[1], |
170 | ! |
lower = plot_width[2], |
171 | ! |
upper = plot_width[3], |
172 | ! |
null.ok = TRUE, |
173 | ! |
.var.name = "plot_width" |
174 |
) |
|
175 | ||
176 | ! |
if (length(alpha) == 1) { |
177 | ! |
checkmate::assert_numeric(alpha, any.missing = FALSE, finite = TRUE) |
178 |
} else { |
|
179 | ! |
checkmate::assert_numeric(alpha, len = 3, any.missing = FALSE, finite = TRUE) |
180 | ! |
checkmate::assert_numeric(alpha[1], lower = alpha[2], upper = alpha[3], .var.name = "alpha") |
181 |
} |
|
182 | ||
183 | ! |
if (length(size) == 1) { |
184 | ! |
checkmate::assert_numeric(size, any.missing = FALSE, finite = TRUE) |
185 |
} else { |
|
186 | ! |
checkmate::assert_numeric(size, len = 3, any.missing = FALSE, finite = TRUE) |
187 | ! |
checkmate::assert_numeric(size[1], lower = size[2], upper = size[3], .var.name = "size") |
188 |
} |
|
189 | ||
190 | ! |
ggtheme <- match.arg(ggtheme) |
191 | ||
192 | ! |
plot_choices <- c( |
193 | ! |
"Response vs Regressor", "Residuals vs Fitted", "Normal Q-Q", "Scale-Location", |
194 | ! |
"Cook's distance", "Residuals vs Leverage", "Cook's dist vs Leverage" |
195 |
) |
|
196 | ! |
checkmate::assert_list(ggplot2_args, types = "ggplot2_args") |
197 | ! |
checkmate::assert_subset(names(ggplot2_args), c("default", plot_choices)) |
198 | ||
199 | ! |
checkmate::assert_multi_class(pre_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
200 | ! |
checkmate::assert_multi_class(post_output, c("shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE) |
201 | ! |
checkmate::assert_choice(default_plot_type, seq.int(1L, length(plot_choices))) |
202 | ! |
checkmate::assert_string(default_outlier_label) |
203 | ||
204 | ! |
if (length(label_segment_threshold) == 1) { |
205 | ! |
checkmate::assert_numeric(label_segment_threshold, any.missing = FALSE, finite = TRUE) |
206 |
} else { |
|
207 | ! |
checkmate::assert_numeric(label_segment_threshold, len = 3, any.missing = FALSE, finite = TRUE) |
208 | ! |
checkmate::assert_numeric( |
209 | ! |
label_segment_threshold[1], |
210 | ! |
lower = label_segment_threshold[2], |
211 | ! |
upper = label_segment_threshold[3], |
212 | ! |
.var.name = "label_segment_threshold" |
213 |
) |
|
214 |
} |
|
215 |
# End of assertions |
|
216 | ||
217 |
# Make UI args |
|
218 | ! |
args <- as.list(environment()) |
219 | ! |
args[["plot_choices"]] <- plot_choices |
220 | ! |
data_extract_list <- list( |
221 | ! |
regressor = regressor, |
222 | ! |
response = response |
223 |
) |
|
224 | ||
225 | ! |
ans <- module( |
226 | ! |
label = label, |
227 | ! |
server = srv_a_regression, |
228 | ! |
ui = ui_a_regression, |
229 | ! |
ui_args = args, |
230 | ! |
server_args = c( |
231 | ! |
data_extract_list, |
232 | ! |
list( |
233 | ! |
plot_height = plot_height, |
234 | ! |
plot_width = plot_width, |
235 | ! |
default_outlier_label = default_outlier_label, |
236 | ! |
ggplot2_args = ggplot2_args |
237 |
) |
|
238 |
), |
|
239 | ! |
datanames = teal.transform::get_extract_datanames(data_extract_list) |
240 |
) |
|
241 | ! |
attr(ans, "teal_bookmarkable") <- FALSE |
242 | ! |
ans |
243 |
} |
|
244 | ||
245 |
# UI function for the regression module |
|
246 |
ui_a_regression <- function(id, ...) { |
|
247 | ! |
ns <- NS(id) |
248 | ! |
args <- list(...) |
249 | ! |
is_single_dataset_value <- teal.transform::is_single_dataset(args$regressor, args$response) |
250 | ||
251 | ! |
teal.widgets::standard_layout( |
252 | ! |
output = teal.widgets::white_small_well(tags$div( |
253 | ! |
teal.widgets::plot_with_settings_ui(id = ns("myplot")), |
254 | ! |
tags$div(verbatimTextOutput(ns("text"))) |
255 |
)), |
|
256 | ! |
encoding = tags$div( |
257 |
### Reporter |
|
258 | ! |
teal.reporter::simple_reporter_ui(ns("simple_reporter")), |
259 |
### |
|
260 | ! |
tags$label("Encodings", class = "text-primary"), |
261 | ! |
teal.transform::datanames_input(args[c("response", "regressor")]), |
262 | ! |
teal.transform::data_extract_ui( |
263 | ! |
id = ns("response"), |
264 | ! |
label = "Response variable", |
265 | ! |
data_extract_spec = args$response, |
266 | ! |
is_single_dataset = is_single_dataset_value |
267 |
), |
|
268 | ! |
teal.transform::data_extract_ui( |
269 | ! |
id = ns("regressor"), |
270 | ! |
label = "Regressor variables", |
271 | ! |
data_extract_spec = args$regressor, |
272 | ! |
is_single_dataset = is_single_dataset_value |
273 |
), |
|
274 | ! |
radioButtons( |
275 | ! |
ns("plot_type"), |
276 | ! |
label = "Plot type:", |
277 | ! |
choices = args$plot_choices, |
278 | ! |
selected = args$plot_choices[args$default_plot_type] |
279 |
), |
|
280 | ! |
checkboxInput(ns("show_outlier"), label = "Display outlier labels", value = TRUE), |
281 | ! |
conditionalPanel( |
282 | ! |
condition = "input['show_outlier']", |
283 | ! |
ns = ns, |
284 | ! |
teal.widgets::optionalSliderInput( |
285 | ! |
ns("outlier"), |
286 | ! |
tags$div( |
287 | ! |
class = "teal-tooltip", |
288 | ! |
tagList( |
289 | ! |
"Outlier definition:", |
290 | ! |
icon("circle-info"), |
291 | ! |
tags$span( |
292 | ! |
class = "tooltiptext", |
293 | ! |
paste( |
294 | ! |
"Use the slider to choose the cut-off value to define outliers.", |
295 | ! |
"Points with a Cook's distance greater than", |
296 | ! |
"the value on the slider times the mean of the Cook's distance of the dataset will have labels." |
297 |
) |
|
298 |
) |
|
299 |
) |
|
300 |
), |
|
301 | ! |
min = 1, max = 10, value = 9, ticks = FALSE, step = .1 |
302 |
), |
|
303 | ! |
teal.widgets::optionalSelectInput( |
304 | ! |
ns("label_var"), |
305 | ! |
multiple = FALSE, |
306 | ! |
label = "Outlier label" |
307 |
) |
|
308 |
), |
|
309 | ! |
teal.widgets::panel_group( |
310 | ! |
teal.widgets::panel_item( |
311 | ! |
title = "Plot settings", |
312 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("alpha"), "Opacity:", args$alpha, ticks = FALSE), |
313 | ! |
teal.widgets::optionalSliderInputValMinMax(ns("size"), "Points size:", args$size, ticks = FALSE), |
314 | ! |
teal.widgets::optionalSliderInputValMinMax( |
315 | ! |
inputId = ns("label_min_segment"), |
316 | ! |
label = tags$div( |
317 | ! |
class = "teal-tooltip", |
318 | ! |
tagList( |
319 | ! |
"Label min. segment:", |
320 | ! |
icon("circle-info"), |
321 | ! |
tags$span( |
322 | ! |
class = "tooltiptext", |
323 | ! |
paste( |
324 | ! |
"Use the slider to choose the cut-off value to define minimum distance between label and point", |
325 | ! |
"that generates a line segment.", |
326 | ! |
"It's only valid when 'Display outlier labels' is checked." |
327 |
) |
|
328 |
) |
|
329 |
) |
|
330 |
), |
|
331 | ! |
value_min_max = args$label_segment_threshold, |
332 |
# Extra parameters to sliderInput |
|
333 | ! |
ticks = FALSE, |
334 | ! |
step = .1, |
335 | ! |
round = FALSE |
336 |
), |
|
337 | ! |
selectInput( |
338 | ! |
inputId = ns("ggtheme"), |
339 | ! |
label = "Theme (by ggplot):", |
340 | ! |
choices = ggplot_themes, |
341 | ! |
selected = args$ggtheme, |
342 | ! |
multiple = FALSE |
343 |
) |
|
344 |
) |
|
345 |
) |
|
346 |
), |
|
347 | ! |
forms = tagList( |
348 | ! |
teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
349 |
), |
|
350 | ! |
pre_output = args$pre_output, |
351 | ! |
post_output = args$post_output |
352 |
) |
|
353 |
} |
|
354 | ||
355 |
# Server function for the regression module |
|
356 |
srv_a_regression <- function(id, |
|
357 |
data, |
|
358 |
reporter, |
|
359 |
filter_panel_api, |
|
360 |
response, |
|
361 |
regressor, |
|
362 |
plot_height, |
|
363 |
plot_width, |
|
364 |
ggplot2_args, |
|
365 |
default_outlier_label) { |
|
366 | ! |
with_reporter <- !missing(reporter) && inherits(reporter, "Reporter") |
367 | ! |
with_filter <- !missing(filter_panel_api) && inherits(filter_panel_api, "FilterPanelAPI") |
368 | ! |
checkmate::assert_class(data, "reactive") |
369 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
370 | ! |
moduleServer(id, function(input, output, session) { |
371 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
372 | ||
373 | ! |
ns <- session$ns |
374 | ||
375 | ! |
rule_rvr1 <- function(value) { |
376 | ! |
if (isTRUE(input$plot_type == "Response vs Regressor")) { |
377 | ! |
if (length(value) > 1L) { |
378 | ! |
"This plot can only have one regressor." |
379 |
} |
|
380 |
} |
|
381 |
} |
|
382 | ! |
rule_rvr2 <- function(other) { |
383 | ! |
function(value) { |
384 | ! |
if (isTRUE(input$plot_type == "Response vs Regressor")) { |
385 | ! |
otherval <- selector_list()[[other]]()$select |
386 | ! |
if (isTRUE(value == otherval)) { |
387 | ! |
"Response and Regressor must be different." |
388 |
} |
|
389 |
} |
|
390 |
} |
|
391 |
} |
|
392 | ||
393 | ! |
selector_list <- teal.transform::data_extract_multiple_srv( |
394 | ! |
data_extract = list(response = response, regressor = regressor), |
395 | ! |
datasets = data, |
396 | ! |
select_validation_rule = list( |
397 | ! |
regressor = shinyvalidate::compose_rules( |
398 | ! |
shinyvalidate::sv_required("At least one regressor should be selected."), |
399 | ! |
rule_rvr1, |
400 | ! |
rule_rvr2("response") |
401 |
), |
|
402 | ! |
response = shinyvalidate::compose_rules( |
403 | ! |
shinyvalidate::sv_required("At least one response should be selected."), |
404 | ! |
rule_rvr2("regressor") |
405 |
) |
|
406 |
) |
|
407 |
) |
|
408 | ||
409 | ! |
iv_r <- reactive({ |
410 | ! |
iv <- shinyvalidate::InputValidator$new() |
411 | ! |
teal.transform::compose_and_enable_validators(iv, selector_list) |
412 |
}) |
|
413 | ||
414 | ! |
iv_out <- shinyvalidate::InputValidator$new() |
415 | ! |
iv_out$condition(~ isTRUE(input$show_outlier)) |
416 | ! |
iv_out$add_rule("label_var", shinyvalidate::sv_required("Please provide an `Outlier label` variable")) |
417 | ! |
iv_out$enable() |
418 | ||
419 | ! |
anl_merged_input <- teal.transform::merge_expression_srv( |
420 | ! |
selector_list = selector_list, |
421 | ! |
datasets = data |
422 |
) |
|
423 | ||
424 | ! |
regression_var <- reactive({ |
425 | ! |
teal::validate_inputs(iv_r()) |
426 | ||
427 | ! |
list( |
428 | ! |
response = as.vector(anl_merged_input()$columns_source$response), |
429 | ! |
regressor = as.vector(anl_merged_input()$columns_source$regressor) |
430 |
) |
|
431 |
}) |
|
432 | ||
433 | ! |
anl_merged_q <- reactive({ |
434 | ! |
req(anl_merged_input()) |
435 | ! |
data() %>% |
436 | ! |
teal.code::eval_code(as.expression(anl_merged_input()$expr)) |
437 |
}) |
|
438 | ||
439 |
# sets qenv object and populates it with data merge call and fit expression |
|
440 | ! |
fit_r <- reactive({ |
441 | ! |
ANL <- anl_merged_q()[["ANL"]] |
442 | ! |
teal::validate_has_data(ANL, 10) |
443 | ||
444 | ! |
validate(need(is.numeric(ANL[regression_var()$response][[1]]), "Response variable should be numeric.")) |
445 | ||
446 | ! |
teal::validate_has_data( |
447 | ! |
ANL[, c(regression_var()$response, regression_var()$regressor)], 10, |
448 | ! |
complete = TRUE, allow_inf = FALSE |
449 |
) |
|
450 | ||
451 | ! |
form <- stats::as.formula( |
452 | ! |
paste( |
453 | ! |
regression_var()$response, |
454 | ! |
paste( |
455 | ! |
regression_var()$regressor, |
456 | ! |
collapse = " + " |
457 |
), |
|
458 | ! |
sep = " ~ " |
459 |
) |
|
460 |
) |
|
461 | ||
462 | ! |
if (input$show_outlier) { |
463 | ! |
opts <- teal.transform::variable_choices(ANL) |
464 | ! |
selected <- if (!is.null(isolate(input$label_var)) && isolate(input$label_var) %in% as.character(opts)) { |
465 | ! |
isolate(input$label_var) |
466 |
} else { |
|
467 | ! |
if (length(opts[as.character(opts) == default_outlier_label]) == 0) { |
468 | ! |
opts[[1]] |
469 |
} else { |
|
470 | ! |
opts[as.character(opts) == default_outlier_label] |
471 |
} |
|
472 |
} |
|
473 | ! |
teal.widgets::updateOptionalSelectInput( |
474 | ! |
session = session, |
475 | ! |
inputId = "label_var", |
476 | ! |
choices = opts, |
477 | ! |
selected = restoreInput(ns("label_var"), selected) |
478 |
) |
|
479 | ||
480 | ! |
data <- fortify(stats::lm(form, data = ANL)) |
481 | ! |
cooksd <- data$.cooksd[!is.nan(data$.cooksd)] |
482 | ! |
max_outlier <- max(ceiling(max(cooksd) / mean(cooksd)), 2) |
483 | ! |
cur_outlier <- isolate(input$outlier) |
484 | ! |
updateSliderInput( |
485 | ! |
session = session, |
486 | ! |
inputId = "outlier", |
487 | ! |
min = 1, |
488 | ! |
max = max_outlier, |
489 | ! |
value = restoreInput(ns("outlier"), if (cur_outlier < max_outlier) cur_outlier else max_outlier * .9) |
490 |
) |
|
491 |
} |
|
492 | ||
493 | ! |
anl_merged_q() %>% |
494 | ! |
teal.code::eval_code(substitute(fit <- stats::lm(form, data = ANL), env = list(form = form))) %>% |
495 | ! |
teal.code::eval_code(quote({ |
496 | ! |
for (regressor in names(fit$contrasts)) { |
497 | ! |
alts <- paste0(levels(ANL[[regressor]]), collapse = "|") |
498 | ! |
names(fit$coefficients) <- gsub( |
499 | ! |
paste0("^(", regressor, ")(", alts, ")$"), paste0("\\1", ": ", "\\2"), names(fit$coefficients) |
500 |
) |
|
501 |
} |
|
502 |
})) %>% |
|
503 | ! |
teal.code::eval_code(quote(summary(fit))) |
504 |
}) |
|
505 | ||
506 | ! |
label_col <- reactive({ |
507 | ! |
teal::validate_inputs(iv_out) |
508 | ||
509 | ! |
substitute( |
510 | ! |
expr = dplyr::if_else( |
511 | ! |
data$.cooksd > outliers * mean(data$.cooksd, na.rm = TRUE), |
512 | ! |
as.character(stats::na.omit(ANL)[[label_var]]), |
513 |
"" |
|
514 |
) %>% |
|
515 | ! |
dplyr::if_else(is.na(.), "cooksd == NaN", .), |
516 | ! |
env = list(outliers = input$outlier, label_var = input$label_var) |
517 |
) |
|
518 |
}) |
|
519 | ||
520 | ! |
label_min_segment <- reactive({ |
521 | ! |
input$label_min_segment |
522 |
}) |
|
523 | ||
524 | ! |
outlier_label <- reactive({ |
525 | ! |
substitute( |
526 | ! |
expr = ggrepel::geom_text_repel( |
527 | ! |
label = label_col, |
528 | ! |
color = "red", |
529 | ! |
hjust = 0, |
530 | ! |
vjust = 1, |
531 | ! |
max.overlaps = Inf, |
532 | ! |
min.segment.length = label_min_segment, |
533 | ! |
segment.alpha = 0.5, |
534 | ! |
seed = 123 |
535 |
), |
|
536 | ! |
env = list(label_col = label_col(), label_min_segment = label_min_segment()) |
537 |
) |
|
538 |
}) |
|
539 | ||
540 | ! |
output_q <- reactive({ |
541 | ! |
alpha <- input$alpha |
542 | ! |
size <- input$size |
543 | ! |
ggtheme <- input$ggtheme |
544 | ! |
input_type <- input$plot_type |
545 | ! |
show_outlier <- input$show_outlier |
546 | ||
547 | ! |
teal::validate_inputs(iv_r()) |
548 | ||
549 | ! |
plot_type_0 <- function() { |
550 | ! |
fit <- fit_r()[["fit"]] |
551 | ! |
ANL <- anl_merged_q()[["ANL"]] |
552 | ||
553 | ! |
stopifnot(ncol(fit$model) == 2) |
554 | ||
555 | ! |
if (!is.factor(ANL[[regression_var()$regressor]])) { |
556 | ! |
shinyjs::show("size") |
557 | ! |
shinyjs::show("alpha") |
558 | ! |
plot <- substitute( |
559 | ! |
env = list( |
560 | ! |
regressor = regression_var()$regressor, |
561 | ! |
response = regression_var()$response, |
562 | ! |
size = size, |
563 | ! |
alpha = alpha |
564 |
), |
|
565 | ! |
expr = ggplot( |
566 | ! |
fit$model[, 2:1], |
567 | ! |
aes_string(regressor, response) |
568 |
) + |
|
569 | ! |
geom_point(size = size, alpha = alpha) + |
570 | ! |
stat_smooth( |
571 | ! |
method = "lm", |
572 | ! |
formula = y ~ x, |
573 | ! |
se = FALSE |
574 |
) |
|
575 |
) |
|
576 | ! |
if (show_outlier) { |
577 | ! |
plot <- substitute( |
578 | ! |
expr = plot + outlier_label, |
579 | ! |
env = list(plot = plot, outlier_label = outlier_label()) |
580 |
) |
|
581 |
} |
|
582 |
} else { |
|
583 | ! |
shinyjs::hide("size") |
584 | ! |
shinyjs::hide("alpha") |
585 | ! |
plot <- substitute( |
586 | ! |
expr = ggplot(fit$model[, 2:1], aes_string(regressor, response)) + |
587 | ! |
geom_boxplot(), |
588 | ! |
env = list(regressor = regression_var()$regressor, response = regression_var()$response) |
589 |
) |
|
590 | ! |
if (show_outlier) { |
591 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
592 |
} |
|
593 |
} |
|
594 | ||
595 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
596 | ! |
teal.widgets::resolve_ggplot2_args( |
597 | ! |
user_plot = ggplot2_args[["Response vs Regressor"]], |
598 | ! |
user_default = ggplot2_args$default, |
599 | ! |
module_plot = teal.widgets::ggplot2_args( |
600 | ! |
labs = list( |
601 | ! |
title = "Response vs Regressor", |
602 | ! |
x = varname_w_label(regression_var()$regressor, ANL), |
603 | ! |
y = varname_w_label(regression_var()$response, ANL) |
604 |
), |
|
605 | ! |
theme = list() |
606 |
) |
|
607 |
), |
|
608 | ! |
ggtheme = ggtheme |
609 |
) |
|
610 | ||
611 | ! |
teal.code::eval_code( |
612 | ! |
fit_r(), |
613 | ! |
substitute( |
614 | ! |
expr = { |
615 | ! |
class(fit$residuals) <- NULL |
616 | ! |
data <- fortify(fit) |
617 | ! |
g <- plot |
618 | ! |
print(g) |
619 |
}, |
|
620 | ! |
env = list( |
621 | ! |
plot = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
622 |
) |
|
623 |
) |
|
624 |
) |
|
625 |
} |
|
626 | ||
627 | ! |
plot_base <- function() { |
628 | ! |
base_fit <- fit_r() |
629 | ! |
teal.code::eval_code( |
630 | ! |
base_fit, |
631 | ! |
quote({ |
632 | ! |
class(fit$residuals) <- NULL |
633 | ||
634 | ! |
data <- ggplot2::fortify(fit) |
635 | ||
636 | ! |
smooth <- function(x, y) { |
637 | ! |
as.data.frame(stats::lowess(x, y, f = 2 / 3, iter = 3)) |
638 |
} |
|
639 | ||
640 | ! |
smoothy_aes <- ggplot2::aes_string(x = "x", y = "y") |
641 | ||
642 | ! |
reg_form <- deparse(fit$call[[2]]) |
643 |
}) |
|
644 |
) |
|
645 |
} |
|
646 | ||
647 | ! |
plot_type_1 <- function(plot_base) { |
648 | ! |
shinyjs::show("size") |
649 | ! |
shinyjs::show("alpha") |
650 | ! |
plot <- substitute( |
651 | ! |
expr = ggplot(data = data, aes(.fitted, .resid)) + |
652 | ! |
geom_point(size = size, alpha = alpha) + |
653 | ! |
geom_hline(yintercept = 0, linetype = "dashed", size = 1) + |
654 | ! |
geom_line(data = smoothy, mapping = smoothy_aes), |
655 | ! |
env = list(size = size, alpha = alpha) |
656 |
) |
|
657 | ! |
if (show_outlier) { |
658 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
659 |
} |
|
660 | ||
661 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
662 | ! |
teal.widgets::resolve_ggplot2_args( |
663 | ! |
user_plot = ggplot2_args[["Residuals vs Fitted"]], |
664 | ! |
user_default = ggplot2_args$default, |
665 | ! |
module_plot = teal.widgets::ggplot2_args( |
666 | ! |
labs = list( |
667 | ! |
x = quote(paste0("Fitted values\nlm(", reg_form, ")")), |
668 | ! |
y = "Residuals", |
669 | ! |
title = "Residuals vs Fitted" |
670 |
) |
|
671 |
) |
|
672 |
), |
|
673 | ! |
ggtheme = ggtheme |
674 |
) |
|
675 | ||
676 | ! |
teal.code::eval_code( |
677 | ! |
plot_base, |
678 | ! |
substitute( |
679 | ! |
expr = { |
680 | ! |
smoothy <- smooth(data$.fitted, data$.resid) |
681 | ! |
g <- plot |
682 | ! |
print(g) |
683 |
}, |
|
684 | ! |
env = list( |
685 | ! |
plot = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
686 |
) |
|
687 |
) |
|
688 |
) |
|
689 |
} |
|
690 | ||
691 | ! |
plot_type_2 <- function(plot_base) { |
692 | ! |
shinyjs::show("size") |
693 | ! |
shinyjs::show("alpha") |
694 | ! |
plot <- substitute( |
695 | ! |
expr = ggplot(data = data, aes(sample = .stdresid)) + |
696 | ! |
stat_qq(size = size, alpha = alpha) + |
697 | ! |
geom_abline(linetype = "dashed"), |
698 | ! |
env = list(size = size, alpha = alpha) |
699 |
) |
|
700 | ! |
if (show_outlier) { |
701 | ! |
plot <- substitute( |
702 | ! |
expr = plot + |
703 | ! |
stat_qq( |
704 | ! |
geom = ggrepel::GeomTextRepel, |
705 | ! |
label = label_col %>% |
706 | ! |
data.frame(label = .) %>% |
707 | ! |
dplyr::filter(label != "cooksd == NaN") %>% |
708 | ! |
unlist(), |
709 | ! |
color = "red", |
710 | ! |
hjust = 0, |
711 | ! |
vjust = 0, |
712 | ! |
max.overlaps = Inf, |
713 | ! |
min.segment.length = label_min_segment, |
714 | ! |
segment.alpha = .5, |
715 | ! |
seed = 123 |
716 |
), |
|
717 | ! |
env = list(plot = plot, label_col = label_col(), label_min_segment = label_min_segment()) |
718 |
) |
|
719 |
} |
|
720 | ||
721 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
722 | ! |
teal.widgets::resolve_ggplot2_args( |
723 | ! |
user_plot = ggplot2_args[["Normal Q-Q"]], |
724 | ! |
user_default = ggplot2_args$default, |
725 | ! |
module_plot = teal.widgets::ggplot2_args( |
726 | ! |
labs = list( |
727 | ! |
x = quote(paste0("Theoretical Quantiles\nlm(", reg_form, ")")), |
728 | ! |
y = "Standardized residuals", |
729 | ! |
title = "Normal Q-Q" |
730 |
) |
|
731 |
) |
|
732 |
), |
|
733 | ! |
ggtheme = ggtheme |
734 |
) |
|
735 | ||
736 | ! |
teal.code::eval_code( |
737 | ! |
plot_base, |
738 | ! |
substitute( |
739 | ! |
expr = { |
740 | ! |
g <- plot |
741 | ! |
print(g) |
742 |
}, |
|
743 | ! |
env = list( |
744 | ! |
plot = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
745 |
) |
|
746 |
) |
|
747 |
) |
|
748 |
} |
|
749 | ||
750 | ! |
plot_type_3 <- function(plot_base) { |
751 | ! |
shinyjs::show("size") |
752 | ! |
shinyjs::show("alpha") |
753 | ! |
plot <- substitute( |
754 | ! |
expr = ggplot(data = data, aes(.fitted, sqrt(abs(.stdresid)))) + |
755 | ! |
geom_point(size = size, alpha = alpha) + |
756 | ! |
geom_line(data = smoothy, mapping = smoothy_aes), |
757 | ! |
env = list(size = size, alpha = alpha) |
758 |
) |
|
759 | ! |
if (show_outlier) { |
760 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
761 |
} |
|
762 | ||
763 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
764 | ! |
teal.widgets::resolve_ggplot2_args( |
765 | ! |
user_plot = ggplot2_args[["Scale-Location"]], |
766 | ! |
user_default = ggplot2_args$default, |
767 | ! |
module_plot = teal.widgets::ggplot2_args( |
768 | ! |
labs = list( |
769 | ! |
x = quote(paste0("Fitted values\nlm(", reg_form, ")")), |
770 | ! |
y = quote(expression(sqrt(abs(`Standardized residuals`)))), |
771 | ! |
title = "Scale-Location" |
772 |
) |
|
773 |
) |
|
774 |
), |
|
775 | ! |
ggtheme = ggtheme |
776 |
) |
|
777 | ||
778 | ! |
teal.code::eval_code( |
779 | ! |
plot_base, |
780 | ! |
substitute( |
781 | ! |
expr = { |
782 | ! |
smoothy <- smooth(data$.fitted, sqrt(abs(data$.stdresid))) |
783 | ! |
g <- plot |
784 | ! |
print(g) |
785 |
}, |
|
786 | ! |
env = list( |
787 | ! |
plot = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
788 |
) |
|
789 |
) |
|
790 |
) |
|
791 |
} |
|
792 | ||
793 | ! |
plot_type_4 <- function(plot_base) { |
794 | ! |
shinyjs::hide("size") |
795 | ! |
shinyjs::show("alpha") |
796 | ! |
plot <- substitute( |
797 | ! |
expr = ggplot(data = data, aes(seq_along(.cooksd), .cooksd)) + |
798 | ! |
geom_col(alpha = alpha), |
799 | ! |
env = list(alpha = alpha) |
800 |
) |
|
801 | ! |
if (show_outlier) { |
802 | ! |
plot <- substitute( |
803 | ! |
expr = plot + |
804 | ! |
geom_hline( |
805 | ! |
yintercept = c( |
806 | ! |
outlier * mean(data$.cooksd, na.rm = TRUE), |
807 | ! |
mean(data$.cooksd, na.rm = TRUE) |
808 |
), |
|
809 | ! |
color = "red", |
810 | ! |
linetype = "dashed" |
811 |
) + |
|
812 | ! |
geom_text( |
813 | ! |
aes( |
814 | ! |
x = 0, |
815 | ! |
y = mean(data$.cooksd, na.rm = TRUE), |
816 | ! |
label = paste("mu", "=", round(mean(data$.cooksd, na.rm = TRUE), 4)), |
817 | ! |
vjust = -1, |
818 | ! |
hjust = 0, |
819 | ! |
color = "red", |
820 | ! |
angle = 90 |
821 |
), |
|
822 | ! |
parse = TRUE, |
823 | ! |
show.legend = FALSE |
824 |
) + |
|
825 | ! |
outlier_label, |
826 | ! |
env = list(plot = plot, outlier = input$outlier, outlier_label = outlier_label()) |
827 |
) |
|
828 |
} |
|
829 | ||
830 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
831 | ! |
teal.widgets::resolve_ggplot2_args( |
832 | ! |
user_plot = ggplot2_args[["Cook's distance"]], |
833 | ! |
user_default = ggplot2_args$default, |
834 | ! |
module_plot = teal.widgets::ggplot2_args( |
835 | ! |
labs = list( |
836 | ! |
x = quote(paste0("Obs. number\nlm(", reg_form, ")")), |
837 | ! |
y = "Cook's distance", |
838 | ! |
title = "Cook's distance" |
839 |
) |
|
840 |
) |
|
841 |
), |
|
842 | ! |
ggtheme = ggtheme |
843 |
) |
|
844 | ||
845 | ! |
teal.code::eval_code( |
846 | ! |
plot_base, |
847 | ! |
substitute( |
848 | ! |
expr = { |
849 | ! |
g <- plot |
850 | ! |
print(g) |
851 |
}, |
|
852 | ! |
env = list( |
853 | ! |
plot = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
854 |
) |
|
855 |
) |
|
856 |
) |
|
857 |
} |
|
858 | ||
859 | ||
860 | ! |
plot_type_5 <- function(plot_base) { |
861 | ! |
shinyjs::show("size") |
862 | ! |
shinyjs::show("alpha") |
863 | ! |
plot <- substitute( |
864 | ! |
expr = ggplot(data = data, aes(.hat, .stdresid)) + |
865 | ! |
geom_vline( |
866 | ! |
size = 1, |
867 | ! |
colour = "black", |
868 | ! |
linetype = "dashed", |
869 | ! |
xintercept = 0 |
870 |
) + |
|
871 | ! |
geom_hline( |
872 | ! |
size = 1, |
873 | ! |
colour = "black", |
874 | ! |
linetype = "dashed", |
875 | ! |
yintercept = 0 |
876 |
) + |
|
877 | ! |
geom_point(size = size, alpha = alpha) + |
878 | ! |
geom_line(data = smoothy, mapping = smoothy_aes), |
879 | ! |
env = list(size = size, alpha = alpha) |
880 |
) |
|
881 | ! |
if (show_outlier) { |
882 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
883 |
} |
|
884 | ||
885 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
886 | ! |
teal.widgets::resolve_ggplot2_args( |
887 | ! |
user_plot = ggplot2_args[["Residuals vs Leverage"]], |
888 | ! |
user_default = ggplot2_args$default, |
889 | ! |
module_plot = teal.widgets::ggplot2_args( |
890 | ! |
labs = list( |
891 | ! |
x = quote(paste0("Standardized residuals\nlm(", reg_form, ")")), |
892 | ! |
y = "Leverage", |
893 | ! |
title = "Residuals vs Leverage" |
894 |
) |
|
895 |
) |
|
896 |
), |
|
897 | ! |
ggtheme = ggtheme |
898 |
) |
|
899 | ||
900 | ! |
teal.code::eval_code( |
901 | ! |
plot_base, |
902 | ! |
substitute( |
903 | ! |
expr = { |
904 | ! |
smoothy <- smooth(data$.hat, data$.stdresid) |
905 | ! |
g <- plot |
906 | ! |
print(g) |
907 |
}, |
|
908 | ! |
env = list( |
909 | ! |
plot = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
910 |
) |
|
911 |
) |
|
912 |
) |
|
913 |
} |
|
914 | ||
915 | ! |
plot_type_6 <- function(plot_base) { |
916 | ! |
shinyjs::show("size") |
917 | ! |
shinyjs::show("alpha") |
918 | ! |
plot <- substitute( |
919 | ! |
expr = ggplot(data = data, aes(.hat, .cooksd)) + |
920 | ! |
geom_vline(xintercept = 0, colour = NA) + |
921 | ! |
geom_abline( |
922 | ! |
slope = seq(0, 3, by = 0.5), |
923 | ! |
colour = "black", |
924 | ! |
linetype = "dashed", |
925 | ! |
size = 1 |
926 |
) + |
|
927 | ! |
geom_line(data = smoothy, mapping = smoothy_aes) + |
928 | ! |
geom_point(size = size, alpha = alpha), |
929 | ! |
env = list(size = size, alpha = alpha) |
930 |
) |
|
931 | ! |
if (show_outlier) { |
932 | ! |
plot <- substitute(expr = plot + outlier_label, env = list(plot = plot, outlier_label = outlier_label())) |
933 |
} |
|
934 | ||
935 | ! |
parsed_ggplot2_args <- teal.widgets::parse_ggplot2_args( |
936 | ! |
teal.widgets::resolve_ggplot2_args( |
937 | ! |
user_plot = ggplot2_args[["Cook's dist vs Leverage"]], |
938 | ! |
user_default = ggplot2_args$default, |
939 | ! |
module_plot = teal.widgets::ggplot2_args( |
940 | ! |
labs = list( |
941 | ! |
x = quote(paste0("Leverage\nlm(", reg_form, ")")), |
942 | ! |
y = "Cooks's distance", |
943 | ! |
title = "Cook's dist vs Leverage" |
944 |
) |
|
945 |
) |
|
946 |
), |
|
947 | ! |
ggtheme = ggtheme |
948 |
) |
|
949 | ||
950 | ! |
teal.code::eval_code( |
951 | ! |
plot_base, |
952 | ! |
substitute( |
953 | ! |
expr = { |
954 | ! |
smoothy <- smooth(data$.hat, data$.cooksd) |
955 | ! |
g <- plot |
956 | ! |
print(g) |
957 |
}, |
|
958 | ! |
env = list( |
959 | ! |
plot = Reduce(function(x, y) call("+", x, y), c(plot, parsed_ggplot2_args)) |
960 |
) |
|
961 |
) |
|
962 |
) |
|
963 |
} |
|
964 | ||
965 | ! |
qenv <- if (input_type == "Response vs Regressor") { |
966 | ! |
plot_type_0() |
967 |
} else { |
|
968 | ! |
plot_base_q <- plot_base() |
969 | ! |
switch(input_type, |
970 | ! |
"Residuals vs Fitted" = plot_base_q %>% plot_type_1(), |
971 | ! |
"Normal Q-Q" = plot_base_q %>% plot_type_2(), |
972 | ! |
"Scale-Location" = plot_base_q %>% plot_type_3(), |
973 | ! |
"Cook's distance" = plot_base_q %>% plot_type_4(), |
974 | ! |
"Residuals vs Leverage" = plot_base_q %>% plot_type_5(), |
975 | ! |
"Cook's dist vs Leverage" = plot_base_q %>% plot_type_6() |
976 |
) |
|
977 |
} |
|
978 | ! |
qenv |
979 |
}) |
|
980 | ||
981 | ||
982 | ! |
fitted <- reactive(output_q()[["fit"]]) |
983 | ! |
plot_r <- reactive(output_q()[["g"]]) |
984 | ||
985 |
# Insert the plot into a plot_with_settings module from teal.widgets |
|
986 | ! |
pws <- teal.widgets::plot_with_settings_srv( |
987 | ! |
id = "myplot", |
988 | ! |
plot_r = plot_r, |
989 | ! |
height = plot_height, |
990 | ! |
width = plot_width |
991 |
) |
|
992 | ||
993 | ! |
output$text <- renderText({ |
994 | ! |
req(iv_r()$is_valid()) |
995 | ! |
req(iv_out$is_valid()) |
996 | ! |
paste(utils::capture.output(summary(teal.code::dev_suppress(fitted())))[-1], |
997 | ! |
collapse = "\n" |
998 |
) |
|
999 |
}) |
|
1000 | ||
1001 | ! |
teal.widgets::verbatim_popup_srv( |
1002 | ! |
id = "rcode", |
1003 | ! |
verbatim_content = reactive(teal.code::get_code(output_q())), |
1004 | ! |
title = "R code for the regression plot", |
1005 |
) |
|
1006 | ||
1007 |
### REPORTER |
|
1008 | ! |
if (with_reporter) { |
1009 | ! |
card_fun <- function(comment, label) { |
1010 | ! |
card <- teal::report_card_template( |
1011 | ! |
title = "Linear Regression Plot", |
1012 | ! |
label = label, |
1013 | ! |
with_filter = with_filter, |
1014 | ! |
filter_panel_api = filter_panel_api |
1015 |
) |
|
1016 | ! |
card$append_text("Plot", "header3") |
1017 | ! |
card$append_plot(plot_r(), dim = pws$dim()) |
1018 | ! |
if (!comment == "") { |
1019 | ! |
card$append_text("Comment", "header3") |
1020 | ! |
card$append_text(comment) |
1021 |
} |
|
1022 | ! |
card$append_src(teal.code::get_code(output_q())) |
1023 | ! |
card |
1024 |
} |
|
1025 | ! |
teal.reporter::simple_reporter_srv("simple_reporter", reporter = reporter, card_fun = card_fun) |
1026 |
} |
|
1027 |
### |
|
1028 |
}) |
|
1029 |
} |
|
1030 | ||
1031 |
regression_names <- paste0( |
|
1032 |
'"Response vs Regressor", "Residuals vs Fitted", ', |
|
1033 |
'"Scale-Location", "Cook\'s distance", "Residuals vs Leverage"", "Cook\'s dist vs Leverage"' |
|
1034 |
) |
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 |
#' 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 |
#' |
|
29 |
#' @param alpha (`integer(1)` or `integer(3)`) optional, specifies point opacity. |
|
30 |
#' - When the length of `alpha` is one: the plot points will have a fixed opacity. |
|
31 |
#' - When the length of `alpha` is three: the plot points opacity are dynamically adjusted based on |
|
32 |
#' vector of `value`, `min`, and `max`. |
|
33 |
#' @param size (`integer(1)` or `integer(3)`) optional, specifies point size. |
|
34 |
#' - When the length of `size` is one: the plot point sizes will have a fixed size. |
|
35 |
#' - When the length of `size` is three: the plot points size are dynamically adjusted based on |
|
36 |
#' vector of `value`, `min`, and `max`. |
|
37 |
#' |
|
38 |
#' @return Object of class `teal_module` to be used in `teal` applications. |
|
39 |
#' |
|
40 |
#' @name shared_params |
|
41 |
#' @keywords internal |
|
42 |
NULL |
|
43 | ||
44 |
#' Add labels for facets to a `ggplot2` object |
|
45 |
#' |
|
46 |
#' Enhances a `ggplot2` plot by adding labels that describe |
|
47 |
#' the faceting variables along the x and y axes. |
|
48 |
#' |
|
49 |
#' @param p (`ggplot2`) object to which facet labels will be added. |
|
50 |
#' @param xfacet_label (`character`) Label for the facet along the x-axis. |
|
51 |
#' If `NULL`, no label is added. If a vector, labels are joined with " & ". |
|
52 |
#' @param yfacet_label (`character`) Label for the facet along the y-axis. |
|
53 |
#' Similar behavior to `xfacet_label`. |
|
54 |
#' |
|
55 |
#' @return Returns `grid` or `grob` object (to be drawn with `grid.draw`) |
|
56 |
#' |
|
57 |
#' @examples |
|
58 |
#' library(ggplot2) |
|
59 |
#' library(grid) |
|
60 |
#' |
|
61 |
#' p <- ggplot(mtcars) + |
|
62 |
#' aes(x = mpg, y = disp) + |
|
63 |
#' geom_point() + |
|
64 |
#' facet_grid(gear ~ cyl) |
|
65 |
#' |
|
66 |
#' xfacet_label <- "cylinders" |
|
67 |
#' yfacet_label <- "gear" |
|
68 |
#' res <- add_facet_labels(p, xfacet_label, yfacet_label) |
|
69 |
#' grid.newpage() |
|
70 |
#' grid.draw(res) |
|
71 |
#' |
|
72 |
#' grid.newpage() |
|
73 |
#' grid.draw(add_facet_labels(p, xfacet_label = NULL, yfacet_label)) |
|
74 |
#' grid.newpage() |
|
75 |
#' grid.draw(add_facet_labels(p, xfacet_label, yfacet_label = NULL)) |
|
76 |
#' grid.newpage() |
|
77 |
#' grid.draw(add_facet_labels(p, xfacet_label = NULL, yfacet_label = NULL)) |
|
78 |
#' |
|
79 |
#' @export |
|
80 |
#' |
|
81 |
add_facet_labels <- function(p, xfacet_label = NULL, yfacet_label = NULL) { |
|
82 | ! |
checkmate::assert_class(p, classes = "ggplot") |
83 | ! |
checkmate::assert_character(xfacet_label, null.ok = TRUE, min.len = 1) |
84 | ! |
checkmate::assert_character(yfacet_label, null.ok = TRUE, min.len = 1) |
85 | ! |
if (is.null(xfacet_label) && is.null(yfacet_label)) { |
86 | ! |
return(ggplotGrob(p)) |
87 |
} |
|
88 | ! |
grid::grid.grabExpr({ |
89 | ! |
g <- ggplotGrob(p) |
90 | ||
91 |
# we are going to replace these, so we make sure they have nothing in them |
|
92 | ! |
checkmate::assert_class(g$grobs[[grep("xlab-t", g$layout$name, fixed = TRUE)]], "zeroGrob") |
93 | ! |
checkmate::assert_class(g$grobs[[grep("ylab-r", g$layout$name, fixed = TRUE)]], "zeroGrob") |
94 | ||
95 | ! |
xaxis_label_grob <- g$grobs[[grep("xlab-b", g$layout$name, fixed = TRUE)]] |
96 | ! |
xaxis_label_grob$children[[1]]$label <- paste(xfacet_label, collapse = " & ") |
97 | ! |
yaxis_label_grob <- g$grobs[[grep("ylab-l", g$layout$name, fixed = TRUE)]] |
98 | ! |
yaxis_label_grob$children[[1]]$label <- paste(yfacet_label, collapse = " & ") |
99 | ! |
yaxis_label_grob$children[[1]]$rot <- 270 |
100 | ||
101 | ! |
top_height <- if (is.null(xfacet_label)) 0 else grid::unit(2, "line") |
102 | ! |
right_width <- if (is.null(yfacet_label)) 0 else grid::unit(2, "line") |
103 | ||
104 | ! |
grid::grid.newpage() |
105 | ! |
grid::pushViewport(grid::plotViewport(margins = c(0, 0, top_height, right_width), name = "ggplot")) |
106 | ! |
grid::grid.draw(g) |
107 | ! |
grid::upViewport(1) |
108 | ||
109 |
# draw x facet |
|
110 | ! |
if (!is.null(xfacet_label)) { |
111 | ! |
grid::pushViewport(grid::viewport( |
112 | ! |
x = 0, y = grid::unit(1, "npc") - top_height, width = grid::unit(1, "npc"), |
113 | ! |
height = top_height, just = c("left", "bottom"), name = "topxaxis" |
114 |
)) |
|
115 | ! |
grid::grid.draw(xaxis_label_grob) |
116 | ! |
grid::upViewport(1) |
117 |
} |
|
118 | ||
119 |
# draw y facet |
|
120 | ! |
if (!is.null(yfacet_label)) { |
121 | ! |
grid::pushViewport(grid::viewport( |
122 | ! |
x = grid::unit(1, "npc") - grid::unit(as.numeric(right_width) / 2, "line"), y = 0, width = right_width, |
123 | ! |
height = grid::unit(1, "npc"), just = c("left", "bottom"), name = "rightyaxis" |
124 |
)) |
|
125 | ! |
grid::grid.draw(yaxis_label_grob) |
126 | ! |
grid::upViewport(1) |
127 |
} |
|
128 |
}) |
|
129 |
} |
|
130 | ||
131 |
#' Call a function with a character vector for the `...` argument |
|
132 |
#' |
|
133 |
#' @param fun (`character`) Name of a function where the `...` argument shall be replaced by values from `str_args`. |
|
134 |
#' @param str_args (`character`) A character vector that the function shall be executed with |
|
135 |
#' |
|
136 |
#' @return |
|
137 |
#' Value of call to `fun` with arguments specified in `str_args`. |
|
138 |
#' |
|
139 |
#' @keywords internal |
|
140 |
call_fun_dots <- function(fun, str_args) { |
|
141 | ! |
do.call("call", c(list(fun), lapply(str_args, as.name)), quote = TRUE) |
142 |
} |
|
143 | ||
144 |
#' Generate a string for a variable including its label |
|
145 |
#' |
|
146 |
#' @param var_names (`character`) Name of variable to extract labels from. |
|
147 |
#' @param dataset (`dataset`) Name of analysis dataset. |
|
148 |
#' @param prefix,suffix (`character`) String to paste to the beginning/end of the variable name with label. |
|
149 |
#' @param wrap_width (`numeric`) Number of characters to wrap original label to. Defaults to 80. |
|
150 |
#' |
|
151 |
#' @return (`character`) String with variable name and label. |
|
152 |
#' |
|
153 |
#' @keywords internal |
|
154 |
#' |
|
155 |
varname_w_label <- function(var_names, |
|
156 |
dataset, |
|
157 |
wrap_width = 80, |
|
158 |
prefix = NULL, |
|
159 |
suffix = NULL) { |
|
160 | ! |
add_label <- function(var_names) { |
161 | ! |
label <- vapply( |
162 | ! |
dataset[var_names], function(x) { |
163 | ! |
attr_label <- attr(x, "label") |
164 | ! |
`if`(is.null(attr_label), "", attr_label) |
165 |
}, |
|
166 | ! |
character(1) |
167 |
) |
|
168 | ||
169 | ! |
if (length(label) == 1 && !is.na(label) && !identical(label, "")) { |
170 | ! |
paste0(prefix, label, " [", var_names, "]", suffix) |
171 |
} else { |
|
172 | ! |
var_names |
173 |
} |
|
174 |
} |
|
175 | ||
176 | ! |
if (length(var_names) < 1) { |
177 | ! |
NULL |
178 | ! |
} else if (length(var_names) == 1) { |
179 | ! |
stringr::str_wrap(add_label(var_names), width = wrap_width) |
180 | ! |
} else if (length(var_names) > 1) { |
181 | ! |
stringr::str_wrap(vapply(var_names, add_label, character(1)), width = wrap_width) |
182 |
} |
|
183 |
} |
|
184 | ||
185 |
# see vignette("ggplot2-specs", package="ggplot2") |
|
186 |
shape_names <- c( |
|
187 |
"circle", paste("circle", c("open", "filled", "cross", "plus", "small")), "bullet", |
|
188 |
"square", paste("square", c("open", "filled", "cross", "plus", "triangle")), |
|
189 |
"diamond", paste("diamond", c("open", "filled", "plus")), |
|
190 |
"triangle", paste("triangle", c("open", "filled", "square")), |
|
191 |
paste("triangle down", c("open", "filled")), |
|
192 |
"plus", "cross", "asterisk" |
|
193 |
) |
|
194 | ||
195 |
#' Get icons to represent variable types in dataset |
|
196 |
#' |
|
197 |
#' @param var_type (`character`) of R internal types (classes). |
|
198 |
#' @return (`character`) vector of HTML icons corresponding to data type in each column. |
|
199 |
#' @keywords internal |
|
200 |
variable_type_icons <- function(var_type) { |
|
201 | ! |
checkmate::assert_character(var_type, any.missing = FALSE) |
202 | ||
203 | ! |
class_to_icon <- list( |
204 | ! |
numeric = "arrow-up-1-9", |
205 | ! |
integer = "arrow-up-1-9", |
206 | ! |
logical = "pause", |
207 | ! |
Date = "calendar", |
208 | ! |
POSIXct = "calendar", |
209 | ! |
POSIXlt = "calendar", |
210 | ! |
factor = "chart-bar", |
211 | ! |
character = "keyboard", |
212 | ! |
primary_key = "key", |
213 | ! |
unknown = "circle-question" |
214 |
) |
|
215 | ! |
class_to_icon <- lapply(class_to_icon, function(icon_name) toString(icon(icon_name, lib = "font-awesome"))) |
216 | ||
217 | ! |
unname(vapply( |
218 | ! |
var_type, |
219 | ! |
FUN.VALUE = character(1), |
220 | ! |
FUN = function(class) { |
221 | ! |
if (class == "") { |
222 | ! |
class |
223 | ! |
} else if (is.null(class_to_icon[[class]])) { |
224 | ! |
class_to_icon[["unknown"]] |
225 |
} else { |
|
226 | ! |
class_to_icon[[class]] |
227 |
} |
|
228 |
} |
|
229 |
)) |
|
230 |
} |
|
231 | ||
232 |
#' Include `CSS` files from `/inst/css/` package directory to application header |
|
233 |
#' |
|
234 |
#' `system.file` should not be used to access files in other packages, it does |
|
235 |
#' not work with `devtools`. Therefore, we redefine this method in each package |
|
236 |
#' as needed. Thus, we do not export this method |
|
237 |
#' |
|
238 |
#' @param pattern (`character`) optional, regular expression to match the file names to be included. |
|
239 |
#' |
|
240 |
#' @return HTML code that includes `CSS` files. |
|
241 |
#' @keywords internal |
|
242 |
#' |
|
243 |
include_css_files <- function(pattern = "*") { |
|
244 | ! |
css_files <- list.files( |
245 | ! |
system.file("css", package = "teal.modules.general", mustWork = TRUE), |
246 | ! |
pattern = pattern, full.names = TRUE |
247 |
) |
|
248 | ! |
if (length(css_files) == 0) { |
249 | ! |
return(NULL) |
250 |
} |
|
251 | ! |
singleton(tags$head(lapply(css_files, includeCSS))) |
252 |
} |
|
253 | ||
254 |
#' JavaScript condition to check if a specific tab is active |
|
255 |
#' |
|
256 |
#' @param id (`character(1)`) the id of the tab panel with tabs. |
|
257 |
#' @param name (`character(1)`) the name of the tab. |
|
258 |
#' @return JavaScript expression to be used in `shiny::conditionalPanel()` to determine |
|
259 |
#' if the specified tab is active. |
|
260 |
#' @keywords internal |
|
261 |
#' |
|
262 |
is_tab_active_js <- function(id, name) { |
|
263 |
# supporting the bs3 and higher version at the same time |
|
264 | ! |
sprintf( |
265 | ! |
"$(\"#%1$s > li.active\").text().trim() == '%2$s' || $(\"#%1$s > li a.active\").text().trim() == '%2$s'", |
266 | ! |
id, name |
267 |
) |
|
268 |
} |
|
269 | ||
270 |
#' Assert single selection on `data_extract_spec` object |
|
271 |
#' Helper to reduce code in assertions |
|
272 |
#' @noRd |
|
273 |
#' |
|
274 |
assert_single_selection <- function(x, |
|
275 |
.var.name = checkmate::vname(x)) { # nolint: object_name. |
|
276 | 104x |
if (any(vapply(x, function(.x) .x$select$multiple, logical(1)))) { |
277 | 4x |
stop("'", .var.name, "' should not allow multiple selection") |
278 |
} |
|
279 | 100x |
invisible(TRUE) |
280 |
} |
1 |
#' `teal` module: Front page |
|
2 |
#' |
|
3 |
#' Creates a simple front page for `teal` applications, displaying |
|
4 |
#' introductory text, tables, additional `html` or `shiny` tags, and footnotes. |
|
5 |
#' |
|
6 |
#' @inheritParams teal::module |
|
7 |
#' @param header_text (`character` vector) text to be shown at the top of the module, for each |
|
8 |
#' element, if named the name is shown first in bold as a header followed by the value. The first |
|
9 |
#' element's header is displayed larger than the others. |
|
10 |
#' @param tables (`named list` of `data.frame`s) tables to be shown in the module. |
|
11 |
#' @param additional_tags (`shiny.tag.list` or `html`) additional `shiny` tags or `html` to be included after the table, |
|
12 |
#' for example to include an image, `tagList(tags$img(src = "image.png"))` or to include further `html`, |
|
13 |
#' `HTML("html text here")`. |
|
14 |
#' @param footnotes (`character` vector) of text to be shown at the bottom of the module, for each |
|
15 |
#' element, if named the name is shown first in bold, followed by the value. |
|
16 |
#' @param show_metadata (`logical`) indicating whether the metadata of the datasets be available on the module. |
|
17 |
#' |
|
18 |
#' @inherit shared_params return |
|
19 |
#' |
|
20 |
#' @examplesShinylive |
|
21 |
#' library(teal.modules.general) |
|
22 |
#' interactive <- function() TRUE |
|
23 |
#' {{ next_example }} |
|
24 |
#' @examples |
|
25 |
#' data <- teal_data() |
|
26 |
#' data <- within(data, { |
|
27 |
#' require(nestcolor) |
|
28 |
#' ADSL <- rADSL |
|
29 |
#' attr(ADSL, "metadata") <- list("Author" = "NEST team", "data_source" = "synthetic data") |
|
30 |
#' }) |
|
31 |
#' join_keys(data) <- default_cdisc_join_keys[names(data)] |
|
32 |
#' |
|
33 |
#' table_1 <- data.frame(Info = c("A", "B"), Text = c("A", "B")) |
|
34 |
#' table_2 <- data.frame(`Column 1` = c("C", "D"), `Column 2` = c(5.5, 6.6), `Column 3` = c("A", "B")) |
|
35 |
#' table_3 <- data.frame(Info = c("E", "F"), Text = c("G", "H")) |
|
36 |
#' |
|
37 |
#' table_input <- list( |
|
38 |
#' "Table 1" = table_1, |
|
39 |
#' "Table 2" = table_2, |
|
40 |
#' "Table 3" = table_3 |
|
41 |
#' ) |
|
42 |
#' |
|
43 |
#' app <- init( |
|
44 |
#' data = data, |
|
45 |
#' modules = modules( |
|
46 |
#' tm_front_page( |
|
47 |
#' header_text = c( |
|
48 |
#' "Important information" = "It can go here.", |
|
49 |
#' "Other information" = "Can go here." |
|
50 |
#' ), |
|
51 |
#' tables = table_input, |
|
52 |
#' additional_tags = HTML("Additional HTML or shiny tags go here <br>"), |
|
53 |
#' footnotes = c("X" = "is the first footnote", "Y is the second footnote"), |
|
54 |
#' show_metadata = TRUE |
|
55 |
#' ) |
|
56 |
#' ), |
|
57 |
#' header = tags$h1("Sample Application"), |
|
58 |
#' footer = tags$p("Application footer"), |
|
59 |
#' ) |
|
60 |
#' |
|
61 |
#' if (interactive()) { |
|
62 |
#' shinyApp(app$ui, app$server) |
|
63 |
#' } |
|
64 |
#' |
|
65 |
#' @export |
|
66 |
#' |
|
67 |
tm_front_page <- function(label = "Front page", |
|
68 |
header_text = character(0), |
|
69 |
tables = list(), |
|
70 |
additional_tags = tagList(), |
|
71 |
footnotes = character(0), |
|
72 |
show_metadata = FALSE) { |
|
73 | ! |
message("Initializing tm_front_page") |
74 | ||
75 |
# Start of assertions |
|
76 | ! |
checkmate::assert_string(label) |
77 | ! |
checkmate::assert_character(header_text, min.len = 0, any.missing = FALSE) |
78 | ! |
checkmate::assert_list(tables, types = "data.frame", names = "named", any.missing = FALSE) |
79 | ! |
checkmate::assert_multi_class(additional_tags, classes = c("shiny.tag.list", "html")) |
80 | ! |
checkmate::assert_character(footnotes, min.len = 0, any.missing = FALSE) |
81 | ! |
checkmate::assert_flag(show_metadata) |
82 |
# End of assertions |
|
83 | ||
84 |
# Make UI args |
|
85 | ! |
args <- as.list(environment()) |
86 | ||
87 | ! |
ans <- module( |
88 | ! |
label = label, |
89 | ! |
server = srv_front_page, |
90 | ! |
ui = ui_front_page, |
91 | ! |
ui_args = args, |
92 | ! |
server_args = list(tables = tables, show_metadata = show_metadata), |
93 | ! |
datanames = if (show_metadata) "all" else NULL |
94 |
) |
|
95 | ! |
attr(ans, "teal_bookmarkable") <- TRUE |
96 | ! |
ans |
97 |
} |
|
98 | ||
99 |
# UI function for the front page module |
|
100 |
ui_front_page <- function(id, ...) { |
|
101 | ! |
args <- list(...) |
102 | ! |
ns <- NS(id) |
103 | ||
104 | ! |
tagList( |
105 | ! |
include_css_files("custom"), |
106 | ! |
tags$div( |
107 | ! |
id = "front_page_content", |
108 | ! |
class = "ml-8", |
109 | ! |
tags$div( |
110 | ! |
id = "front_page_headers", |
111 | ! |
get_header_tags(args$header_text) |
112 |
), |
|
113 | ! |
tags$div( |
114 | ! |
id = "front_page_tables", |
115 | ! |
class = "ml-4", |
116 | ! |
get_table_tags(args$tables, ns) |
117 |
), |
|
118 | ! |
tags$div( |
119 | ! |
id = "front_page_custom_html", |
120 | ! |
class = "my-4", |
121 | ! |
args$additional_tags |
122 |
), |
|
123 | ! |
if (args$show_metadata) { |
124 | ! |
tags$div( |
125 | ! |
id = "front_page_metabutton", |
126 | ! |
class = "m-4", |
127 | ! |
actionButton(ns("metadata_button"), "Show metadata") |
128 |
) |
|
129 |
}, |
|
130 | ! |
tags$footer( |
131 | ! |
class = ".small", |
132 | ! |
get_footer_tags(args$footnotes) |
133 |
) |
|
134 |
) |
|
135 |
) |
|
136 |
} |
|
137 | ||
138 |
# Server function for the front page module |
|
139 |
srv_front_page <- function(id, data, tables, show_metadata) { |
|
140 | ! |
checkmate::assert_class(data, "reactive") |
141 | ! |
checkmate::assert_class(isolate(data()), "teal_data") |
142 | ! |
moduleServer(id, function(input, output, session) { |
143 | ! |
teal.logger::log_shiny_input_changes(input, namespace = "teal.modules.general") |
144 | ||
145 | ! |
ns <- session$ns |
146 | ||
147 | ! |
setBookmarkExclude("metadata_button") |
148 | ||
149 | ! |
lapply(seq_along(tables), function(idx) { |
150 | ! |
output[[paste0("table_", idx)]] <- renderTable( |
151 | ! |
tables[[idx]], |
152 | ! |
bordered = TRUE, |
153 | ! |
caption = names(tables)[idx], |
154 | ! |
caption.placement = "top" |
155 |
) |
|
156 |
}) |
|
157 | ||
158 | ! |
if (show_metadata) { |
159 | ! |
observeEvent( |
160 | ! |
input$metadata_button, showModal( |
161 | ! |
modalDialog( |
162 | ! |
title = "Metadata", |
163 | ! |
dataTableOutput(ns("metadata_table")), |
164 | ! |
size = "l", |
165 | ! |
easyClose = TRUE |
166 |
) |
|
167 |
) |
|
168 |
) |
|
169 | ||
170 | ! |
metadata_data_frame <- reactive({ |
171 | ! |
datanames <- names(data()) |
172 | ! |
convert_metadata_to_dataframe( |
173 | ! |
lapply(datanames, function(dataname) attr(data()[[dataname]], "metadata")), |
174 | ! |
datanames |
175 |
) |
|
176 |
}) |
|
177 | ||
178 | ! |
output$metadata_table <- renderDataTable({ |
179 | ! |
validate(need(nrow(metadata_data_frame()) > 0, "The data has no associated metadata")) |
180 | ! |
metadata_data_frame() |
181 |
}) |
|
182 |
} |
|
183 |
}) |
|
184 |
} |
|
185 | ||
186 |
## utils functions |
|
187 | ||
188 |
get_header_tags <- function(header_text) { |
|
189 | ! |
if (length(header_text) == 0) { |
190 | ! |
return(list()) |
191 |
} |
|
192 | ||
193 | ! |
get_single_header_tags <- function(header_text, p_text, header_tag = tags$h4) { |
194 | ! |
tagList( |
195 | ! |
tags$div( |
196 | ! |
if (!is.null(header_text) && nchar(header_text) > 0) header_tag(header_text), |
197 | ! |
tags$p(p_text) |
198 |
) |
|
199 |
) |
|
200 |
} |
|
201 | ||
202 | ! |
header_tags <- get_single_header_tags(names(header_text[1]), header_text[1], header_tag = tags$h3) |
203 | ! |
c(header_tags, mapply(get_single_header_tags, utils::tail(names(header_text), -1), utils::tail(header_text, -1))) |
204 |
} |
|
205 | ||
206 |
get_table_tags <- function(tables, ns) { |
|
207 | ! |
if (length(tables) == 0) { |
208 | ! |
return(list()) |
209 |
} |
|
210 | ! |
table_tags <- c(lapply(seq_along(tables), function(idx) { |
211 | ! |
list( |
212 | ! |
tableOutput(ns(paste0("table_", idx))) |
213 |
) |
|
214 |
})) |
|
215 | ! |
return(table_tags) |
216 |
} |
|
217 | ||
218 |
get_footer_tags <- function(footnotes) { |
|
219 | ! |
if (length(footnotes) == 0) { |
220 | ! |
return(list()) |
221 |
} |
|
222 | ! |
bold_texts <- if (is.null(names(footnotes))) rep("", length(footnotes)) else names(footnotes) |
223 | ! |
footnote_tags <- mapply(function(bold_text, value) { |
224 | ! |
list( |
225 | ! |
tags$div( |
226 | ! |
tags$b(bold_text), |
227 | ! |
value, |
228 | ! |
tags$br() |
229 |
) |
|
230 |
) |
|
231 | ! |
}, bold_text = bold_texts, value = footnotes) |
232 |
} |
|
233 | ||
234 |
# take a list of metadata, one item per dataset (raw_metadata each element from datasets$get_metadata()) |
|
235 |
# and the corresponding datanames and output a data.frame with columns {Dataset, Name, Value}. |
|
236 |
# which are, the Dataset the metadata came from, the metadata's name and value |
|
237 |
convert_metadata_to_dataframe <- function(raw_metadata, datanames) { |
|
238 | 4x |
output <- mapply(function(metadata, dataname) { |
239 | 6x |
if (is.null(metadata)) { |
240 | 2x |
return(data.frame(Dataset = character(0), Name = character(0), Value = character(0))) |
241 |
} |
|
242 | 4x |
return(data.frame( |
243 | 4x |
Dataset = dataname, |
244 | 4x |
Name = names(metadata), |
245 | 4x |
Value = unname(unlist(lapply(metadata, as.character))) |
246 |
)) |
|
247 | 4x |
}, raw_metadata, datanames, SIMPLIFY = FALSE) |
248 | 4x |
do.call(rbind, output) |
249 |
} |
1 |
.onLoad <- function(libname, pkgname) { |
|
2 | ! |
teal.logger::register_logger(namespace = "teal.modules.general") |
3 | ! |
teal.logger::register_handlers("teal.modules.general") |
4 |
} |
|
5 | ||
6 |
### global variables |
|
7 |
ggplot_themes <- c("gray", "bw", "linedraw", "light", "dark", "minimal", "classic", "void") |
|
8 | ||
9 |
interactive <- NULL |