1 |
#' Difference Test for Two Proportions |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Various tests were implemented to test the difference between two proportions. |
|
6 |
#' |
|
7 |
#' @inheritParams argument_convention |
|
8 |
#' @param method (`string`)\cr one of `chisq`, `cmh`, `fisher`, or `schouten`; specifies the test used |
|
9 |
#' to calculate the p-value. |
|
10 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("test_proportion_diff")` |
|
11 |
#' to see available statistics for this function. |
|
12 |
#' |
|
13 |
#' @seealso [h_prop_diff_test] |
|
14 |
#' |
|
15 |
#' @name prop_diff_test |
|
16 |
#' @order 1 |
|
17 |
NULL |
|
18 | ||
19 |
#' @describeIn prop_diff_test Statistics function which tests the difference between two proportions. |
|
20 |
#' |
|
21 |
#' @return |
|
22 |
#' * `s_test_proportion_diff()` returns a named `list` with a single item `pval` with an attribute `label` |
|
23 |
#' describing the method used. The p-value tests the null hypothesis that proportions in two groups are the same. |
|
24 |
#' |
|
25 |
#' @keywords internal |
|
26 |
s_test_proportion_diff <- function(df, |
|
27 |
.var, |
|
28 |
.ref_group, |
|
29 |
.in_ref_col, |
|
30 |
variables = list(strata = NULL), |
|
31 |
method = c("chisq", "schouten", "fisher", "cmh")) { |
|
32 | 35x |
method <- match.arg(method) |
33 | 35x |
y <- list(pval = "") |
34 | ||
35 | 35x |
if (!.in_ref_col) { |
36 | 35x |
assert_df_with_variables(df, list(rsp = .var)) |
37 | 35x |
assert_df_with_variables(.ref_group, list(rsp = .var)) |
38 | 35x |
rsp <- factor( |
39 | 35x |
c(.ref_group[[.var]], df[[.var]]), |
40 | 35x |
levels = c("TRUE", "FALSE") |
41 |
) |
|
42 | 35x |
grp <- factor( |
43 | 35x |
rep(c("ref", "Not-ref"), c(nrow(.ref_group), nrow(df))), |
44 | 35x |
levels = c("ref", "Not-ref") |
45 |
) |
|
46 | ||
47 | 35x |
if (!is.null(variables$strata) || method == "cmh") { |
48 | 12x |
strata <- variables$strata |
49 | 12x |
checkmate::assert_false(is.null(strata)) |
50 | 12x |
strata_vars <- stats::setNames(as.list(strata), strata) |
51 | 12x |
assert_df_with_variables(df, strata_vars) |
52 | 12x |
assert_df_with_variables(.ref_group, strata_vars) |
53 | 12x |
strata <- c(interaction(.ref_group[strata]), interaction(df[strata])) |
54 |
} |
|
55 | ||
56 | 35x |
tbl <- switch(method, |
57 | 35x |
cmh = table(grp, rsp, strata), |
58 | 35x |
table(grp, rsp) |
59 |
) |
|
60 | ||
61 | 35x |
y$pval <- switch(method, |
62 | 35x |
chisq = prop_chisq(tbl), |
63 | 35x |
cmh = prop_cmh(tbl), |
64 | 35x |
fisher = prop_fisher(tbl), |
65 | 35x |
schouten = prop_schouten(tbl) |
66 |
) |
|
67 |
} |
|
68 | ||
69 | 35x |
y$pval <- formatters::with_label(y$pval, d_test_proportion_diff(method)) |
70 | 35x |
y |
71 |
} |
|
72 | ||
73 |
#' Description of the Difference Test Between Two Proportions |
|
74 |
#' |
|
75 |
#' @description `r lifecycle::badge("stable")` |
|
76 |
#' |
|
77 |
#' This is an auxiliary function that describes the analysis in `s_test_proportion_diff`. |
|
78 |
#' |
|
79 |
#' @inheritParams s_test_proportion_diff |
|
80 |
#' |
|
81 |
#' @return `string` describing the test from which the p-value is derived. |
|
82 |
#' |
|
83 |
#' @export |
|
84 |
d_test_proportion_diff <- function(method) { |
|
85 | 49x |
checkmate::assert_string(method) |
86 | 49x |
meth_part <- switch(method, |
87 | 49x |
"schouten" = "Chi-Squared Test with Schouten Correction", |
88 | 49x |
"chisq" = "Chi-Squared Test", |
89 | 49x |
"cmh" = "Cochran-Mantel-Haenszel Test", |
90 | 49x |
"fisher" = "Fisher's Exact Test", |
91 | 49x |
stop(paste(method, "does not have a description")) |
92 |
) |
|
93 | 49x |
paste0("p-value (", meth_part, ")") |
94 |
} |
|
95 | ||
96 |
#' @describeIn prop_diff_test Formatted analysis function which is used as `afun` in `test_proportion_diff()`. |
|
97 |
#' |
|
98 |
#' @return |
|
99 |
#' * `a_test_proportion_diff()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
100 |
#' |
|
101 |
#' @keywords internal |
|
102 |
a_test_proportion_diff <- make_afun( |
|
103 |
s_test_proportion_diff, |
|
104 |
.formats = c(pval = "x.xxxx | (<0.0001)"), |
|
105 |
.indent_mods = c(pval = 1L) |
|
106 |
) |
|
107 | ||
108 |
#' @describeIn prop_diff_test Layout-creating function which can take statistics function arguments |
|
109 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
110 |
#' |
|
111 |
#' @return |
|
112 |
#' * `test_proportion_diff()` returns a layout object suitable for passing to further layouting functions, |
|
113 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
114 |
#' the statistics from `s_test_proportion_diff()` to the table layout. |
|
115 |
#' |
|
116 |
#' @examples |
|
117 |
#' dta <- data.frame( |
|
118 |
#' rsp = sample(c(TRUE, FALSE), 100, TRUE), |
|
119 |
#' grp = factor(rep(c("A", "B"), each = 50)), |
|
120 |
#' strat = factor(rep(c("V", "W", "X", "Y", "Z"), each = 20)) |
|
121 |
#' ) |
|
122 |
#' |
|
123 |
#' # With `rtables` pipelines. |
|
124 |
#' l <- basic_table() %>% |
|
125 |
#' split_cols_by(var = "grp", ref_group = "B") %>% |
|
126 |
#' test_proportion_diff( |
|
127 |
#' vars = "rsp", |
|
128 |
#' method = "cmh", variables = list(strata = "strat") |
|
129 |
#' ) |
|
130 |
#' |
|
131 |
#' build_table(l, df = dta) |
|
132 |
#' |
|
133 |
#' @export |
|
134 |
#' @order 2 |
|
135 |
test_proportion_diff <- function(lyt, |
|
136 |
vars, |
|
137 |
variables = list(strata = NULL), |
|
138 |
method = c("chisq", "schouten", "fisher", "cmh"), |
|
139 |
na_str = default_na_str(), |
|
140 |
nested = TRUE, |
|
141 |
..., |
|
142 |
var_labels = vars, |
|
143 |
show_labels = "hidden", |
|
144 |
table_names = vars, |
|
145 |
.stats = NULL, |
|
146 |
.formats = NULL, |
|
147 |
.labels = NULL, |
|
148 |
.indent_mods = NULL) { |
|
149 | 6x |
extra_args <- list(variables = variables, method = method, ...) |
150 | ||
151 | 6x |
afun <- make_afun( |
152 | 6x |
a_test_proportion_diff, |
153 | 6x |
.stats = .stats, |
154 | 6x |
.formats = .formats, |
155 | 6x |
.labels = .labels, |
156 | 6x |
.indent_mods = .indent_mods |
157 |
) |
|
158 | 6x |
analyze( |
159 | 6x |
lyt, |
160 | 6x |
vars, |
161 | 6x |
afun = afun, |
162 | 6x |
var_labels = var_labels, |
163 | 6x |
na_str = na_str, |
164 | 6x |
nested = nested, |
165 | 6x |
extra_args = extra_args, |
166 | 6x |
show_labels = show_labels, |
167 | 6x |
table_names = table_names |
168 |
) |
|
169 |
} |
|
170 | ||
171 |
#' Helper Functions to Test Proportion Differences |
|
172 |
#' |
|
173 |
#' Helper functions to implement various tests on the difference between two proportions. |
|
174 |
#' |
|
175 |
#' @param tbl (`matrix`)\cr matrix with two groups in rows and the binary response (`TRUE`/`FALSE`) in columns. |
|
176 |
#' |
|
177 |
#' @return A p-value. |
|
178 |
#' |
|
179 |
#' @seealso [prop_diff_test()] for implementation of these helper functions. |
|
180 |
#' |
|
181 |
#' @name h_prop_diff_test |
|
182 |
NULL |
|
183 | ||
184 |
#' @describeIn h_prop_diff_test performs Chi-Squared test. Internally calls [stats::prop.test()]. |
|
185 |
#' |
|
186 |
#' @keywords internal |
|
187 |
prop_chisq <- function(tbl) { |
|
188 | 30x |
checkmate::assert_integer(c(ncol(tbl), nrow(tbl)), lower = 2, upper = 2) |
189 | 30x |
tbl <- tbl[, c("TRUE", "FALSE")] |
190 | 30x |
if (any(colSums(tbl) == 0)) { |
191 | 2x |
return(1) |
192 |
} |
|
193 | 28x |
stats::prop.test(tbl, correct = FALSE)$p.value |
194 |
} |
|
195 | ||
196 |
#' @describeIn h_prop_diff_test performs stratified Cochran-Mantel-Haenszel test. Internally calls |
|
197 |
#' [stats::mantelhaen.test()]. Note that strata with less than two observations are automatically discarded. |
|
198 |
#' |
|
199 |
#' @param ary (`array`, 3 dimensions)\cr array with two groups in rows, the binary response |
|
200 |
#' (`TRUE`/`FALSE`) in columns, and the strata in the third dimension. |
|
201 |
#' |
|
202 |
#' @keywords internal |
|
203 |
prop_cmh <- function(ary) { |
|
204 | 16x |
checkmate::assert_array(ary) |
205 | 16x |
checkmate::assert_integer(c(ncol(ary), nrow(ary)), lower = 2, upper = 2) |
206 | 16x |
checkmate::assert_integer(length(dim(ary)), lower = 3, upper = 3) |
207 | 16x |
strata_sizes <- apply(ary, MARGIN = 3, sum) |
208 | 16x |
if (any(strata_sizes < 5)) { |
209 | 1x |
warning("<5 data points in some strata. CMH test may be incorrect.") |
210 | 1x |
ary <- ary[, , strata_sizes > 1] |
211 |
} |
|
212 | ||
213 | 16x |
stats::mantelhaen.test(ary, correct = FALSE)$p.value |
214 |
} |
|
215 | ||
216 |
#' @describeIn h_prop_diff_test performs the Chi-Squared test with Schouten correction. |
|
217 |
#' |
|
218 |
#' @seealso Schouten correction is based upon \insertCite{Schouten1980-kd;textual}{tern}. |
|
219 |
#' |
|
220 |
#' @keywords internal |
|
221 |
prop_schouten <- function(tbl) { |
|
222 | 100x |
checkmate::assert_integer(c(ncol(tbl), nrow(tbl)), lower = 2, upper = 2) |
223 | 100x |
tbl <- tbl[, c("TRUE", "FALSE")] |
224 | 100x |
if (any(colSums(tbl) == 0)) { |
225 | 1x |
return(1) |
226 |
} |
|
227 | ||
228 | 99x |
n <- sum(tbl) |
229 | 99x |
n1 <- sum(tbl[1, ]) |
230 | 99x |
n2 <- sum(tbl[2, ]) |
231 | ||
232 | 99x |
ad <- diag(tbl) |
233 | 99x |
bc <- diag(apply(tbl, 2, rev)) |
234 | 99x |
ac <- tbl[, 1] |
235 | 99x |
bd <- tbl[, 2] |
236 | ||
237 | 99x |
t_schouten <- (n - 1) * |
238 | 99x |
(abs(prod(ad) - prod(bc)) - 0.5 * min(n1, n2))^2 / |
239 | 99x |
(n1 * n2 * sum(ac) * sum(bd)) |
240 | ||
241 | 99x |
1 - stats::pchisq(t_schouten, df = 1) |
242 |
} |
|
243 | ||
244 |
#' @describeIn h_prop_diff_test performs the Fisher's exact test. Internally calls [stats::fisher.test()]. |
|
245 |
#' |
|
246 |
#' @keywords internal |
|
247 |
prop_fisher <- function(tbl) { |
|
248 | 2x |
checkmate::assert_integer(c(ncol(tbl), nrow(tbl)), lower = 2, upper = 2) |
249 | 2x |
tbl <- tbl[, c("TRUE", "FALSE")] |
250 | 2x |
stats::fisher.test(tbl)$p.value |
251 |
} |
1 |
#' Estimation of Proportions |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Estimate the proportion of responders within a studied population. |
|
6 |
#' |
|
7 |
#' @inheritParams prop_strat_wilson |
|
8 |
#' @inheritParams argument_convention |
|
9 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("estimate_proportion")` |
|
10 |
#' to see available statistics for this function. |
|
11 |
#' @param method (`string`)\cr the method used to construct the confidence interval |
|
12 |
#' for proportion of successful outcomes; one of `waldcc`, `wald`, `clopper-pearson`, |
|
13 |
#' `wilson`, `wilsonc`, `strat_wilson`, `strat_wilsonc`, `agresti-coull` or `jeffreys`. |
|
14 |
#' @param long (`flag`)\cr a long description is required. |
|
15 |
#' |
|
16 |
#' @seealso [h_proportions] |
|
17 |
#' |
|
18 |
#' @name estimate_proportions |
|
19 |
#' @order 1 |
|
20 |
NULL |
|
21 | ||
22 |
#' @describeIn estimate_proportions Statistics function estimating a |
|
23 |
#' proportion along with its confidence interval. |
|
24 |
#' |
|
25 |
#' @param df (`logical` or `data.frame`)\cr if only a logical vector is used, |
|
26 |
#' it indicates whether each subject is a responder or not. `TRUE` represents |
|
27 |
#' a successful outcome. If a `data.frame` is provided, also the `strata` variable |
|
28 |
#' names must be provided in `variables` as a list element with the strata strings. |
|
29 |
#' In the case of `data.frame`, the logical vector of responses must be indicated as a |
|
30 |
#' variable name in `.var`. |
|
31 |
#' |
|
32 |
#' @return |
|
33 |
#' * `s_proportion()` returns statistics `n_prop` (`n` and proportion) and `prop_ci` (proportion CI) for a |
|
34 |
#' given variable. |
|
35 |
#' |
|
36 |
#' @examples |
|
37 |
#' # Case with only logical vector. |
|
38 |
#' rsp_v <- c(1, 0, 1, 0, 1, 1, 0, 0) |
|
39 |
#' s_proportion(rsp_v) |
|
40 |
#' |
|
41 |
#' # Example for Stratified Wilson CI |
|
42 |
#' nex <- 100 # Number of example rows |
|
43 |
#' dta <- data.frame( |
|
44 |
#' "rsp" = sample(c(TRUE, FALSE), nex, TRUE), |
|
45 |
#' "grp" = sample(c("A", "B"), nex, TRUE), |
|
46 |
#' "f1" = sample(c("a1", "a2"), nex, TRUE), |
|
47 |
#' "f2" = sample(c("x", "y", "z"), nex, TRUE), |
|
48 |
#' stringsAsFactors = TRUE |
|
49 |
#' ) |
|
50 |
#' |
|
51 |
#' s_proportion( |
|
52 |
#' df = dta, |
|
53 |
#' .var = "rsp", |
|
54 |
#' variables = list(strata = c("f1", "f2")), |
|
55 |
#' conf_level = 0.90, |
|
56 |
#' method = "strat_wilson" |
|
57 |
#' ) |
|
58 |
#' |
|
59 |
#' @export |
|
60 |
s_proportion <- function(df, |
|
61 |
.var, |
|
62 |
conf_level = 0.95, |
|
63 |
method = c( |
|
64 |
"waldcc", "wald", "clopper-pearson", |
|
65 |
"wilson", "wilsonc", "strat_wilson", "strat_wilsonc", |
|
66 |
"agresti-coull", "jeffreys" |
|
67 |
), |
|
68 |
weights = NULL, |
|
69 |
max_iterations = 50, |
|
70 |
variables = list(strata = NULL), |
|
71 |
long = FALSE) { |
|
72 | 135x |
method <- match.arg(method) |
73 | 135x |
checkmate::assert_flag(long) |
74 | 135x |
assert_proportion_value(conf_level) |
75 | ||
76 | 135x |
if (!is.null(variables$strata)) { |
77 |
# Checks for strata |
|
78 | ! |
if (missing(df)) stop("When doing stratified analysis a data.frame with specific columns is needed.") |
79 | ! |
strata_colnames <- variables$strata |
80 | ! |
checkmate::assert_character(strata_colnames, null.ok = FALSE) |
81 | ! |
strata_vars <- stats::setNames(as.list(strata_colnames), strata_colnames) |
82 | ! |
assert_df_with_variables(df, strata_vars) |
83 | ||
84 | ! |
strata <- interaction(df[strata_colnames]) |
85 | ! |
strata <- as.factor(strata) |
86 | ||
87 |
# Pushing down checks to prop_strat_wilson |
|
88 | 135x |
} else if (checkmate::test_subset(method, c("strat_wilson", "strat_wilsonc"))) { |
89 | ! |
stop("To use stratified methods you need to specify the strata variables.") |
90 |
} |
|
91 | 135x |
if (checkmate::test_atomic_vector(df)) { |
92 | 135x |
rsp <- as.logical(df) |
93 |
} else { |
|
94 | ! |
rsp <- as.logical(df[[.var]]) |
95 |
} |
|
96 | 135x |
n <- sum(rsp) |
97 | 135x |
p_hat <- mean(rsp) |
98 | ||
99 | 135x |
prop_ci <- switch(method, |
100 | 135x |
"clopper-pearson" = prop_clopper_pearson(rsp, conf_level), |
101 | 135x |
"wilson" = prop_wilson(rsp, conf_level), |
102 | 135x |
"wilsonc" = prop_wilson(rsp, conf_level, correct = TRUE), |
103 | 135x |
"strat_wilson" = prop_strat_wilson(rsp, |
104 | 135x |
strata, |
105 | 135x |
weights, |
106 | 135x |
conf_level, |
107 | 135x |
max_iterations, |
108 | 135x |
correct = FALSE |
109 | 135x |
)$conf_int, |
110 | 135x |
"strat_wilsonc" = prop_strat_wilson(rsp, |
111 | 135x |
strata, |
112 | 135x |
weights, |
113 | 135x |
conf_level, |
114 | 135x |
max_iterations, |
115 | 135x |
correct = TRUE |
116 | 135x |
)$conf_int, |
117 | 135x |
"wald" = prop_wald(rsp, conf_level), |
118 | 135x |
"waldcc" = prop_wald(rsp, conf_level, correct = TRUE), |
119 | 135x |
"agresti-coull" = prop_agresti_coull(rsp, conf_level), |
120 | 135x |
"jeffreys" = prop_jeffreys(rsp, conf_level) |
121 |
) |
|
122 | ||
123 | 135x |
list( |
124 | 135x |
"n_prop" = formatters::with_label(c(n, p_hat), "Responders"), |
125 | 135x |
"prop_ci" = formatters::with_label( |
126 | 135x |
x = 100 * prop_ci, label = d_proportion(conf_level, method, long = long) |
127 |
) |
|
128 |
) |
|
129 |
} |
|
130 | ||
131 |
#' @describeIn estimate_proportions Formatted analysis function which is used as `afun` |
|
132 |
#' in `estimate_proportion()`. |
|
133 |
#' |
|
134 |
#' @return |
|
135 |
#' * `a_proportion()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
136 |
#' |
|
137 |
#' @export |
|
138 |
a_proportion <- make_afun( |
|
139 |
s_proportion, |
|
140 |
.formats = c(n_prop = "xx (xx.x%)", prop_ci = "(xx.x, xx.x)") |
|
141 |
) |
|
142 | ||
143 |
#' @describeIn estimate_proportions Layout-creating function which can take statistics function arguments |
|
144 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
145 |
#' |
|
146 |
#' @return |
|
147 |
#' * `estimate_proportion()` returns a layout object suitable for passing to further layouting functions, |
|
148 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
149 |
#' the statistics from `s_proportion()` to the table layout. |
|
150 |
#' |
|
151 |
#' @examples |
|
152 |
#' dta_test <- data.frame( |
|
153 |
#' USUBJID = paste0("S", 1:12), |
|
154 |
#' ARM = rep(LETTERS[1:3], each = 4), |
|
155 |
#' AVAL = c(A = c(1, 1, 1, 1), B = c(0, 0, 1, 1), C = c(0, 0, 0, 0)) |
|
156 |
#' ) |
|
157 |
#' |
|
158 |
#' basic_table() %>% |
|
159 |
#' split_cols_by("ARM") %>% |
|
160 |
#' estimate_proportion(vars = "AVAL") %>% |
|
161 |
#' build_table(df = dta_test) |
|
162 |
#' |
|
163 |
#' @export |
|
164 |
#' @order 2 |
|
165 |
estimate_proportion <- function(lyt, |
|
166 |
vars, |
|
167 |
conf_level = 0.95, |
|
168 |
method = c( |
|
169 |
"waldcc", "wald", "clopper-pearson", |
|
170 |
"wilson", "wilsonc", "strat_wilson", "strat_wilsonc", |
|
171 |
"agresti-coull", "jeffreys" |
|
172 |
), |
|
173 |
weights = NULL, |
|
174 |
max_iterations = 50, |
|
175 |
variables = list(strata = NULL), |
|
176 |
long = FALSE, |
|
177 |
na_str = default_na_str(), |
|
178 |
nested = TRUE, |
|
179 |
..., |
|
180 |
show_labels = "hidden", |
|
181 |
table_names = vars, |
|
182 |
.stats = NULL, |
|
183 |
.formats = NULL, |
|
184 |
.labels = NULL, |
|
185 |
.indent_mods = NULL) { |
|
186 | 3x |
extra_args <- list( |
187 | 3x |
conf_level = conf_level, method = method, weights = weights, max_iterations = max_iterations, |
188 | 3x |
variables = variables, long = long, ... |
189 |
) |
|
190 | ||
191 | 3x |
afun <- make_afun( |
192 | 3x |
a_proportion, |
193 | 3x |
.stats = .stats, |
194 | 3x |
.formats = .formats, |
195 | 3x |
.labels = .labels, |
196 | 3x |
.indent_mods = .indent_mods |
197 |
) |
|
198 | 3x |
analyze( |
199 | 3x |
lyt, |
200 | 3x |
vars, |
201 | 3x |
afun = afun, |
202 | 3x |
na_str = na_str, |
203 | 3x |
nested = nested, |
204 | 3x |
extra_args = extra_args, |
205 | 3x |
show_labels = show_labels, |
206 | 3x |
table_names = table_names |
207 |
) |
|
208 |
} |
|
209 | ||
210 |
#' Helper Functions for Calculating Proportion Confidence Intervals |
|
211 |
#' |
|
212 |
#' @description `r lifecycle::badge("stable")` |
|
213 |
#' |
|
214 |
#' Functions to calculate different proportion confidence intervals for use in [estimate_proportion()]. |
|
215 |
#' |
|
216 |
#' @inheritParams argument_convention |
|
217 |
#' @inheritParams estimate_proportions |
|
218 |
#' |
|
219 |
#' @return Confidence interval of a proportion. |
|
220 |
#' |
|
221 |
#' @seealso [estimate_proportions], descriptive function [d_proportion()], |
|
222 |
#' and helper functions [strata_normal_quantile()] and [update_weights_strat_wilson()]. |
|
223 |
#' |
|
224 |
#' @name h_proportions |
|
225 |
NULL |
|
226 | ||
227 |
#' @describeIn h_proportions Calculates the Wilson interval by calling [stats::prop.test()]. |
|
228 |
#' Also referred to as Wilson score interval. |
|
229 |
#' |
|
230 |
#' @examples |
|
231 |
#' rsp <- c( |
|
232 |
#' TRUE, TRUE, TRUE, TRUE, TRUE, |
|
233 |
#' FALSE, FALSE, FALSE, FALSE, FALSE |
|
234 |
#' ) |
|
235 |
#' prop_wilson(rsp, conf_level = 0.9) |
|
236 |
#' |
|
237 |
#' @export |
|
238 |
prop_wilson <- function(rsp, conf_level, correct = FALSE) { |
|
239 | 5x |
y <- stats::prop.test( |
240 | 5x |
sum(rsp), |
241 | 5x |
length(rsp), |
242 | 5x |
correct = correct, |
243 | 5x |
conf.level = conf_level |
244 |
) |
|
245 | ||
246 | 5x |
as.numeric(y$conf.int) |
247 |
} |
|
248 | ||
249 |
#' @describeIn h_proportions Calculates the stratified Wilson confidence |
|
250 |
#' interval for unequal proportions as described in \insertCite{Yan2010-jt;textual}{tern} |
|
251 |
#' |
|
252 |
#' @param strata (`factor`)\cr variable with one level per stratum and same length as `rsp`. |
|
253 |
#' @param weights (`numeric` or `NULL`)\cr weights for each level of the strata. If `NULL`, they are |
|
254 |
#' estimated using the iterative algorithm proposed in \insertCite{Yan2010-jt;textual}{tern} that |
|
255 |
#' minimizes the weighted squared length of the confidence interval. |
|
256 |
#' @param max_iterations (`count`)\cr maximum number of iterations for the iterative procedure used |
|
257 |
#' to find estimates of optimal weights. |
|
258 |
#' @param correct (`flag`)\cr include the continuity correction. For further information, see for example |
|
259 |
#' [stats::prop.test()]. |
|
260 |
#' |
|
261 |
#' @references |
|
262 |
#' \insertRef{Yan2010-jt}{tern} |
|
263 |
#' |
|
264 |
#' @examples |
|
265 |
#' # Stratified Wilson confidence interval with unequal probabilities |
|
266 |
#' |
|
267 |
#' set.seed(1) |
|
268 |
#' rsp <- sample(c(TRUE, FALSE), 100, TRUE) |
|
269 |
#' strata_data <- data.frame( |
|
270 |
#' "f1" = sample(c("a", "b"), 100, TRUE), |
|
271 |
#' "f2" = sample(c("x", "y", "z"), 100, TRUE), |
|
272 |
#' stringsAsFactors = TRUE |
|
273 |
#' ) |
|
274 |
#' strata <- interaction(strata_data) |
|
275 |
#' n_strata <- ncol(table(rsp, strata)) # Number of strata |
|
276 |
#' |
|
277 |
#' prop_strat_wilson( |
|
278 |
#' rsp = rsp, strata = strata, |
|
279 |
#' conf_level = 0.90 |
|
280 |
#' ) |
|
281 |
#' |
|
282 |
#' # Not automatic setting of weights |
|
283 |
#' prop_strat_wilson( |
|
284 |
#' rsp = rsp, strata = strata, |
|
285 |
#' weights = rep(1 / n_strata, n_strata), |
|
286 |
#' conf_level = 0.90 |
|
287 |
#' ) |
|
288 |
#' |
|
289 |
#' @export |
|
290 |
prop_strat_wilson <- function(rsp, |
|
291 |
strata, |
|
292 |
weights = NULL, |
|
293 |
conf_level = 0.95, |
|
294 |
max_iterations = NULL, |
|
295 |
correct = FALSE) { |
|
296 | 20x |
checkmate::assert_logical(rsp, any.missing = FALSE) |
297 | 20x |
checkmate::assert_factor(strata, len = length(rsp)) |
298 | 20x |
assert_proportion_value(conf_level) |
299 | ||
300 | 20x |
tbl <- table(rsp, strata) |
301 | 20x |
n_strata <- length(unique(strata)) |
302 | ||
303 |
# Checking the weights and maximum number of iterations. |
|
304 | 20x |
do_iter <- FALSE |
305 | 20x |
if (is.null(weights)) { |
306 | 6x |
weights <- rep(1 / n_strata, n_strata) # Initialization for iterative procedure |
307 | 6x |
do_iter <- TRUE |
308 | ||
309 |
# Iteration parameters |
|
310 | 2x |
if (is.null(max_iterations)) max_iterations <- 10 |
311 | 6x |
checkmate::assert_int(max_iterations, na.ok = FALSE, null.ok = FALSE, lower = 1) |
312 |
} |
|
313 | 20x |
checkmate::assert_numeric(weights, lower = 0, upper = 1, any.missing = FALSE, len = n_strata) |
314 | 20x |
sum_weights <- checkmate::assert_int(sum(weights)) |
315 | ! |
if (as.integer(sum_weights + 0.5) != 1L) stop("Sum of weights must be 1L.") |
316 | ||
317 | ||
318 | 20x |
xs <- tbl["TRUE", ] |
319 | 20x |
ns <- colSums(tbl) |
320 | 20x |
use_stratum <- (ns > 0) |
321 | 20x |
ns <- ns[use_stratum] |
322 | 20x |
xs <- xs[use_stratum] |
323 | 20x |
ests <- xs / ns |
324 | 20x |
vars <- ests * (1 - ests) / ns |
325 | ||
326 | 20x |
strata_qnorm <- strata_normal_quantile(vars, weights, conf_level) |
327 | ||
328 |
# Iterative setting of weights if they were not set externally |
|
329 | 20x |
weights_new <- if (do_iter) { |
330 | 6x |
update_weights_strat_wilson(vars, strata_qnorm, weights, ns, max_iterations, conf_level)$weights |
331 |
} else { |
|
332 | 14x |
weights |
333 |
} |
|
334 | ||
335 | 20x |
strata_conf_level <- 2 * stats::pnorm(strata_qnorm) - 1 |
336 | ||
337 | 20x |
ci_by_strata <- Map( |
338 | 20x |
function(x, n) { |
339 |
# Classic Wilson's confidence interval |
|
340 | 139x |
suppressWarnings(stats::prop.test(x, n, correct = correct, conf.level = strata_conf_level)$conf.int) |
341 |
}, |
|
342 | 20x |
x = xs, |
343 | 20x |
n = ns |
344 |
) |
|
345 | 20x |
lower_by_strata <- sapply(ci_by_strata, "[", 1L) |
346 | 20x |
upper_by_strata <- sapply(ci_by_strata, "[", 2L) |
347 | ||
348 | 20x |
lower <- sum(weights_new * lower_by_strata) |
349 | 20x |
upper <- sum(weights_new * upper_by_strata) |
350 | ||
351 |
# Return values |
|
352 | 20x |
if (do_iter) { |
353 | 6x |
list( |
354 | 6x |
conf_int = c( |
355 | 6x |
lower = lower, |
356 | 6x |
upper = upper |
357 |
), |
|
358 | 6x |
weights = weights_new |
359 |
) |
|
360 |
} else { |
|
361 | 14x |
list( |
362 | 14x |
conf_int = c( |
363 | 14x |
lower = lower, |
364 | 14x |
upper = upper |
365 |
) |
|
366 |
) |
|
367 |
} |
|
368 |
} |
|
369 | ||
370 |
#' @describeIn h_proportions Calculates the Clopper-Pearson interval by calling [stats::binom.test()]. |
|
371 |
#' Also referred to as the `exact` method. |
|
372 |
#' |
|
373 |
#' @examples |
|
374 |
#' prop_clopper_pearson(rsp, conf_level = .95) |
|
375 |
#' |
|
376 |
#' @export |
|
377 |
prop_clopper_pearson <- function(rsp, |
|
378 |
conf_level) { |
|
379 | 1x |
y <- stats::binom.test( |
380 | 1x |
x = sum(rsp), |
381 | 1x |
n = length(rsp), |
382 | 1x |
conf.level = conf_level |
383 |
) |
|
384 | 1x |
as.numeric(y$conf.int) |
385 |
} |
|
386 | ||
387 |
#' @describeIn h_proportions Calculates the Wald interval by following the usual textbook definition |
|
388 |
#' for a single proportion confidence interval using the normal approximation. |
|
389 |
#' |
|
390 |
#' @param correct (`flag`)\cr apply continuity correction. |
|
391 |
#' |
|
392 |
#' @examples |
|
393 |
#' prop_wald(rsp, conf_level = 0.95) |
|
394 |
#' prop_wald(rsp, conf_level = 0.95, correct = TRUE) |
|
395 |
#' |
|
396 |
#' @export |
|
397 |
prop_wald <- function(rsp, conf_level, correct = FALSE) { |
|
398 | 132x |
n <- length(rsp) |
399 | 132x |
p_hat <- mean(rsp) |
400 | 132x |
z <- stats::qnorm((1 + conf_level) / 2) |
401 | 132x |
q_hat <- 1 - p_hat |
402 | 132x |
correct <- if (correct) 1 / (2 * n) else 0 |
403 | ||
404 | 132x |
err <- z * sqrt(p_hat * q_hat) / sqrt(n) + correct |
405 | 132x |
l_ci <- max(0, p_hat - err) |
406 | 132x |
u_ci <- min(1, p_hat + err) |
407 | ||
408 | 132x |
c(l_ci, u_ci) |
409 |
} |
|
410 | ||
411 |
#' @describeIn h_proportions Calculates the `Agresti-Coull` interval (created by `Alan Agresti` and `Brent Coull`) by |
|
412 |
#' (for 95% CI) adding two successes and two failures to the data and then using the Wald formula to construct a CI. |
|
413 |
#' |
|
414 |
#' @examples |
|
415 |
#' prop_agresti_coull(rsp, conf_level = 0.95) |
|
416 |
#' |
|
417 |
#' @export |
|
418 |
prop_agresti_coull <- function(rsp, conf_level) { |
|
419 | 2x |
n <- length(rsp) |
420 | 2x |
x_sum <- sum(rsp) |
421 | 2x |
z <- stats::qnorm((1 + conf_level) / 2) |
422 | ||
423 |
# Add here both z^2 / 2 successes and failures. |
|
424 | 2x |
x_sum_tilde <- x_sum + z^2 / 2 |
425 | 2x |
n_tilde <- n + z^2 |
426 | ||
427 |
# Then proceed as with the Wald interval. |
|
428 | 2x |
p_tilde <- x_sum_tilde / n_tilde |
429 | 2x |
q_tilde <- 1 - p_tilde |
430 | 2x |
err <- z * sqrt(p_tilde * q_tilde) / sqrt(n_tilde) |
431 | 2x |
l_ci <- max(0, p_tilde - err) |
432 | 2x |
u_ci <- min(1, p_tilde + err) |
433 | ||
434 | 2x |
c(l_ci, u_ci) |
435 |
} |
|
436 | ||
437 |
#' @describeIn h_proportions Calculates the Jeffreys interval, an equal-tailed interval based on the |
|
438 |
#' non-informative Jeffreys prior for a binomial proportion. |
|
439 |
#' |
|
440 |
#' @examples |
|
441 |
#' prop_jeffreys(rsp, conf_level = 0.95) |
|
442 |
#' |
|
443 |
#' @export |
|
444 |
prop_jeffreys <- function(rsp, |
|
445 |
conf_level) { |
|
446 | 4x |
n <- length(rsp) |
447 | 4x |
x_sum <- sum(rsp) |
448 | ||
449 | 4x |
alpha <- 1 - conf_level |
450 | 4x |
l_ci <- ifelse( |
451 | 4x |
x_sum == 0, |
452 | 4x |
0, |
453 | 4x |
stats::qbeta(alpha / 2, x_sum + 0.5, n - x_sum + 0.5) |
454 |
) |
|
455 | ||
456 | 4x |
u_ci <- ifelse( |
457 | 4x |
x_sum == n, |
458 | 4x |
1, |
459 | 4x |
stats::qbeta(1 - alpha / 2, x_sum + 0.5, n - x_sum + 0.5) |
460 |
) |
|
461 | ||
462 | 4x |
c(l_ci, u_ci) |
463 |
} |
|
464 | ||
465 |
#' Description of the Proportion Summary |
|
466 |
#' |
|
467 |
#' @description `r lifecycle::badge("stable")` |
|
468 |
#' |
|
469 |
#' This is a helper function that describes the analysis in [s_proportion()]. |
|
470 |
#' |
|
471 |
#' @inheritParams s_proportion |
|
472 |
#' @param long (`flag`)\cr whether a long or a short (default) description is required. |
|
473 |
#' |
|
474 |
#' @return String describing the analysis. |
|
475 |
#' |
|
476 |
#' @export |
|
477 |
d_proportion <- function(conf_level, |
|
478 |
method, |
|
479 |
long = FALSE) { |
|
480 | 147x |
label <- paste0(conf_level * 100, "% CI") |
481 | ||
482 | ! |
if (long) label <- paste(label, "for Response Rates") |
483 | ||
484 | 147x |
method_part <- switch(method, |
485 | 147x |
"clopper-pearson" = "Clopper-Pearson", |
486 | 147x |
"waldcc" = "Wald, with correction", |
487 | 147x |
"wald" = "Wald, without correction", |
488 | 147x |
"wilson" = "Wilson, without correction", |
489 | 147x |
"strat_wilson" = "Stratified Wilson, without correction", |
490 | 147x |
"wilsonc" = "Wilson, with correction", |
491 | 147x |
"strat_wilsonc" = "Stratified Wilson, with correction", |
492 | 147x |
"agresti-coull" = "Agresti-Coull", |
493 | 147x |
"jeffreys" = "Jeffreys", |
494 | 147x |
stop(paste(method, "does not have a description")) |
495 |
) |
|
496 | ||
497 | 147x |
paste0(label, " (", method_part, ")") |
498 |
} |
|
499 | ||
500 |
#' Helper Function for the Estimation of Stratified Quantiles |
|
501 |
#' |
|
502 |
#' @description `r lifecycle::badge("stable")` |
|
503 |
#' |
|
504 |
#' This function wraps the estimation of stratified percentiles when we assume |
|
505 |
#' the approximation for large numbers. This is necessary only in the case |
|
506 |
#' proportions for each strata are unequal. |
|
507 |
#' |
|
508 |
#' @inheritParams argument_convention |
|
509 |
#' @inheritParams prop_strat_wilson |
|
510 |
#' |
|
511 |
#' @return Stratified quantile. |
|
512 |
#' |
|
513 |
#' @seealso [prop_strat_wilson()] |
|
514 |
#' |
|
515 |
#' @examples |
|
516 |
#' strata_data <- table(data.frame( |
|
517 |
#' "f1" = sample(c(TRUE, FALSE), 100, TRUE), |
|
518 |
#' "f2" = sample(c("x", "y", "z"), 100, TRUE), |
|
519 |
#' stringsAsFactors = TRUE |
|
520 |
#' )) |
|
521 |
#' ns <- colSums(strata_data) |
|
522 |
#' ests <- strata_data["TRUE", ] / ns |
|
523 |
#' vars <- ests * (1 - ests) / ns |
|
524 |
#' weights <- rep(1 / length(ns), length(ns)) |
|
525 |
#' |
|
526 |
#' strata_normal_quantile(vars, weights, 0.95) |
|
527 |
#' |
|
528 |
#' @export |
|
529 |
strata_normal_quantile <- function(vars, weights, conf_level) { |
|
530 | 41x |
summands <- weights^2 * vars |
531 |
# Stratified quantile |
|
532 | 41x |
sqrt(sum(summands)) / sum(sqrt(summands)) * stats::qnorm((1 + conf_level) / 2) |
533 |
} |
|
534 | ||
535 |
#' Helper Function for the Estimation of Weights for `prop_strat_wilson` |
|
536 |
#' |
|
537 |
#' @description `r lifecycle::badge("stable")` |
|
538 |
#' |
|
539 |
#' This function wraps the iteration procedure that allows you to estimate |
|
540 |
#' the weights for each proportional strata. This assumes to minimize the |
|
541 |
#' weighted squared length of the confidence interval. |
|
542 |
#' |
|
543 |
#' @inheritParams prop_strat_wilson |
|
544 |
#' @param vars (`numeric`)\cr normalized proportions for each strata. |
|
545 |
#' @param strata_qnorm (`numeric`)\cr initial estimation with identical weights of the quantiles. |
|
546 |
#' @param initial_weights (`numeric`)\cr initial weights used to calculate `strata_qnorm`. This can |
|
547 |
#' be optimized in the future if we need to estimate better initial weights. |
|
548 |
#' @param n_per_strata (`numeric`)\cr number of elements in each strata. |
|
549 |
#' @param max_iterations (`count`)\cr maximum number of iterations to be tried. Convergence is always checked. |
|
550 |
#' @param tol (`number`)\cr tolerance threshold for convergence. |
|
551 |
#' |
|
552 |
#' @return A `list` of 3 elements: `n_it`, `weights`, and `diff_v`. |
|
553 |
#' |
|
554 |
#' @seealso For references and details see [prop_strat_wilson()]. |
|
555 |
#' |
|
556 |
#' @examples |
|
557 |
#' vs <- c(0.011, 0.013, 0.012, 0.014, 0.017, 0.018) |
|
558 |
#' sq <- 0.674 |
|
559 |
#' ws <- rep(1 / length(vs), length(vs)) |
|
560 |
#' ns <- c(22, 18, 17, 17, 14, 12) |
|
561 |
#' |
|
562 |
#' update_weights_strat_wilson(vs, sq, ws, ns, 100, 0.95, 0.001) |
|
563 |
#' |
|
564 |
#' @export |
|
565 |
update_weights_strat_wilson <- function(vars, |
|
566 |
strata_qnorm, |
|
567 |
initial_weights, |
|
568 |
n_per_strata, |
|
569 |
max_iterations = 50, |
|
570 |
conf_level = 0.95, |
|
571 |
tol = 0.001) { |
|
572 | 8x |
it <- 0 |
573 | 8x |
diff_v <- NULL |
574 | ||
575 | 8x |
while (it < max_iterations) { |
576 | 19x |
it <- it + 1 |
577 | 19x |
weights_new_t <- (1 + strata_qnorm^2 / n_per_strata)^2 |
578 | 19x |
weights_new_b <- (vars + strata_qnorm^2 / (4 * n_per_strata^2)) |
579 | 19x |
weights_new <- weights_new_t / weights_new_b |
580 | 19x |
weights_new <- weights_new / sum(weights_new) |
581 | 19x |
strata_qnorm <- strata_normal_quantile(vars, weights_new, conf_level) |
582 | 19x |
diff_v <- c(diff_v, sum(abs(weights_new - initial_weights))) |
583 | 8x |
if (diff_v[length(diff_v)] < tol) break |
584 | 11x |
initial_weights <- weights_new |
585 |
} |
|
586 | ||
587 | 8x |
if (it == max_iterations) { |
588 | ! |
warning("The heuristic to find weights did not converge with max_iterations = ", max_iterations) |
589 |
} |
|
590 | ||
591 | 8x |
list( |
592 | 8x |
"n_it" = it, |
593 | 8x |
"weights" = weights_new, |
594 | 8x |
"diff_v" = diff_v |
595 |
) |
|
596 |
} |
1 |
#' `rtables` Access Helper Functions |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' These are a couple of functions that help with accessing the data in `rtables` objects. |
|
6 |
#' Currently these work for occurrence tables, which are defined as having a count as the first |
|
7 |
#' element and a fraction as the second element in each cell. |
|
8 |
#' |
|
9 |
#' @seealso [prune_occurrences] for usage of these functions. |
|
10 |
#' |
|
11 |
#' @name rtables_access |
|
12 |
NULL |
|
13 | ||
14 |
#' @describeIn rtables_access Helper function to extract the first values from each content |
|
15 |
#' cell and from specified columns in a `TableRow`. Defaults to all columns. |
|
16 |
#' |
|
17 |
#' @param table_row (`TableRow`)\cr an analysis row in a occurrence table. |
|
18 |
#' @param col_names (`character`)\cr the names of the columns to extract from. |
|
19 |
#' @param col_indices (`integer`)\cr the indices of the columns to extract from. If `col_names` are provided, |
|
20 |
#' then these are inferred from the names of `table_row`. Note that this currently only works well with a single |
|
21 |
#' column split. |
|
22 |
#' |
|
23 |
#' @return |
|
24 |
#' * `h_row_first_values()` returns a `vector` of numeric values. |
|
25 |
#' |
|
26 |
#' @examples |
|
27 |
#' tbl <- basic_table() %>% |
|
28 |
#' split_cols_by("ARM") %>% |
|
29 |
#' split_rows_by("RACE") %>% |
|
30 |
#' analyze("AGE", function(x) { |
|
31 |
#' list( |
|
32 |
#' "mean (sd)" = rcell(c(mean(x), sd(x)), format = "xx.x (xx.x)"), |
|
33 |
#' "n" = length(x), |
|
34 |
#' "frac" = rcell(c(0.1, 0.1), format = "xx (xx)") |
|
35 |
#' ) |
|
36 |
#' }) %>% |
|
37 |
#' build_table(tern_ex_adsl) %>% |
|
38 |
#' prune_table() |
|
39 |
#' tree_row_elem <- collect_leaves(tbl[2, ])[[1]] |
|
40 |
#' result <- max(h_row_first_values(tree_row_elem)) |
|
41 |
#' result |
|
42 |
#' |
|
43 |
#' @export |
|
44 |
h_row_first_values <- function(table_row, |
|
45 |
col_names = NULL, |
|
46 |
col_indices = NULL) { |
|
47 | 727x |
col_indices <- check_names_indices(table_row, col_names, col_indices) |
48 | 727x |
checkmate::assert_integerish(col_indices) |
49 | 727x |
checkmate::assert_subset(col_indices, seq_len(ncol(table_row))) |
50 | ||
51 |
# Main values are extracted |
|
52 | 727x |
row_vals <- row_values(table_row)[col_indices] |
53 | ||
54 |
# Main return |
|
55 | 727x |
vapply(row_vals, function(rv) { |
56 | 2066x |
if (is.null(rv)) { |
57 | 727x |
NA_real_ |
58 |
} else { |
|
59 | 2063x |
rv[1L] |
60 |
} |
|
61 | 727x |
}, FUN.VALUE = numeric(1)) |
62 |
} |
|
63 | ||
64 |
#' @describeIn rtables_access Helper function that extracts row values and checks if they are |
|
65 |
#' convertible to integers (`integerish` values). |
|
66 |
#' |
|
67 |
#' @return |
|
68 |
#' * `h_row_counts()` returns a `vector` of numeric values. |
|
69 |
#' |
|
70 |
#' @examples |
|
71 |
#' # Row counts (integer values) |
|
72 |
#' # h_row_counts(tree_row_elem) # Fails because there are no integers |
|
73 |
#' # Using values with integers |
|
74 |
#' tree_row_elem <- collect_leaves(tbl[3, ])[[1]] |
|
75 |
#' result <- h_row_counts(tree_row_elem) |
|
76 |
#' # result |
|
77 |
#' |
|
78 |
#' @export |
|
79 |
h_row_counts <- function(table_row, |
|
80 |
col_names = NULL, |
|
81 |
col_indices = NULL) { |
|
82 | 727x |
counts <- h_row_first_values(table_row, col_names, col_indices) |
83 | 727x |
checkmate::assert_integerish(counts) |
84 | 727x |
counts |
85 |
} |
|
86 | ||
87 |
#' @describeIn rtables_access helper function to extract fractions from specified columns in a `TableRow`. |
|
88 |
#' More specifically it extracts the second values from each content cell and checks it is a fraction. |
|
89 |
#' |
|
90 |
#' @return |
|
91 |
#' * `h_row_fractions()` returns a `vector` of proportions. |
|
92 |
#' |
|
93 |
#' @examples |
|
94 |
#' # Row fractions |
|
95 |
#' tree_row_elem <- collect_leaves(tbl[4, ])[[1]] |
|
96 |
#' h_row_fractions(tree_row_elem) |
|
97 |
#' |
|
98 |
#' @export |
|
99 |
h_row_fractions <- function(table_row, |
|
100 |
col_names = NULL, |
|
101 |
col_indices = NULL) { |
|
102 | 243x |
col_indices <- check_names_indices(table_row, col_names, col_indices) |
103 | 243x |
row_vals <- row_values(table_row)[col_indices] |
104 | 243x |
fractions <- sapply(row_vals, "[", 2L) |
105 | 243x |
checkmate::assert_numeric(fractions, lower = 0, upper = 1) |
106 | 243x |
fractions |
107 |
} |
|
108 | ||
109 |
#' @describeIn rtables_access Helper function to extract column counts from specified columns in a table. |
|
110 |
#' |
|
111 |
#' @param table (`VTableNodeInfo`)\cr an occurrence table or row. |
|
112 |
#' |
|
113 |
#' @return |
|
114 |
#' * `h_col_counts()` returns a `vector` of column counts. |
|
115 |
#' |
|
116 |
#' @export |
|
117 |
h_col_counts <- function(table, |
|
118 |
col_names = NULL, |
|
119 |
col_indices = NULL) { |
|
120 | 304x |
col_indices <- check_names_indices(table, col_names, col_indices) |
121 | 304x |
counts <- col_counts(table)[col_indices] |
122 | 304x |
stats::setNames(counts, col_names) |
123 |
} |
|
124 | ||
125 |
#' @describeIn rtables_access Helper function to get first row of content table of current table. |
|
126 |
#' |
|
127 |
#' @return |
|
128 |
#' * `h_content_first_row()` returns a row from an `rtables` table. |
|
129 |
#' |
|
130 |
#' @export |
|
131 |
h_content_first_row <- function(table) { |
|
132 | 27x |
ct <- content_table(table) |
133 | 27x |
tree_children(ct)[[1]] |
134 |
} |
|
135 | ||
136 |
#' @describeIn rtables_access Helper function which says whether current table is a leaf in the tree. |
|
137 |
#' |
|
138 |
#' @return |
|
139 |
#' * `is_leaf_table()` returns a `logical` value indicating whether current table is a leaf. |
|
140 |
#' |
|
141 |
#' @keywords internal |
|
142 |
is_leaf_table <- function(table) { |
|
143 | 168x |
children <- tree_children(table) |
144 | 168x |
child_classes <- unique(sapply(children, class)) |
145 | 168x |
identical(child_classes, "ElementaryTable") |
146 |
} |
|
147 | ||
148 |
#' @describeIn rtables_access Internal helper function that tests standard inputs for column indices. |
|
149 |
#' |
|
150 |
#' @return |
|
151 |
#' * `check_names_indices` returns column indices. |
|
152 |
#' |
|
153 |
#' @keywords internal |
|
154 |
check_names_indices <- function(table_row, |
|
155 |
col_names = NULL, |
|
156 |
col_indices = NULL) { |
|
157 | 1274x |
if (!is.null(col_names)) { |
158 | 1231x |
if (!is.null(col_indices)) { |
159 | ! |
stop( |
160 | ! |
"Inserted both col_names and col_indices when selecting row values. ", |
161 | ! |
"Please choose one." |
162 |
) |
|
163 |
} |
|
164 | 1231x |
col_indices <- h_col_indices(table_row, col_names) |
165 |
} |
|
166 | 1274x |
if (is.null(col_indices)) { |
167 | 37x |
ll <- ifelse(is.null(ncol(table_row)), length(table_row), ncol(table_row)) |
168 | 37x |
col_indices <- seq_len(ll) |
169 |
} |
|
170 | ||
171 | 1274x |
return(col_indices) |
172 |
} |
1 |
#' Control Function for Subgroup Treatment Effect Pattern (STEP) Calculations |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' This is an auxiliary function for controlling arguments for STEP calculations. |
|
6 |
#' |
|
7 |
#' @param biomarker (`numeric` or `NULL`)\cr optional provision of the numeric biomarker variable, which |
|
8 |
#' could be used to infer `bandwidth`, see below. |
|
9 |
#' @param use_percentile (`flag`)\cr if `TRUE`, the running windows are created according to |
|
10 |
#' quantiles rather than actual values, i.e. the bandwidth refers to the percentage of data |
|
11 |
#' covered in each window. Suggest `TRUE` if the biomarker variable is not uniformly |
|
12 |
#' distributed. |
|
13 |
#' @param bandwidth (`number` or `NULL`)\cr indicating the bandwidth of each window. |
|
14 |
#' Depending on the argument `use_percentile`, it can be either the length of actual-value |
|
15 |
#' windows on the real biomarker scale, or percentage windows. |
|
16 |
#' If `use_percentile = TRUE`, it should be a number between 0 and 1. |
|
17 |
#' If `NULL`, treat the bandwidth to be infinity, which means only one global model will be fitted. |
|
18 |
#' By default, `0.25` is used for percentage windows and one quarter of the range of the `biomarker` |
|
19 |
#' variable for actual-value windows. |
|
20 |
#' @param degree (`count`)\cr the degree of polynomial function of the biomarker as an interaction term |
|
21 |
#' with the treatment arm fitted at each window. If 0 (default), then the biomarker variable |
|
22 |
#' is not included in the model fitted in each biomarker window. |
|
23 |
#' @param num_points (`count`)\cr the number of points at which the hazard ratios are estimated. The |
|
24 |
#' smallest number is 2. |
|
25 |
#' |
|
26 |
#' @return A list of components with the same names as the arguments, except `biomarker` which is |
|
27 |
#' just used to calculate the `bandwidth` in case that actual biomarker windows are requested. |
|
28 |
#' |
|
29 |
#' @examples |
|
30 |
#' # Provide biomarker values and request actual values to be used, |
|
31 |
#' # so that bandwidth is chosen from range. |
|
32 |
#' control_step(biomarker = 1:10, use_percentile = FALSE) |
|
33 |
#' |
|
34 |
#' # Use a global model with quadratic biomarker interaction term. |
|
35 |
#' control_step(bandwidth = NULL, degree = 2) |
|
36 |
#' |
|
37 |
#' # Reduce number of points to be used. |
|
38 |
#' control_step(num_points = 10) |
|
39 |
#' |
|
40 |
#' @export |
|
41 |
control_step <- function(biomarker = NULL, |
|
42 |
use_percentile = TRUE, |
|
43 |
bandwidth, |
|
44 |
degree = 0L, |
|
45 |
num_points = 39L) { |
|
46 | 31x |
checkmate::assert_numeric(biomarker, null.ok = TRUE) |
47 | 30x |
checkmate::assert_flag(use_percentile) |
48 | 30x |
checkmate::assert_int(num_points, lower = 2) |
49 | 29x |
checkmate::assert_count(degree) |
50 | ||
51 | 29x |
if (missing(bandwidth)) { |
52 |
# Infer bandwidth |
|
53 | 21x |
bandwidth <- if (use_percentile) { |
54 | 18x |
0.25 |
55 | 21x |
} else if (!is.null(biomarker)) { |
56 | 3x |
diff(range(biomarker, na.rm = TRUE)) / 4 |
57 |
} else { |
|
58 | ! |
NULL |
59 |
} |
|
60 |
} else { |
|
61 |
# Check bandwidth |
|
62 | 8x |
if (!is.null(bandwidth)) { |
63 | 5x |
if (use_percentile) { |
64 | 4x |
assert_proportion_value(bandwidth) |
65 |
} else { |
|
66 | 1x |
checkmate::assert_scalar(bandwidth) |
67 | 1x |
checkmate::assert_true(bandwidth > 0) |
68 |
} |
|
69 |
} |
|
70 |
} |
|
71 | 28x |
list( |
72 | 28x |
use_percentile = use_percentile, |
73 | 28x |
bandwidth = bandwidth, |
74 | 28x |
degree = as.integer(degree), |
75 | 28x |
num_points = as.integer(num_points) |
76 |
) |
|
77 |
} |
1 |
#' Confidence Interval for Mean |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Convenient function for calculating the mean confidence interval. It calculates the arithmetic as well as the |
|
6 |
#' geometric mean. It can be used as a `ggplot` helper function for plotting. |
|
7 |
#' |
|
8 |
#' @inheritParams argument_convention |
|
9 |
#' @param n_min (`number`)\cr a minimum number of non-missing `x` to estimate the confidence interval for mean. |
|
10 |
#' @param gg_helper (`logical`)\cr `TRUE` when output should be aligned for the use with `ggplot`. |
|
11 |
#' @param geom_mean (`logical`)\cr `TRUE` when the geometric mean should be calculated. |
|
12 |
#' |
|
13 |
#' @return A named `vector` of values `mean_ci_lwr` and `mean_ci_upr`. |
|
14 |
#' |
|
15 |
#' @examples |
|
16 |
#' stat_mean_ci(sample(10), gg_helper = FALSE) |
|
17 |
#' |
|
18 |
#' p <- ggplot2::ggplot(mtcars, ggplot2::aes(cyl, mpg)) + |
|
19 |
#' ggplot2::geom_point() |
|
20 |
#' |
|
21 |
#' p + ggplot2::stat_summary( |
|
22 |
#' fun.data = stat_mean_ci, |
|
23 |
#' geom = "errorbar" |
|
24 |
#' ) |
|
25 |
#' |
|
26 |
#' p + ggplot2::stat_summary( |
|
27 |
#' fun.data = stat_mean_ci, |
|
28 |
#' fun.args = list(conf_level = 0.5), |
|
29 |
#' geom = "errorbar" |
|
30 |
#' ) |
|
31 |
#' |
|
32 |
#' p + ggplot2::stat_summary( |
|
33 |
#' fun.data = stat_mean_ci, |
|
34 |
#' fun.args = list(conf_level = 0.5, geom_mean = TRUE), |
|
35 |
#' geom = "errorbar" |
|
36 |
#' ) |
|
37 |
#' |
|
38 |
#' @export |
|
39 |
stat_mean_ci <- function(x, |
|
40 |
conf_level = 0.95, |
|
41 |
na.rm = TRUE, # nolint |
|
42 |
n_min = 2, |
|
43 |
gg_helper = TRUE, |
|
44 |
geom_mean = FALSE) { |
|
45 | 720x |
if (na.rm) { |
46 | 2x |
x <- stats::na.omit(x) |
47 |
} |
|
48 | 720x |
n <- length(x) |
49 | ||
50 | 720x |
if (!geom_mean) { |
51 | 361x |
m <- mean(x) |
52 |
} else { |
|
53 | 359x |
negative_values_exist <- any(is.na(x[!is.na(x)]) <- x[!is.na(x)] <= 0) |
54 | 359x |
if (negative_values_exist) { |
55 | 22x |
m <- NA_real_ |
56 |
} else { |
|
57 | 337x |
x <- log(x) |
58 | 337x |
m <- mean(x) |
59 |
} |
|
60 |
} |
|
61 | ||
62 | 720x |
if (n < n_min || is.na(m)) { |
63 | 122x |
ci <- c(mean_ci_lwr = NA_real_, mean_ci_upr = NA_real_) |
64 |
} else { |
|
65 | 598x |
hci <- stats::qt((1 + conf_level) / 2, df = n - 1) * stats::sd(x) / sqrt(n) |
66 | 598x |
ci <- c(mean_ci_lwr = m - hci, mean_ci_upr = m + hci) |
67 | 598x |
if (geom_mean) { |
68 | 291x |
ci <- exp(ci) |
69 |
} |
|
70 |
} |
|
71 | ||
72 | 720x |
if (gg_helper) { |
73 | ! |
m <- ifelse(is.na(m), NA_real_, m) |
74 | ! |
ci <- data.frame(y = ifelse(geom_mean, exp(m), m), ymin = ci[[1]], ymax = ci[[2]]) |
75 |
} |
|
76 | ||
77 | 720x |
return(ci) |
78 |
} |
|
79 | ||
80 |
#' Confidence Interval for Median |
|
81 |
#' |
|
82 |
#' @description `r lifecycle::badge("stable")` |
|
83 |
#' |
|
84 |
#' Convenient function for calculating the median confidence interval. It can be used as a `ggplot` helper |
|
85 |
#' function for plotting. |
|
86 |
#' |
|
87 |
#' @inheritParams argument_convention |
|
88 |
#' @param gg_helper (`logical`)\cr `TRUE` when output should be aligned for the use with `ggplot`. |
|
89 |
#' |
|
90 |
#' @details The function was adapted from `DescTools/versions/0.99.35/source` |
|
91 |
#' |
|
92 |
#' @return A named `vector` of values `median_ci_lwr` and `median_ci_upr`. |
|
93 |
#' |
|
94 |
#' @examples |
|
95 |
#' stat_median_ci(sample(10), gg_helper = FALSE) |
|
96 |
#' |
|
97 |
#' p <- ggplot2::ggplot(mtcars, ggplot2::aes(cyl, mpg)) + |
|
98 |
#' ggplot2::geom_point() |
|
99 |
#' p + ggplot2::stat_summary( |
|
100 |
#' fun.data = stat_median_ci, |
|
101 |
#' geom = "errorbar" |
|
102 |
#' ) |
|
103 |
#' |
|
104 |
#' @export |
|
105 |
stat_median_ci <- function(x, |
|
106 |
conf_level = 0.95, |
|
107 |
na.rm = TRUE, # nolint |
|
108 |
gg_helper = TRUE) { |
|
109 | 362x |
x <- unname(x) |
110 | 362x |
if (na.rm) { |
111 | 3x |
x <- x[!is.na(x)] |
112 |
} |
|
113 | 362x |
n <- length(x) |
114 | 362x |
med <- stats::median(x) |
115 | ||
116 | 362x |
k <- stats::qbinom(p = (1 - conf_level) / 2, size = n, prob = 0.5, lower.tail = TRUE) |
117 | ||
118 |
# k == 0 - for small samples (e.g. n <= 5) ci can be outside the observed range |
|
119 | 362x |
if (k == 0 || is.na(med)) { |
120 | 98x |
ci <- c(median_ci_lwr = NA_real_, median_ci_upr = NA_real_) |
121 | 98x |
empir_conf_level <- NA_real_ |
122 |
} else { |
|
123 | 264x |
x_sort <- sort(x) |
124 | 264x |
ci <- c(median_ci_lwr = x_sort[k], median_ci_upr = x_sort[n - k + 1]) |
125 | 264x |
empir_conf_level <- 1 - 2 * stats::pbinom(k - 1, size = n, prob = 0.5) |
126 |
} |
|
127 | ||
128 | 362x |
if (gg_helper) { |
129 | ! |
ci <- data.frame(y = med, ymin = ci[[1]], ymax = ci[[2]]) |
130 |
} |
|
131 | ||
132 | 362x |
attr(ci, "conf_level") <- empir_conf_level |
133 | ||
134 | 362x |
return(ci) |
135 |
} |
|
136 | ||
137 |
#' p-Value of the Mean |
|
138 |
#' |
|
139 |
#' @description `r lifecycle::badge("stable")` |
|
140 |
#' |
|
141 |
#' Convenient function for calculating the two-sided p-value of the mean. |
|
142 |
#' |
|
143 |
#' @inheritParams argument_convention |
|
144 |
#' @param n_min (`numeric`)\cr a minimum number of non-missing `x` to estimate the p-value of the mean. |
|
145 |
#' @param test_mean (`numeric`)\cr mean value to test under the null hypothesis. |
|
146 |
#' |
|
147 |
#' @return A p-value. |
|
148 |
#' |
|
149 |
#' @examples |
|
150 |
#' stat_mean_pval(sample(10)) |
|
151 |
#' |
|
152 |
#' stat_mean_pval(rnorm(10), test_mean = 0.5) |
|
153 |
#' |
|
154 |
#' @export |
|
155 |
stat_mean_pval <- function(x, |
|
156 |
na.rm = TRUE, # nolint |
|
157 |
n_min = 2, |
|
158 |
test_mean = 0) { |
|
159 | 363x |
if (na.rm) { |
160 | 4x |
x <- stats::na.omit(x) |
161 |
} |
|
162 | 363x |
n <- length(x) |
163 | ||
164 | 363x |
x_mean <- mean(x) |
165 | 363x |
x_sd <- stats::sd(x) |
166 | ||
167 | 363x |
if (n < n_min) { |
168 | 53x |
pv <- c(p_value = NA_real_) |
169 |
} else { |
|
170 | 310x |
x_se <- stats::sd(x) / sqrt(n) |
171 | 310x |
ttest <- (x_mean - test_mean) / x_se |
172 | 310x |
pv <- c(p_value = 2 * stats::pt(-abs(ttest), df = n - 1)) |
173 |
} |
|
174 | ||
175 | 363x |
return(pv) |
176 |
} |
|
177 | ||
178 |
#' Proportion Difference and Confidence Interval |
|
179 |
#' |
|
180 |
#' @description `r lifecycle::badge("stable")` |
|
181 |
#' |
|
182 |
#' Function for calculating the proportion (or risk) difference and confidence interval between arm |
|
183 |
#' X (reference group) and arm Y. Risk difference is calculated by subtracting cumulative incidence |
|
184 |
#' in arm Y from cumulative incidence in arm X. |
|
185 |
#' |
|
186 |
#' @inheritParams argument_convention |
|
187 |
#' @param x (`list` of `integer`)\cr list of number of occurrences in arm X (reference group). |
|
188 |
#' @param y (`list` of `integer`)\cr list of number of occurrences in arm Y. Must be of equal length to `x`. |
|
189 |
#' @param N_x (`numeric`)\cr total number of records in arm X. |
|
190 |
#' @param N_y (`numeric`)\cr total number of records in arm Y. |
|
191 |
#' @param list_names (`character`)\cr names of each variable/level corresponding to pair of proportions in |
|
192 |
#' `x` and `y`. Must be of equal length to `x` and `y`. |
|
193 |
#' @param pct (`flag`)\cr whether output should be returned as percentages. Defaults to `TRUE`. |
|
194 |
#' |
|
195 |
#' @return List of proportion differences and CIs corresponding to each pair of number of occurrences in `x` and |
|
196 |
#' `y`. Each list element consists of 3 statistics: proportion difference, CI lower bound, and CI upper bound. |
|
197 |
#' |
|
198 |
#' @seealso Split function [add_riskdiff()] which, when used as `split_fun` within [rtables::split_cols_by()] |
|
199 |
#' with `riskdiff` argument is set to `TRUE` in subsequent analyze functions, adds a column containing |
|
200 |
#' proportion (risk) difference to an `rtables` layout. |
|
201 |
#' |
|
202 |
#' @examples |
|
203 |
#' stat_propdiff_ci( |
|
204 |
#' x = list(0.375), y = list(0.01), N_x = 5, N_y = 5, list_names = "x", conf_level = 0.9 |
|
205 |
#' ) |
|
206 |
#' |
|
207 |
#' stat_propdiff_ci( |
|
208 |
#' x = list(0.5, 0.75, 1), y = list(0.25, 0.05, 0.5), N_x = 10, N_y = 20, pct = FALSE |
|
209 |
#' ) |
|
210 |
#' |
|
211 |
#' @export |
|
212 |
stat_propdiff_ci <- function(x, |
|
213 |
y, |
|
214 |
N_x, # nolint |
|
215 |
N_y, # nolint |
|
216 |
list_names = NULL, |
|
217 |
conf_level = 0.95, |
|
218 |
pct = TRUE) { |
|
219 | 13x |
checkmate::assert_list(x, types = "numeric") |
220 | 13x |
checkmate::assert_list(y, types = "numeric", len = length(x)) |
221 | 13x |
checkmate::assert_character(list_names, len = length(x), null.ok = TRUE) |
222 | 13x |
rd_list <- lapply(seq_along(x), function(i) { |
223 | 31x |
p_x <- x[[i]] / N_x |
224 | 31x |
p_y <- y[[i]] / N_y |
225 | 31x |
rd_ci <- p_x - p_y + c(-1, 1) * stats::qnorm((1 + conf_level) / 2) * |
226 | 31x |
sqrt(p_x * (1 - p_x) / N_x + p_y * (1 - p_y) / N_y) |
227 | 31x |
c(p_x - p_y, rd_ci) * ifelse(pct, 100, 1) |
228 |
}) |
|
229 | 13x |
names(rd_list) <- list_names |
230 | 13x |
rd_list |
231 |
} |
1 |
#' Confidence Intervals for a Difference of Binomials |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("experimental")` |
|
4 |
#' |
|
5 |
#' Several confidence intervals for the difference between proportions. |
|
6 |
#' |
|
7 |
#' @name desctools_binom |
|
8 |
NULL |
|
9 | ||
10 |
#' Recycle List of Parameters |
|
11 |
#' |
|
12 |
#' This function recycles all supplied elements to the maximal dimension. |
|
13 |
#' |
|
14 |
#' @param ... (`any`)\cr Elements to recycle. |
|
15 |
#' |
|
16 |
#' @return A `list`. |
|
17 |
#' |
|
18 |
#' @keywords internal |
|
19 |
#' @noRd |
|
20 |
h_recycle <- function(...) { |
|
21 | 64x |
lst <- list(...) |
22 | 64x |
maxdim <- max(lengths(lst)) |
23 | 64x |
res <- lapply(lst, rep, length.out = maxdim) |
24 | 64x |
attr(res, "maxdim") <- maxdim |
25 | 64x |
return(res) |
26 |
} |
|
27 | ||
28 |
#' @describeIn desctools_binom Several confidence intervals for the difference between proportions. |
|
29 |
#' |
|
30 |
#' @return A `matrix` of 3 values: |
|
31 |
#' * `est`: estimate of proportion difference. |
|
32 |
#' * `lwr.ci`: estimate of lower end of the confidence interval. |
|
33 |
#' * `upr.ci`: estimate of upper end of the confidence interval. |
|
34 |
#' |
|
35 |
#' @keywords internal |
|
36 |
desctools_binom <- function(x1, |
|
37 |
n1, |
|
38 |
x2, |
|
39 |
n2, |
|
40 |
conf.level = 0.95, # nolint |
|
41 |
sides = c("two.sided", "left", "right"), |
|
42 |
method = c( |
|
43 |
"ac", "wald", "waldcc", "score", "scorecc", "mn", "mee", "blj", "ha", "hal", "jp" |
|
44 |
)) { |
|
45 | 20x |
if (missing(sides)) { |
46 | 20x |
sides <- match.arg(sides) |
47 |
} |
|
48 | 20x |
if (missing(method)) { |
49 | 1x |
method <- match.arg(method) |
50 |
} |
|
51 | 20x |
iBinomDiffCI <- function(x1, n1, x2, n2, conf.level, sides, method) { # nolint |
52 | 20x |
if (sides != "two.sided") { |
53 | ! |
conf.level <- 1 - 2 * (1 - conf.level) # nolint |
54 |
} |
|
55 | 20x |
alpha <- 1 - conf.level |
56 | 20x |
kappa <- stats::qnorm(1 - alpha / 2) |
57 | 20x |
p1_hat <- x1 / n1 |
58 | 20x |
p2_hat <- x2 / n2 |
59 | 20x |
est <- p1_hat - p2_hat |
60 | 20x |
switch(method, |
61 | 20x |
wald = { |
62 | 2x |
vd <- p1_hat * (1 - p1_hat) / n1 + p2_hat * (1 - p2_hat) / n2 |
63 | 2x |
term2 <- kappa * sqrt(vd) |
64 | 2x |
ci_lwr <- max(-1, est - term2) |
65 | 2x |
ci_upr <- min(1, est + term2) |
66 |
}, |
|
67 | 20x |
waldcc = { |
68 | 4x |
vd <- p1_hat * (1 - p1_hat) / n1 + p2_hat * (1 - p2_hat) / n2 |
69 | 4x |
term2 <- kappa * sqrt(vd) |
70 | 4x |
term2 <- term2 + 0.5 * (1 / n1 + 1 / n2) |
71 | 4x |
ci_lwr <- max(-1, est - term2) |
72 | 4x |
ci_upr <- min(1, est + term2) |
73 |
}, |
|
74 | 20x |
ac = { |
75 | 2x |
n1 <- n1 + 2 |
76 | 2x |
n2 <- n2 + 2 |
77 | 2x |
x1 <- x1 + 1 |
78 | 2x |
x2 <- x2 + 1 |
79 | 2x |
p1_hat <- x1 / n1 |
80 | 2x |
p2_hat <- x2 / n2 |
81 | 2x |
est1 <- p1_hat - p2_hat |
82 | 2x |
vd <- p1_hat * (1 - p1_hat) / n1 + p2_hat * (1 - p2_hat) / n2 |
83 | 2x |
term2 <- kappa * sqrt(vd) |
84 | 2x |
ci_lwr <- max(-1, est1 - term2) |
85 | 2x |
ci_upr <- min(1, est1 + term2) |
86 |
}, |
|
87 | 20x |
exact = { |
88 | ! |
ci_lwr <- NA |
89 | ! |
ci_upr <- NA |
90 |
}, |
|
91 | 20x |
score = { |
92 | 2x |
w1 <- desctools_binomci( |
93 | 2x |
x = x1, n = n1, conf.level = conf.level, |
94 | 2x |
method = "wilson" |
95 |
) |
|
96 | 2x |
w2 <- desctools_binomci( |
97 | 2x |
x = x2, n = n2, conf.level = conf.level, |
98 | 2x |
method = "wilson" |
99 |
) |
|
100 | 2x |
l1 <- w1[2] |
101 | 2x |
u1 <- w1[3] |
102 | 2x |
l2 <- w2[2] |
103 | 2x |
u2 <- w2[3] |
104 | 2x |
ci_lwr <- est - kappa * sqrt(l1 * (1 - l1) / n1 + u2 * (1 - u2) / n2) |
105 | 2x |
ci_upr <- est + kappa * sqrt(u1 * (1 - u1) / n1 + l2 * (1 - l2) / n2) |
106 |
}, |
|
107 | 20x |
scorecc = { |
108 | 1x |
w1 <- desctools_binomci( |
109 | 1x |
x = x1, n = n1, conf.level = conf.level, |
110 | 1x |
method = "wilsoncc" |
111 |
) |
|
112 | 1x |
w2 <- desctools_binomci( |
113 | 1x |
x = x2, n = n2, conf.level = conf.level, |
114 | 1x |
method = "wilsoncc" |
115 |
) |
|
116 | 1x |
l1 <- w1[2] |
117 | 1x |
u1 <- w1[3] |
118 | 1x |
l2 <- w2[2] |
119 | 1x |
u2 <- w2[3] |
120 | 1x |
ci_lwr <- max(-1, est - sqrt((p1_hat - l1)^2 + (u2 - p2_hat)^2)) |
121 | 1x |
ci_upr <- min(1, est + sqrt((u1 - p1_hat)^2 + (p2_hat - l2)^2)) |
122 |
}, |
|
123 | 20x |
mee = { |
124 | 1x |
.score <- function(p1, n1, p2, n2, dif) { |
125 | ! |
if (dif > 1) dif <- 1 |
126 | ! |
if (dif < -1) dif <- -1 |
127 | 24x |
diff <- p1 - p2 - dif |
128 | 24x |
if (abs(diff) == 0) { |
129 | ! |
res <- 0 |
130 |
} else { |
|
131 | 24x |
t <- n2 / n1 |
132 | 24x |
a <- 1 + t |
133 | 24x |
b <- -(1 + t + p1 + t * p2 + dif * (t + 2)) |
134 | 24x |
c <- dif * dif + dif * (2 * p1 + t + 1) + p1 + t * p2 |
135 | 24x |
d <- -p1 * dif * (1 + dif) |
136 | 24x |
v <- (b / a / 3)^3 - b * c / (6 * a * a) + d / a / 2 |
137 | 24x |
if (abs(v) < .Machine$double.eps) v <- 0 |
138 | 24x |
s <- sqrt((b / a / 3)^2 - c / a / 3) |
139 | 24x |
u <- ifelse(v > 0, 1, -1) * s |
140 | 24x |
w <- (3.141592654 + acos(v / u^3)) / 3 |
141 | 24x |
p1d <- 2 * u * cos(w) - b / a / 3 |
142 | 24x |
p2d <- p1d - dif |
143 | 24x |
n <- n1 + n2 |
144 | 24x |
res <- (p1d * (1 - p1d) / n1 + p2d * (1 - p2d) / n2) |
145 |
} |
|
146 | 24x |
return(sqrt(res)) |
147 |
} |
|
148 | 1x |
pval <- function(delta) { |
149 | 24x |
z <- (est - delta) / .score(p1_hat, n1, p2_hat, n2, delta) |
150 | 24x |
2 * min(stats::pnorm(z), 1 - stats::pnorm(z)) |
151 |
} |
|
152 | 1x |
ci_lwr <- max(-1, stats::uniroot(function(delta) { |
153 | 12x |
pval(delta) - alpha |
154 | 1x |
}, interval = c(-1 + 1e-06, est - 1e-06))$root) |
155 | 1x |
ci_upr <- min(1, stats::uniroot(function(delta) { |
156 | 12x |
pval(delta) - alpha |
157 | 1x |
}, interval = c(est + 1e-06, 1 - 1e-06))$root) |
158 |
}, |
|
159 | 20x |
blj = { |
160 | 1x |
p1_dash <- (x1 + 0.5) / (n1 + 1) |
161 | 1x |
p2_dash <- (x2 + 0.5) / (n2 + 1) |
162 | 1x |
vd <- p1_dash * (1 - p1_dash) / n1 + p2_dash * (1 - p2_dash) / n2 |
163 | 1x |
term2 <- kappa * sqrt(vd) |
164 | 1x |
est_dash <- p1_dash - p2_dash |
165 | 1x |
ci_lwr <- max(-1, est_dash - term2) |
166 | 1x |
ci_upr <- min(1, est_dash + term2) |
167 |
}, |
|
168 | 20x |
ha = { |
169 | 4x |
term2 <- 1 / |
170 | 4x |
(2 * min(n1, n2)) + kappa * sqrt(p1_hat * (1 - p1_hat) / (n1 - 1) + p2_hat * (1 - p2_hat) / (n2 - 1)) |
171 | 4x |
ci_lwr <- max(-1, est - term2) |
172 | 4x |
ci_upr <- min(1, est + term2) |
173 |
}, |
|
174 | 20x |
mn = { |
175 | 1x |
.conf <- function(x1, n1, x2, n2, z, lower = FALSE) { |
176 | 2x |
p1 <- x1 / n1 |
177 | 2x |
p2 <- x2 / n2 |
178 | 2x |
p_hat <- p1 - p2 |
179 | 2x |
dp <- 1 + ifelse(lower, 1, -1) * p_hat |
180 | 2x |
i <- 1 |
181 | 2x |
while (i <= 50) { |
182 | 46x |
dp <- 0.5 * dp |
183 | 46x |
y <- p_hat + ifelse(lower, -1, 1) * dp |
184 | 46x |
score <- .score(p1, n1, p2, n2, y) |
185 | 46x |
if (score < z) { |
186 | 20x |
p_hat <- y |
187 |
} |
|
188 | 46x |
if ((dp < 1e-07) || (abs(z - score) < 1e-06)) { |
189 | 2x |
(break)() |
190 |
} else { |
|
191 | 44x |
i <- i + 1 |
192 |
} |
|
193 |
} |
|
194 | 2x |
return(y) |
195 |
} |
|
196 | 1x |
.score <- function(p1, n1, p2, n2, dif) { |
197 | 46x |
diff <- p1 - p2 - dif |
198 | 46x |
if (abs(diff) == 0) { |
199 | ! |
res <- 0 |
200 |
} else { |
|
201 | 46x |
t <- n2 / n1 |
202 | 46x |
a <- 1 + t |
203 | 46x |
b <- -(1 + t + p1 + t * p2 + dif * (t + 2)) |
204 | 46x |
c <- dif * dif + dif * (2 * p1 + t + 1) + p1 + t * p2 |
205 | 46x |
d <- -p1 * dif * (1 + dif) |
206 | 46x |
v <- (b / a / 3)^3 - b * c / (6 * a * a) + d / a / 2 |
207 | 46x |
s <- sqrt((b / a / 3)^2 - c / a / 3) |
208 | 46x |
u <- ifelse(v > 0, 1, -1) * s |
209 | 46x |
w <- (3.141592654 + acos(v / u^3)) / 3 |
210 | 46x |
p1d <- 2 * u * cos(w) - b / a / 3 |
211 | 46x |
p2d <- p1d - dif |
212 | 46x |
n <- n1 + n2 |
213 | 46x |
var <- (p1d * (1 - p1d) / n1 + p2d * (1 - p2d) / n2) * n / (n - 1) |
214 | 46x |
res <- diff^2 / var |
215 |
} |
|
216 | 46x |
return(res) |
217 |
} |
|
218 | 1x |
z <- stats::qchisq(conf.level, 1) |
219 | 1x |
ci_lwr <- max(-1, .conf(x1, n1, x2, n2, z, TRUE)) |
220 | 1x |
ci_upr <- min(1, .conf(x1, n1, x2, n2, z, FALSE)) |
221 |
}, |
|
222 | 20x |
beal = { |
223 | ! |
a <- p1_hat + p2_hat |
224 | ! |
b <- p1_hat - p2_hat |
225 | ! |
u <- ((1 / n1) + (1 / n2)) / 4 |
226 | ! |
v <- ((1 / n1) - (1 / n2)) / 4 |
227 | ! |
V <- u * ((2 - a) * a - b^2) + 2 * v * (1 - a) * b # nolint |
228 | ! |
z <- stats::qchisq(p = 1 - alpha / 2, df = 1) |
229 | ! |
A <- sqrt(z * (V + z * u^2 * (2 - a) * a + z * v^2 * (1 - a)^2)) # nolint |
230 | ! |
B <- (b + z * v * (1 - a)) / (1 + z * u) # nolint |
231 | ! |
ci_lwr <- max(-1, B - A / (1 + z * u)) |
232 | ! |
ci_upr <- min(1, B + A / (1 + z * u)) |
233 |
}, |
|
234 | 20x |
hal = { |
235 | 1x |
psi <- (p1_hat + p2_hat) / 2 |
236 | 1x |
u <- (1 / n1 + 1 / n2) / 4 |
237 | 1x |
v <- (1 / n1 - 1 / n2) / 4 |
238 | 1x |
z <- kappa |
239 | 1x |
theta <- ((p1_hat - p2_hat) + z^2 * v * (1 - 2 * psi)) / (1 + z^2 * u) |
240 | 1x |
w <- z / (1 + z^2 * u) * sqrt(u * (4 * psi * (1 - psi) - (p1_hat - p2_hat)^2) + 2 * v * (1 - 2 * psi) * |
241 | 1x |
(p1_hat - p2_hat) + 4 * z^2 * u^2 * (1 - psi) * psi + z^2 * v^2 * (1 - 2 * psi)^2) # nolint |
242 | 1x |
c(theta + w, theta - w) |
243 | 1x |
ci_lwr <- max(-1, theta - w) |
244 | 1x |
ci_upr <- min(1, theta + w) |
245 |
}, |
|
246 | 20x |
jp = { |
247 | 1x |
psi <- 0.5 * ((x1 + 0.5) / (n1 + 1) + (x2 + 0.5) / (n2 + 1)) |
248 | 1x |
u <- (1 / n1 + 1 / n2) / 4 |
249 | 1x |
v <- (1 / n1 - 1 / n2) / 4 |
250 | 1x |
z <- kappa |
251 | 1x |
theta <- ((p1_hat - p2_hat) + z^2 * v * (1 - 2 * psi)) / (1 + z^2 * u) |
252 | 1x |
w <- z / (1 + z^2 * u) * sqrt(u * (4 * psi * (1 - psi) - (p1_hat - p2_hat)^2) + 2 * v * (1 - 2 * psi) * |
253 | 1x |
(p1_hat - p2_hat) + 4 * z^2 * u^2 * (1 - psi) * psi + z^2 * v^2 * (1 - 2 * psi)^2) # nolint |
254 | 1x |
c(theta + w, theta - w) |
255 | 1x |
ci_lwr <- max(-1, theta - w) |
256 | 1x |
ci_upr <- min(1, theta + w) |
257 |
}, |
|
258 |
) |
|
259 | 20x |
ci <- c( |
260 | 20x |
est = est, lwr.ci = min(ci_lwr, ci_upr), |
261 | 20x |
upr.ci = max(ci_lwr, ci_upr) |
262 |
) |
|
263 | 20x |
if (sides == "left") { |
264 | ! |
ci[3] <- 1 |
265 | 20x |
} else if (sides == "right") { |
266 | ! |
ci[2] <- -1 |
267 |
} |
|
268 | 20x |
return(ci) |
269 |
} |
|
270 | 20x |
method <- match.arg(arg = method, several.ok = TRUE) |
271 | 20x |
sides <- match.arg(arg = sides, several.ok = TRUE) |
272 | 20x |
lst <- h_recycle( |
273 | 20x |
x1 = x1, n1 = n1, x2 = x2, n2 = n2, conf.level = conf.level, |
274 | 20x |
sides = sides, method = method |
275 |
) |
|
276 | 20x |
res <- t(sapply(1:attr(lst, "maxdim"), function(i) { |
277 | 20x |
iBinomDiffCI( |
278 | 20x |
x1 = lst$x1[i], |
279 | 20x |
n1 = lst$n1[i], x2 = lst$x2[i], n2 = lst$n2[i], conf.level = lst$conf.level[i], |
280 | 20x |
sides = lst$sides[i], method = lst$method[i] |
281 |
) |
|
282 |
})) |
|
283 | 20x |
lgn <- h_recycle(x1 = if (is.null(names(x1))) { |
284 | 20x |
paste("x1", seq_along(x1), sep = ".") |
285 |
} else { |
|
286 | ! |
names(x1) |
287 | 20x |
}, n1 = if (is.null(names(n1))) { |
288 | 20x |
paste("n1", seq_along(n1), sep = ".") |
289 |
} else { |
|
290 | ! |
names(n1) |
291 | 20x |
}, x2 = if (is.null(names(x2))) { |
292 | 20x |
paste("x2", seq_along(x2), sep = ".") |
293 |
} else { |
|
294 | ! |
names(x2) |
295 | 20x |
}, n2 = if (is.null(names(n2))) { |
296 | 20x |
paste("n2", seq_along(n2), sep = ".") |
297 |
} else { |
|
298 | ! |
names(n2) |
299 | 20x |
}, conf.level = conf.level, sides = sides, method = method) |
300 | 20x |
xn <- apply(as.data.frame(lgn[sapply(lgn, function(x) { |
301 | 140x |
length(unique(x)) != |
302 | 140x |
1 |
303 | 20x |
})]), 1, paste, collapse = ":") |
304 | 20x |
rownames(res) <- xn |
305 | 20x |
return(res) |
306 |
} |
|
307 | ||
308 |
#' @describeIn desctools_binom Compute confidence intervals for binomial proportions. |
|
309 |
#' |
|
310 |
#' @param x (`count`)\cr number of successes |
|
311 |
#' @param n (`count`)\cr number of trials |
|
312 |
#' @param conf.level (`proportion`)\cr confidence level, defaults to 0.95. |
|
313 |
#' @param sides (`character`)\cr side of the confidence interval to compute. Must be one of `"two-sided"` (default), |
|
314 |
#' `"left"`, or `"right"`. |
|
315 |
#' @param method (`character`)\cr method to use. Can be one out of: `"wald"`, `"wilson"`, `"wilsoncc"`, |
|
316 |
#' `"agresti-coull"`, `"jeffreys"`, `"modified wilson"`, `"modified jeffreys"`, `"clopper-pearson"`, `"arcsine"`, |
|
317 |
#' `"logit"`, `"witting"`, `"pratt"`, `"midp"`, `"lik"`, and `"blaker"`. |
|
318 |
#' |
|
319 |
#' @return A `matrix` with 3 columns containing: |
|
320 |
#' * `est`: estimate of proportion difference. |
|
321 |
#' * `lwr.ci`: lower end of the confidence interval. |
|
322 |
#' * `upr.ci`: upper end of the confidence interval. |
|
323 |
#' |
|
324 |
#' @keywords internal |
|
325 |
desctools_binomci <- function(x, |
|
326 |
n, |
|
327 |
conf.level = 0.95, # nolint |
|
328 |
sides = c("two.sided", "left", "right"), |
|
329 |
method = c( |
|
330 |
"wilson", "wald", "waldcc", "agresti-coull", |
|
331 |
"jeffreys", "modified wilson", "wilsoncc", "modified jeffreys", |
|
332 |
"clopper-pearson", "arcsine", "logit", "witting", "pratt", |
|
333 |
"midp", "lik", "blaker" |
|
334 |
), |
|
335 |
rand = 123, |
|
336 |
tol = 1e-05) { |
|
337 | 24x |
if (missing(method)) { |
338 | 1x |
method <- "wilson" |
339 |
} |
|
340 | 24x |
if (missing(sides)) { |
341 | 23x |
sides <- "two.sided" |
342 |
} |
|
343 | 24x |
iBinomCI <- function(x, n, conf.level = 0.95, sides = c("two.sided", "left", "right"), # nolint |
344 | 24x |
method = c( |
345 | 24x |
"wilson", "wilsoncc", "wald", |
346 | 24x |
"waldcc", "agresti-coull", "jeffreys", "modified wilson", |
347 | 24x |
"modified jeffreys", "clopper-pearson", "arcsine", "logit", |
348 | 24x |
"witting", "pratt", "midp", "lik", "blaker" |
349 |
), |
|
350 | 24x |
rand = 123, |
351 | 24x |
tol = 1e-05) { |
352 | 24x |
if (length(x) != 1) { |
353 | ! |
stop("'x' has to be of length 1 (number of successes)") |
354 |
} |
|
355 | 24x |
if (length(n) != 1) { |
356 | ! |
stop("'n' has to be of length 1 (number of trials)") |
357 |
} |
|
358 | 24x |
if (length(conf.level) != 1) { |
359 | ! |
stop("'conf.level' has to be of length 1 (confidence level)") |
360 |
} |
|
361 | 24x |
if (conf.level < 0.5 || conf.level > 1) { |
362 | ! |
stop("'conf.level' has to be in [0.5, 1]") |
363 |
} |
|
364 | 24x |
sides <- match.arg(sides, choices = c( |
365 | 24x |
"two.sided", "left", |
366 | 24x |
"right" |
367 | 24x |
), several.ok = FALSE) |
368 | 24x |
if (sides != "two.sided") { |
369 | 1x |
conf.level <- 1 - 2 * (1 - conf.level) # nolint |
370 |
} |
|
371 | 24x |
alpha <- 1 - conf.level |
372 | 24x |
kappa <- stats::qnorm(1 - alpha / 2) |
373 | 24x |
p_hat <- x / n |
374 | 24x |
q_hat <- 1 - p_hat |
375 | 24x |
est <- p_hat |
376 | 24x |
switch(match.arg(arg = method, choices = c( |
377 | 24x |
"wilson", |
378 | 24x |
"wald", "waldcc", "wilsoncc", "agresti-coull", "jeffreys", |
379 | 24x |
"modified wilson", "modified jeffreys", "clopper-pearson", |
380 | 24x |
"arcsine", "logit", "witting", "pratt", "midp", "lik", |
381 | 24x |
"blaker" |
382 |
)), |
|
383 | 24x |
wald = { |
384 | 1x |
term2 <- kappa * sqrt(p_hat * q_hat) / sqrt(n) |
385 | 1x |
ci_lwr <- max(0, p_hat - term2) |
386 | 1x |
ci_upr <- min(1, p_hat + term2) |
387 |
}, |
|
388 | 24x |
waldcc = { |
389 | 1x |
term2 <- kappa * sqrt(p_hat * q_hat) / sqrt(n) |
390 | 1x |
term2 <- term2 + 1 / (2 * n) |
391 | 1x |
ci_lwr <- max(0, p_hat - term2) |
392 | 1x |
ci_upr <- min(1, p_hat + term2) |
393 |
}, |
|
394 | 24x |
wilson = { |
395 | 6x |
term1 <- (x + kappa^2 / 2) / (n + kappa^2) |
396 | 6x |
term2 <- kappa * sqrt(n) / (n + kappa^2) * sqrt(p_hat * q_hat + kappa^2 / (4 * n)) |
397 | 6x |
ci_lwr <- max(0, term1 - term2) |
398 | 6x |
ci_upr <- min(1, term1 + term2) |
399 |
}, |
|
400 | 24x |
wilsoncc = { |
401 | 3x |
lci <- ( |
402 | 3x |
2 * x + kappa^2 - 1 - kappa * sqrt(kappa^2 - 2 - 1 / n + 4 * p_hat * (n * q_hat + 1)) |
403 | 3x |
) / (2 * (n + kappa^2)) |
404 | 3x |
uci <- ( |
405 | 3x |
2 * x + kappa^2 + 1 + kappa * sqrt(kappa^2 + 2 - 1 / n + 4 * p_hat * (n * q_hat - 1)) |
406 | 3x |
) / (2 * (n + kappa^2)) |
407 | 3x |
ci_lwr <- max(0, ifelse(p_hat == 0, 0, lci)) |
408 | 3x |
ci_upr <- min(1, ifelse(p_hat == 1, 1, uci)) |
409 |
}, |
|
410 | 24x |
`agresti-coull` = { |
411 | 1x |
x_tilde <- x + kappa^2 / 2 |
412 | 1x |
n_tilde <- n + kappa^2 |
413 | 1x |
p_tilde <- x_tilde / n_tilde |
414 | 1x |
q_tilde <- 1 - p_tilde |
415 | 1x |
est <- p_tilde |
416 | 1x |
term2 <- kappa * sqrt(p_tilde * q_tilde) / sqrt(n_tilde) |
417 | 1x |
ci_lwr <- max(0, p_tilde - term2) |
418 | 1x |
ci_upr <- min(1, p_tilde + term2) |
419 |
}, |
|
420 | 24x |
jeffreys = { |
421 | 1x |
if (x == 0) { |
422 | ! |
ci_lwr <- 0 |
423 |
} else { |
|
424 | 1x |
ci_lwr <- stats::qbeta( |
425 | 1x |
alpha / 2, |
426 | 1x |
x + 0.5, n - x + 0.5 |
427 |
) |
|
428 |
} |
|
429 | 1x |
if (x == n) { |
430 | ! |
ci_upr <- 1 |
431 |
} else { |
|
432 | 1x |
ci_upr <- stats::qbeta(1 - alpha / 2, x + 0.5, n - x + 0.5) |
433 |
} |
|
434 |
}, |
|
435 | 24x |
`modified wilson` = { |
436 | 1x |
term1 <- (x + kappa^2 / 2) / (n + kappa^2) |
437 | 1x |
term2 <- kappa * sqrt(n) / (n + kappa^2) * sqrt(p_hat * q_hat + kappa^2 / (4 * n)) |
438 | 1x |
if ((n <= 50 & x %in% c(1, 2)) | (n >= 51 & x %in% c(1:3))) { |
439 | ! |
ci_lwr <- 0.5 * stats::qchisq(alpha, 2 * x) / n |
440 |
} else { |
|
441 | 1x |
ci_lwr <- max(0, term1 - term2) |
442 |
} |
|
443 | 1x |
if ((n <= 50 & x %in% c(n - 1, n - 2)) | (n >= 51 & x %in% c(n - (1:3)))) { |
444 | ! |
ci_upr <- 1 - 0.5 * stats::qchisq( |
445 | ! |
alpha, |
446 | ! |
2 * (n - x) |
447 | ! |
) / n |
448 |
} else { |
|
449 | 1x |
ci_upr <- min(1, term1 + term2) |
450 |
} |
|
451 |
}, |
|
452 | 24x |
`modified jeffreys` = { |
453 | 1x |
if (x == n) { |
454 | ! |
ci_lwr <- (alpha / 2)^(1 / n) |
455 |
} else { |
|
456 | 1x |
if (x <= 1) { |
457 | ! |
ci_lwr <- 0 |
458 |
} else { |
|
459 | 1x |
ci_lwr <- stats::qbeta( |
460 | 1x |
alpha / 2, |
461 | 1x |
x + 0.5, n - x + 0.5 |
462 |
) |
|
463 |
} |
|
464 |
} |
|
465 | 1x |
if (x == 0) { |
466 | ! |
ci_upr <- 1 - (alpha / 2)^(1 / n) |
467 |
} else { |
|
468 | 1x |
if (x >= n - 1) { |
469 | ! |
ci_upr <- 1 |
470 |
} else { |
|
471 | 1x |
ci_upr <- stats::qbeta(1 - alpha / 2, x + 0.5, n - x + 0.5) |
472 |
} |
|
473 |
} |
|
474 |
}, |
|
475 | 24x |
`clopper-pearson` = { |
476 | 1x |
ci_lwr <- stats::qbeta(alpha / 2, x, n - x + 1) |
477 | 1x |
ci_upr <- stats::qbeta(1 - alpha / 2, x + 1, n - x) |
478 |
}, |
|
479 | 24x |
arcsine = { |
480 | 1x |
p_tilde <- (x + 0.375) / (n + 0.75) |
481 | 1x |
est <- p_tilde |
482 | 1x |
ci_lwr <- sin(asin(sqrt(p_tilde)) - 0.5 * kappa / sqrt(n))^2 |
483 | 1x |
ci_upr <- sin(asin(sqrt(p_tilde)) + 0.5 * kappa / sqrt(n))^2 |
484 |
}, |
|
485 | 24x |
logit = { |
486 | 1x |
lambda_hat <- log(x / (n - x)) |
487 | 1x |
V_hat <- n / (x * (n - x)) # nolint |
488 | 1x |
lambda_lower <- lambda_hat - kappa * sqrt(V_hat) |
489 | 1x |
lambda_upper <- lambda_hat + kappa * sqrt(V_hat) |
490 | 1x |
ci_lwr <- exp(lambda_lower) / (1 + exp(lambda_lower)) |
491 | 1x |
ci_upr <- exp(lambda_upper) / (1 + exp(lambda_upper)) |
492 |
}, |
|
493 | 24x |
witting = { |
494 | 1x |
set.seed(rand) |
495 | 1x |
x_tilde <- x + stats::runif(1, min = 0, max = 1) |
496 | 1x |
pbinom_abscont <- function(q, size, prob) { |
497 | 22x |
v <- trunc(q) |
498 | 22x |
term1 <- stats::pbinom(v - 1, size = size, prob = prob) |
499 | 22x |
term2 <- (q - v) * stats::dbinom(v, size = size, prob = prob) |
500 | 22x |
return(term1 + term2) |
501 |
} |
|
502 | 1x |
qbinom_abscont <- function(p, size, x) { |
503 | 2x |
fun <- function(prob, size, x, p) { |
504 | 22x |
pbinom_abscont(x, size, prob) - p |
505 |
} |
|
506 | 2x |
stats::uniroot(fun, |
507 | 2x |
interval = c(0, 1), size = size, |
508 | 2x |
x = x, p = p |
509 | 2x |
)$root |
510 |
} |
|
511 | 1x |
ci_lwr <- qbinom_abscont(1 - alpha, size = n, x = x_tilde) |
512 | 1x |
ci_upr <- qbinom_abscont(alpha, size = n, x = x_tilde) |
513 |
}, |
|
514 | 24x |
pratt = { |
515 | 1x |
if (x == 0) { |
516 | ! |
ci_lwr <- 0 |
517 | ! |
ci_upr <- 1 - alpha^(1 / n) |
518 | 1x |
} else if (x == 1) { |
519 | ! |
ci_lwr <- 1 - (1 - alpha / 2)^(1 / n) |
520 | ! |
ci_upr <- 1 - (alpha / 2)^(1 / n) |
521 | 1x |
} else if (x == (n - 1)) { |
522 | ! |
ci_lwr <- (alpha / 2)^(1 / n) |
523 | ! |
ci_upr <- (1 - alpha / 2)^(1 / n) |
524 | 1x |
} else if (x == n) { |
525 | ! |
ci_lwr <- alpha^(1 / n) |
526 | ! |
ci_upr <- 1 |
527 |
} else { |
|
528 | 1x |
z <- stats::qnorm(1 - alpha / 2) |
529 | 1x |
A <- ((x + 1) / (n - x))^2 # nolint |
530 | 1x |
B <- 81 * (x + 1) * (n - x) - 9 * n - 8 # nolint |
531 | 1x |
C <- (0 - 3) * z * sqrt(9 * (x + 1) * (n - x) * (9 * n + 5 - z^2) + n + 1) # nolint |
532 | 1x |
D <- 81 * (x + 1)^2 - 9 * (x + 1) * (2 + z^2) + 1 # nolint |
533 | 1x |
E <- 1 + A * ((B + C) / D)^3 # nolint |
534 | 1x |
ci_upr <- 1 / E |
535 | 1x |
A <- (x / (n - x - 1))^2 # nolint |
536 | 1x |
B <- 81 * x * (n - x - 1) - 9 * n - 8 # nolint |
537 | 1x |
C <- 3 * z * sqrt(9 * x * (n - x - 1) * (9 * n + 5 - z^2) + n + 1) # nolint |
538 | 1x |
D <- 81 * x^2 - 9 * x * (2 + z^2) + 1 # nolint |
539 | 1x |
E <- 1 + A * ((B + C) / D)^3 # nolint |
540 | 1x |
ci_lwr <- 1 / E |
541 |
} |
|
542 |
}, |
|
543 | 24x |
midp = { |
544 | 1x |
f_low <- function(pi, x, n) { |
545 | 12x |
1 / 2 * stats::dbinom(x, size = n, prob = pi) + stats::pbinom(x, |
546 | 12x |
size = n, prob = pi, lower.tail = FALSE |
547 |
) - |
|
548 | 12x |
(1 - conf.level) / 2 |
549 |
} |
|
550 | 1x |
f_up <- function(pi, x, n) { |
551 | 12x |
1 / 2 * stats::dbinom(x, size = n, prob = pi) + stats::pbinom(x - 1, size = n, prob = pi) - (1 - conf.level) / 2 |
552 |
} |
|
553 | 1x |
ci_lwr <- 0 |
554 | 1x |
ci_upr <- 1 |
555 | 1x |
if (x != 0) { |
556 | 1x |
ci_lwr <- stats::uniroot(f_low, |
557 | 1x |
interval = c(0, p_hat), |
558 | 1x |
x = x, n = n |
559 | 1x |
)$root |
560 |
} |
|
561 | 1x |
if (x != n) { |
562 | 1x |
ci_upr <- stats::uniroot(f_up, interval = c( |
563 | 1x |
p_hat, |
564 | 1x |
1 |
565 | 1x |
), x = x, n = n)$root |
566 |
} |
|
567 |
}, |
|
568 | 24x |
lik = { |
569 | 2x |
ci_lwr <- 0 |
570 | 2x |
ci_upr <- 1 |
571 | 2x |
z <- stats::qnorm(1 - alpha * 0.5) |
572 | 2x |
tol <- .Machine$double.eps^0.5 |
573 | 2x |
BinDev <- function(y, x, mu, wt, bound = 0, tol = .Machine$double.eps^0.5, # nolint |
574 |
...) { |
|
575 | 40x |
ll_y <- ifelse(y %in% c(0, 1), 0, stats::dbinom(x, wt, |
576 | 40x |
y, |
577 | 40x |
log = TRUE |
578 |
)) |
|
579 | 40x |
ll_mu <- ifelse(mu %in% c(0, 1), 0, stats::dbinom(x, |
580 | 40x |
wt, mu, |
581 | 40x |
log = TRUE |
582 |
)) |
|
583 | 40x |
res <- ifelse(abs(y - mu) < tol, 0, sign(y - mu) * sqrt(-2 * (ll_y - ll_mu))) |
584 | 40x |
return(res - bound) |
585 |
} |
|
586 | 2x |
if (x != 0 && tol < p_hat) { |
587 | 2x |
ci_lwr <- if (BinDev( |
588 | 2x |
tol, x, p_hat, n, -z, |
589 | 2x |
tol |
590 | 2x |
) <= 0) { |
591 | 2x |
stats::uniroot( |
592 | 2x |
f = BinDev, interval = c(tol, if (p_hat < tol || p_hat == 1) { |
593 | ! |
1 - tol |
594 |
} else { |
|
595 | 2x |
p_hat |
596 | 2x |
}), bound = -z, |
597 | 2x |
x = x, mu = p_hat, wt = n |
598 | 2x |
)$root |
599 |
} |
|
600 |
} |
|
601 | 2x |
if (x != n && p_hat < (1 - tol)) { |
602 | 2x |
ci_upr <- if ( |
603 | 2x |
BinDev(y = 1 - tol, x = x, mu = ifelse(p_hat > 1 - tol, tol, p_hat), wt = n, bound = z, tol = tol) < 0) { # nolint |
604 | ! |
ci_lwr <- if (BinDev( |
605 | ! |
tol, x, if (p_hat < tol || p_hat == 1) { |
606 | ! |
1 - tol |
607 |
} else { |
|
608 | ! |
p_hat |
609 | ! |
}, n, |
610 | ! |
-z, tol |
611 | ! |
) <= 0) { |
612 | ! |
stats::uniroot( |
613 | ! |
f = BinDev, interval = c(tol, p_hat), |
614 | ! |
bound = -z, x = x, mu = p_hat, wt = n |
615 | ! |
)$root |
616 |
} |
|
617 |
} else { |
|
618 | 2x |
stats::uniroot( |
619 | 2x |
f = BinDev, interval = c(if (p_hat > 1 - tol) { |
620 | ! |
tol |
621 |
} else { |
|
622 | 2x |
p_hat |
623 | 2x |
}, 1 - tol), bound = z, |
624 | 2x |
x = x, mu = p_hat, wt = n |
625 | 2x |
)$root |
626 |
} |
|
627 |
} |
|
628 |
}, |
|
629 | 24x |
blaker = { |
630 | 1x |
acceptbin <- function(x, n, p) { |
631 | 3954x |
p1 <- 1 - stats::pbinom(x - 1, n, p) |
632 | 3954x |
p2 <- stats::pbinom(x, n, p) |
633 | 3954x |
a1 <- p1 + stats::pbinom(stats::qbinom(p1, n, p) - 1, n, p) |
634 | 3954x |
a2 <- p2 + 1 - stats::pbinom( |
635 | 3954x |
stats::qbinom(1 - p2, n, p), n, |
636 | 3954x |
p |
637 |
) |
|
638 | 3954x |
return(min(a1, a2)) |
639 |
} |
|
640 | 1x |
ci_lwr <- 0 |
641 | 1x |
ci_upr <- 1 |
642 | 1x |
if (x != 0) { |
643 | 1x |
ci_lwr <- stats::qbeta((1 - conf.level) / 2, x, n - x + 1) |
644 | 1x |
while (acceptbin(x, n, ci_lwr + tol) < (1 - conf.level)) { |
645 | 1976x |
ci_lwr <- ci_lwr + tol |
646 |
} |
|
647 |
} |
|
648 | 1x |
if (x != n) { |
649 | 1x |
ci_upr <- stats::qbeta(1 - (1 - conf.level) / 2, x + 1, n - x) |
650 | 1x |
while (acceptbin(x, n, ci_upr - tol) < (1 - conf.level)) { |
651 | 1976x |
ci_upr <- ci_upr - tol |
652 |
} |
|
653 |
} |
|
654 |
} |
|
655 |
) |
|
656 | 24x |
ci <- c(est = est, lwr.ci = max(0, ci_lwr), upr.ci = min( |
657 | 24x |
1, |
658 | 24x |
ci_upr |
659 |
)) |
|
660 | 24x |
if (sides == "left") { |
661 | 1x |
ci[3] <- 1 |
662 | 23x |
} else if (sides == "right") { |
663 | ! |
ci[2] <- 0 |
664 |
} |
|
665 | 24x |
return(ci) |
666 |
} |
|
667 | 24x |
lst <- list( |
668 | 24x |
x = x, n = n, conf.level = conf.level, sides = sides, |
669 | 24x |
method = method, rand = rand |
670 |
) |
|
671 | 24x |
maxdim <- max(unlist(lapply(lst, length))) |
672 | 24x |
lgp <- lapply(lst, rep, length.out = maxdim) |
673 | 24x |
lgn <- h_recycle(x = if (is.null(names(x))) { |
674 | 24x |
paste("x", seq_along(x), sep = ".") |
675 |
} else { |
|
676 | ! |
names(x) |
677 | 24x |
}, n = if (is.null(names(n))) { |
678 | 24x |
paste("n", seq_along(n), sep = ".") |
679 |
} else { |
|
680 | ! |
names(n) |
681 | 24x |
}, conf.level = conf.level, sides = sides, method = method) |
682 | 24x |
xn <- apply(as.data.frame(lgn[sapply(lgn, function(x) { |
683 | 120x |
length(unique(x)) != |
684 | 120x |
1 |
685 | 24x |
})]), 1, paste, collapse = ":") |
686 | 24x |
res <- t(sapply(1:maxdim, function(i) { |
687 | 24x |
iBinomCI( |
688 | 24x |
x = lgp$x[i], |
689 | 24x |
n = lgp$n[i], conf.level = lgp$conf.level[i], sides = lgp$sides[i], |
690 | 24x |
method = lgp$method[i], rand = lgp$rand[i] |
691 |
) |
|
692 |
})) |
|
693 | 24x |
colnames(res)[1] <- c("est") |
694 | 24x |
rownames(res) <- xn |
695 | 24x |
return(res) |
696 |
} |
1 |
#' Survival Time Point Analysis |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Summarize patients' survival rate and difference of survival rates between groups at a time point. |
|
6 |
#' |
|
7 |
#' @inheritParams argument_convention |
|
8 |
#' @inheritParams s_surv_time |
|
9 |
#' @param time_point (`number`)\cr survival time point of interest. |
|
10 |
#' @param control (`list`)\cr parameters for comparison details, specified by using the helper function |
|
11 |
#' [control_surv_timepoint()]. Some possible parameter options are: |
|
12 |
#' * `conf_level` (`proportion`)\cr confidence level of the interval for survival rate. |
|
13 |
#' * `conf_type` (`string`)\cr confidence interval type. Options are "plain" (default), "log", "log-log", |
|
14 |
#' see more in [survival::survfit()]. Note option "none" is no longer supported. |
|
15 |
#' * `time_point` (`number`)\cr survival time point of interest. |
|
16 |
#' @param method (`string`)\cr either `surv` (survival estimations), |
|
17 |
#' `surv_diff` (difference in survival with the control) or `both`. |
|
18 |
#' @param table_names_suffix (`string`)\cr optional suffix for the `table_names` used for the `rtables` to |
|
19 |
#' avoid warnings from duplicate table names. |
|
20 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("surv_timepoint")` |
|
21 |
#' to see available statistics for this function. |
|
22 |
#' @param .indent_mods (named `vector` of `integer`)\cr indent modifiers for the labels. Each element of the vector |
|
23 |
#' should be a name-value pair with name corresponding to a statistic specified in `.stats` and value the indentation |
|
24 |
#' for that statistic's row label. |
|
25 |
#' |
|
26 |
#' @name survival_timepoint |
|
27 |
#' @order 1 |
|
28 |
NULL |
|
29 | ||
30 |
#' @describeIn survival_timepoint Statistics function which analyzes survival rate. |
|
31 |
#' |
|
32 |
#' @return |
|
33 |
#' * `s_surv_timepoint()` returns the statistics: |
|
34 |
#' * `pt_at_risk`: Patients remaining at risk. |
|
35 |
#' * `event_free_rate`: Event-free rate (%). |
|
36 |
#' * `rate_se`: Standard error of event free rate. |
|
37 |
#' * `rate_ci`: Confidence interval for event free rate. |
|
38 |
#' |
|
39 |
#' @keywords internal |
|
40 |
s_surv_timepoint <- function(df, |
|
41 |
.var, |
|
42 |
time_point, |
|
43 |
is_event, |
|
44 |
control = control_surv_timepoint()) { |
|
45 | 23x |
checkmate::assert_string(.var) |
46 | 23x |
assert_df_with_variables(df, list(tte = .var, is_event = is_event)) |
47 | 23x |
checkmate::assert_numeric(df[[.var]], min.len = 1, any.missing = FALSE) |
48 | 23x |
checkmate::assert_number(time_point) |
49 | 23x |
checkmate::assert_logical(df[[is_event]], min.len = 1, any.missing = FALSE) |
50 | ||
51 | 23x |
conf_type <- control$conf_type |
52 | 23x |
conf_level <- control$conf_level |
53 | ||
54 | 23x |
formula <- stats::as.formula(paste0("survival::Surv(", .var, ", ", is_event, ") ~ 1")) |
55 | 23x |
srv_fit <- survival::survfit( |
56 | 23x |
formula = formula, |
57 | 23x |
data = df, |
58 | 23x |
conf.int = conf_level, |
59 | 23x |
conf.type = conf_type |
60 |
) |
|
61 | 23x |
s_srv_fit <- summary(srv_fit, times = time_point, extend = TRUE) |
62 | 23x |
df_srv_fit <- as.data.frame(s_srv_fit[c("time", "n.risk", "surv", "lower", "upper", "std.err")]) |
63 | 23x |
if (df_srv_fit[["n.risk"]] == 0) { |
64 | 1x |
pt_at_risk <- event_free_rate <- rate_se <- NA_real_ |
65 | 1x |
rate_ci <- c(NA_real_, NA_real_) |
66 |
} else { |
|
67 | 22x |
pt_at_risk <- df_srv_fit$n.risk |
68 | 22x |
event_free_rate <- df_srv_fit$surv |
69 | 22x |
rate_se <- df_srv_fit$std.err |
70 | 22x |
rate_ci <- c(df_srv_fit$lower, df_srv_fit$upper) |
71 |
} |
|
72 | 23x |
list( |
73 | 23x |
pt_at_risk = formatters::with_label(pt_at_risk, "Patients remaining at risk"), |
74 | 23x |
event_free_rate = formatters::with_label(event_free_rate * 100, "Event Free Rate (%)"), |
75 | 23x |
rate_se = formatters::with_label(rate_se * 100, "Standard Error of Event Free Rate"), |
76 | 23x |
rate_ci = formatters::with_label(rate_ci * 100, f_conf_level(conf_level)) |
77 |
) |
|
78 |
} |
|
79 | ||
80 |
#' @describeIn survival_timepoint Formatted analysis function which is used as `afun` in `surv_timepoint()` |
|
81 |
#' when `method = "surv"`. |
|
82 |
#' |
|
83 |
#' @return |
|
84 |
#' * `a_surv_timepoint()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
85 |
#' |
|
86 |
#' @keywords internal |
|
87 |
a_surv_timepoint <- make_afun( |
|
88 |
s_surv_timepoint, |
|
89 |
.indent_mods = c( |
|
90 |
pt_at_risk = 0L, |
|
91 |
event_free_rate = 0L, |
|
92 |
rate_se = 1L, |
|
93 |
rate_ci = 1L |
|
94 |
), |
|
95 |
.formats = c( |
|
96 |
pt_at_risk = "xx", |
|
97 |
event_free_rate = "xx.xx", |
|
98 |
rate_se = "xx.xx", |
|
99 |
rate_ci = "(xx.xx, xx.xx)" |
|
100 |
) |
|
101 |
) |
|
102 | ||
103 |
#' @describeIn survival_timepoint Statistics function which analyzes difference between two survival rates. |
|
104 |
#' |
|
105 |
#' @return |
|
106 |
#' * `s_surv_timepoint_diff()` returns the statistics: |
|
107 |
#' * `rate_diff`: Event-free rate difference between two groups. |
|
108 |
#' * `rate_diff_ci`: Confidence interval for the difference. |
|
109 |
#' * `ztest_pval`: p-value to test the difference is 0. |
|
110 |
#' |
|
111 |
#' @keywords internal |
|
112 |
s_surv_timepoint_diff <- function(df, |
|
113 |
.var, |
|
114 |
.ref_group, |
|
115 |
.in_ref_col, |
|
116 |
time_point, |
|
117 |
control = control_surv_timepoint(), |
|
118 |
...) { |
|
119 | 2x |
if (.in_ref_col) { |
120 | ! |
return( |
121 | ! |
list( |
122 | ! |
rate_diff = formatters::with_label("", "Difference in Event Free Rate"), |
123 | ! |
rate_diff_ci = formatters::with_label("", f_conf_level(control$conf_level)), |
124 | ! |
ztest_pval = formatters::with_label("", "p-value (Z-test)") |
125 |
) |
|
126 |
) |
|
127 |
} |
|
128 | 2x |
data <- rbind(.ref_group, df) |
129 | 2x |
group <- factor(rep(c("ref", "x"), c(nrow(.ref_group), nrow(df))), levels = c("ref", "x")) |
130 | 2x |
res_per_group <- lapply(split(data, group), function(x) { |
131 | 4x |
s_surv_timepoint(df = x, .var = .var, time_point = time_point, control = control, ...) |
132 |
}) |
|
133 | ||
134 | 2x |
res_x <- res_per_group[[2]] |
135 | 2x |
res_ref <- res_per_group[[1]] |
136 | 2x |
rate_diff <- res_x$event_free_rate - res_ref$event_free_rate |
137 | 2x |
se_diff <- sqrt(res_x$rate_se^2 + res_ref$rate_se^2) |
138 | ||
139 | 2x |
qs <- c(-1, 1) * stats::qnorm(1 - (1 - control$conf_level) / 2) |
140 | 2x |
rate_diff_ci <- rate_diff + qs * se_diff |
141 | 2x |
ztest_pval <- if (is.na(rate_diff)) { |
142 | 2x |
NA |
143 |
} else { |
|
144 | 2x |
2 * (1 - stats::pnorm(abs(rate_diff) / se_diff)) |
145 |
} |
|
146 | 2x |
list( |
147 | 2x |
rate_diff = formatters::with_label(rate_diff, "Difference in Event Free Rate"), |
148 | 2x |
rate_diff_ci = formatters::with_label(rate_diff_ci, f_conf_level(control$conf_level)), |
149 | 2x |
ztest_pval = formatters::with_label(ztest_pval, "p-value (Z-test)") |
150 |
) |
|
151 |
} |
|
152 | ||
153 |
#' @describeIn survival_timepoint Formatted analysis function which is used as `afun` in `surv_timepoint()` |
|
154 |
#' when `method = "surv_diff"`. |
|
155 |
#' |
|
156 |
#' @return |
|
157 |
#' * `a_surv_timepoint_diff()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
158 |
#' |
|
159 |
#' @keywords internal |
|
160 |
a_surv_timepoint_diff <- make_afun( |
|
161 |
s_surv_timepoint_diff, |
|
162 |
.formats = c( |
|
163 |
rate_diff = "xx.xx", |
|
164 |
rate_diff_ci = "(xx.xx, xx.xx)", |
|
165 |
ztest_pval = "x.xxxx | (<0.0001)" |
|
166 |
) |
|
167 |
) |
|
168 | ||
169 |
#' @describeIn survival_timepoint Layout-creating function which can take statistics function arguments |
|
170 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
171 |
#' |
|
172 |
#' @return |
|
173 |
#' * `surv_timepoint()` returns a layout object suitable for passing to further layouting functions, |
|
174 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
175 |
#' the statistics from `s_surv_timepoint()` and/or `s_surv_timepoint_diff()` to the table layout depending on |
|
176 |
#' the value of `method`. |
|
177 |
#' |
|
178 |
#' @examples |
|
179 |
#' library(dplyr) |
|
180 |
#' |
|
181 |
#' adtte_f <- tern_ex_adtte %>% |
|
182 |
#' filter(PARAMCD == "OS") %>% |
|
183 |
#' mutate( |
|
184 |
#' AVAL = day2month(AVAL), |
|
185 |
#' is_event = CNSR == 0 |
|
186 |
#' ) |
|
187 |
#' |
|
188 |
#' # Survival at given time points. |
|
189 |
#' basic_table() %>% |
|
190 |
#' split_cols_by(var = "ARMCD", ref_group = "ARM A") %>% |
|
191 |
#' add_colcounts() %>% |
|
192 |
#' surv_timepoint( |
|
193 |
#' vars = "AVAL", |
|
194 |
#' var_labels = "Months", |
|
195 |
#' is_event = "is_event", |
|
196 |
#' time_point = 7 |
|
197 |
#' ) %>% |
|
198 |
#' build_table(df = adtte_f) |
|
199 |
#' |
|
200 |
#' # Difference in survival at given time points. |
|
201 |
#' basic_table() %>% |
|
202 |
#' split_cols_by(var = "ARMCD", ref_group = "ARM A") %>% |
|
203 |
#' add_colcounts() %>% |
|
204 |
#' surv_timepoint( |
|
205 |
#' vars = "AVAL", |
|
206 |
#' var_labels = "Months", |
|
207 |
#' is_event = "is_event", |
|
208 |
#' time_point = 9, |
|
209 |
#' method = "surv_diff", |
|
210 |
#' .indent_mods = c("rate_diff" = 0L, "rate_diff_ci" = 2L, "ztest_pval" = 2L) |
|
211 |
#' ) %>% |
|
212 |
#' build_table(df = adtte_f) |
|
213 |
#' |
|
214 |
#' # Survival and difference in survival at given time points. |
|
215 |
#' basic_table() %>% |
|
216 |
#' split_cols_by(var = "ARMCD", ref_group = "ARM A") %>% |
|
217 |
#' add_colcounts() %>% |
|
218 |
#' surv_timepoint( |
|
219 |
#' vars = "AVAL", |
|
220 |
#' var_labels = "Months", |
|
221 |
#' is_event = "is_event", |
|
222 |
#' time_point = 9, |
|
223 |
#' method = "both" |
|
224 |
#' ) %>% |
|
225 |
#' build_table(df = adtte_f) |
|
226 |
#' |
|
227 |
#' @export |
|
228 |
#' @order 2 |
|
229 |
surv_timepoint <- function(lyt, |
|
230 |
vars, |
|
231 |
time_point, |
|
232 |
is_event, |
|
233 |
control = control_surv_timepoint(), |
|
234 |
method = c("surv", "surv_diff", "both"), |
|
235 |
na_str = default_na_str(), |
|
236 |
nested = TRUE, |
|
237 |
..., |
|
238 |
table_names_suffix = "", |
|
239 |
var_labels = "Time", |
|
240 |
show_labels = "visible", |
|
241 |
.stats = c( |
|
242 |
"pt_at_risk", "event_free_rate", "rate_ci", |
|
243 |
"rate_diff", "rate_diff_ci", "ztest_pval" |
|
244 |
), |
|
245 |
.formats = NULL, |
|
246 |
.labels = NULL, |
|
247 |
.indent_mods = if (method == "both") { |
|
248 | 2x |
c(rate_diff = 1L, rate_diff_ci = 2L, ztest_pval = 2L) |
249 |
} else { |
|
250 | 4x |
c(rate_diff_ci = 1L, ztest_pval = 1L) |
251 |
}) { |
|
252 | 6x |
method <- match.arg(method) |
253 | 6x |
checkmate::assert_string(table_names_suffix) |
254 | ||
255 | 6x |
extra_args <- list(time_point = time_point, is_event = is_event, control = control, ...) |
256 | ||
257 | 6x |
f <- list( |
258 | 6x |
surv = c("pt_at_risk", "event_free_rate", "rate_se", "rate_ci"), |
259 | 6x |
surv_diff = c("rate_diff", "rate_diff_ci", "ztest_pval") |
260 |
) |
|
261 | 6x |
.stats <- h_split_param(.stats, .stats, f = f) |
262 | 6x |
.formats <- h_split_param(.formats, names(.formats), f = f) |
263 | 6x |
.labels <- h_split_param(.labels, names(.labels), f = f) |
264 | 6x |
.indent_mods <- h_split_param(.indent_mods, names(.indent_mods), f = f) |
265 | ||
266 | 6x |
afun_surv <- make_afun( |
267 | 6x |
a_surv_timepoint, |
268 | 6x |
.stats = .stats$surv, |
269 | 6x |
.formats = .formats$surv, |
270 | 6x |
.labels = .labels$surv, |
271 | 6x |
.indent_mods = .indent_mods$surv |
272 |
) |
|
273 | ||
274 | 6x |
afun_surv_diff <- make_afun( |
275 | 6x |
a_surv_timepoint_diff, |
276 | 6x |
.stats = .stats$surv_diff, |
277 | 6x |
.formats = .formats$surv_diff, |
278 | 6x |
.labels = .labels$surv_diff, |
279 | 6x |
.indent_mods = .indent_mods$surv_diff |
280 |
) |
|
281 | ||
282 | 6x |
time_point <- extra_args$time_point |
283 | ||
284 | 6x |
for (i in seq_along(time_point)) { |
285 | 6x |
extra_args[["time_point"]] <- time_point[i] |
286 | ||
287 | 6x |
if (method %in% c("surv", "both")) { |
288 | 4x |
lyt <- analyze( |
289 | 4x |
lyt, |
290 | 4x |
vars, |
291 | 4x |
var_labels = paste(time_point[i], var_labels), |
292 | 4x |
table_names = paste0("surv_", time_point[i], table_names_suffix), |
293 | 4x |
show_labels = show_labels, |
294 | 4x |
afun = afun_surv, |
295 | 4x |
na_str = na_str, |
296 | 4x |
nested = nested, |
297 | 4x |
extra_args = extra_args |
298 |
) |
|
299 |
} |
|
300 | ||
301 | 6x |
if (method %in% c("surv_diff", "both")) { |
302 | 4x |
lyt <- analyze( |
303 | 4x |
lyt, |
304 | 4x |
vars, |
305 | 4x |
var_labels = paste(time_point[i], var_labels), |
306 | 4x |
table_names = paste0("surv_diff_", time_point[i], table_names_suffix), |
307 | 4x |
show_labels = ifelse(method == "both", "hidden", show_labels), |
308 | 4x |
afun = afun_surv_diff, |
309 | 4x |
na_str = na_str, |
310 | 4x |
nested = nested, |
311 | 4x |
extra_args = extra_args |
312 |
) |
|
313 |
} |
|
314 |
} |
|
315 | 6x |
lyt |
316 |
} |
1 |
#' Survival Time Analysis |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Summarize median survival time and CIs, percentiles of survival times, survival |
|
6 |
#' time range of censored/event patients. |
|
7 |
#' |
|
8 |
#' @inheritParams argument_convention |
|
9 |
#' @param control (`list`)\cr parameters for comparison details, specified by using the helper function |
|
10 |
#' [control_surv_time()]. Some possible parameter options are: |
|
11 |
#' * `conf_level` (`proportion`)\cr confidence level of the interval for survival time. |
|
12 |
#' * `conf_type` (`string`)\cr confidence interval type. Options are "plain" (default), "log", or "log-log", |
|
13 |
#' see more in [survival::survfit()]. Note option "none" is not supported. |
|
14 |
#' * `quantiles` (`numeric`)\cr vector of length two to specify the quantiles of survival time. |
|
15 |
#' @param ref_fn_censor (`flag`)\cr whether referential footnotes indicating censored observations should be printed |
|
16 |
#' when the `range` statistic is included. |
|
17 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("surv_time")` |
|
18 |
#' to see available statistics for this function. |
|
19 |
#' @param .indent_mods (named `vector` of `integer`)\cr indent modifiers for the labels. Each element of the vector |
|
20 |
#' should be a name-value pair with name corresponding to a statistic specified in `.stats` and value the indentation |
|
21 |
#' for that statistic's row label. |
|
22 |
#' |
|
23 |
#' @examples |
|
24 |
#' library(dplyr) |
|
25 |
#' |
|
26 |
#' adtte_f <- tern_ex_adtte %>% |
|
27 |
#' filter(PARAMCD == "OS") %>% |
|
28 |
#' mutate( |
|
29 |
#' AVAL = day2month(AVAL), |
|
30 |
#' is_event = CNSR == 0 |
|
31 |
#' ) |
|
32 |
#' df <- adtte_f %>% filter(ARMCD == "ARM A") |
|
33 |
#' |
|
34 |
#' @name survival_time |
|
35 |
#' @order 1 |
|
36 |
NULL |
|
37 | ||
38 |
#' @describeIn survival_time Statistics function which analyzes survival times. |
|
39 |
#' |
|
40 |
#' @return |
|
41 |
#' * `s_surv_time()` returns the statistics: |
|
42 |
#' * `median`: Median survival time. |
|
43 |
#' * `median_ci`: Confidence interval for median time. |
|
44 |
#' * `quantiles`: Survival time for two specified quantiles. |
|
45 |
#' * `range_censor`: Survival time range for censored observations. |
|
46 |
#' * `range_event`: Survival time range for observations with events. |
|
47 |
#' * `range`: Survival time range for all observations. |
|
48 |
#' |
|
49 |
#' @keywords internal |
|
50 |
s_surv_time <- function(df, |
|
51 |
.var, |
|
52 |
is_event, |
|
53 |
control = control_surv_time()) { |
|
54 | 182x |
checkmate::assert_string(.var) |
55 | 182x |
assert_df_with_variables(df, list(tte = .var, is_event = is_event)) |
56 | 182x |
checkmate::assert_numeric(df[[.var]], min.len = 1, any.missing = FALSE) |
57 | 182x |
checkmate::assert_logical(df[[is_event]], min.len = 1, any.missing = FALSE) |
58 | ||
59 | 182x |
conf_type <- control$conf_type |
60 | 182x |
conf_level <- control$conf_level |
61 | 182x |
quantiles <- control$quantiles |
62 | ||
63 | 182x |
formula <- stats::as.formula(paste0("survival::Surv(", .var, ", ", is_event, ") ~ 1")) |
64 | 182x |
srv_fit <- survival::survfit( |
65 | 182x |
formula = formula, |
66 | 182x |
data = df, |
67 | 182x |
conf.int = conf_level, |
68 | 182x |
conf.type = conf_type |
69 |
) |
|
70 | 182x |
srv_tab <- summary(srv_fit, extend = TRUE)$table |
71 | 182x |
srv_qt_tab <- stats::quantile(srv_fit, probs = quantiles)$quantile |
72 | 182x |
range_censor <- range_noinf(df[[.var]][!df[[is_event]]], na.rm = TRUE) |
73 | 182x |
range_event <- range_noinf(df[[.var]][df[[is_event]]], na.rm = TRUE) |
74 | 182x |
range <- range_noinf(df[[.var]], na.rm = TRUE) |
75 | 182x |
list( |
76 | 182x |
median = formatters::with_label(unname(srv_tab["median"]), "Median"), |
77 | 182x |
median_ci = formatters::with_label( |
78 | 182x |
unname(srv_tab[paste0(srv_fit$conf.int, c("LCL", "UCL"))]), f_conf_level(conf_level) |
79 |
), |
|
80 | 182x |
quantiles = formatters::with_label( |
81 | 182x |
unname(srv_qt_tab), paste0(quantiles[1] * 100, "% and ", quantiles[2] * 100, "%-ile") |
82 |
), |
|
83 | 182x |
range_censor = formatters::with_label(range_censor, "Range (censored)"), |
84 | 182x |
range_event = formatters::with_label(range_event, "Range (event)"), |
85 | 182x |
range = formatters::with_label(range, "Range") |
86 |
) |
|
87 |
} |
|
88 | ||
89 |
#' @describeIn survival_time Formatted analysis function which is used as `afun` in `surv_time()`. |
|
90 |
#' |
|
91 |
#' @return |
|
92 |
#' * `a_surv_time()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
93 |
#' |
|
94 |
#' @examples |
|
95 |
#' a_surv_time( |
|
96 |
#' df, |
|
97 |
#' .df_row = df, |
|
98 |
#' .var = "AVAL", |
|
99 |
#' is_event = "is_event" |
|
100 |
#' ) |
|
101 |
#' |
|
102 |
#' @export |
|
103 |
a_surv_time <- function(df, |
|
104 |
labelstr = "", |
|
105 |
.var = NULL, |
|
106 |
.df_row = NULL, |
|
107 |
is_event, |
|
108 |
control = control_surv_time(), |
|
109 |
ref_fn_censor = TRUE, |
|
110 |
.stats = NULL, |
|
111 |
.formats = NULL, |
|
112 |
.labels = NULL, |
|
113 |
.indent_mods = NULL, |
|
114 |
na_str = default_na_str()) { |
|
115 | 12x |
x_stats <- s_surv_time( |
116 | 12x |
df = df, .var = .var, is_event = is_event, control = control |
117 |
) |
|
118 | 12x |
rng_censor_lwr <- x_stats[["range_censor"]][1] |
119 | 12x |
rng_censor_upr <- x_stats[["range_censor"]][2] |
120 | ||
121 |
# Use method-specific defaults |
|
122 | 12x |
fmts <- c(median_ci = "(xx.x, xx.x)", quantiles = "xx.x, xx.x", range = "xx.x to xx.x") |
123 | 12x |
lbls <- c(median_ci = "95% CI", range = "Range", range_censor = "Range (censored)", range_event = "Range (event)") |
124 | 12x |
lbls_custom <- .labels |
125 | 12x |
.formats <- c(.formats, fmts[setdiff(names(fmts), names(.formats))]) |
126 | 12x |
.labels <- c(.labels, lbls[setdiff(names(lbls), names(lbls_custom))]) |
127 | ||
128 |
# Fill in with formatting defaults if needed |
|
129 | 12x |
.stats <- get_stats("surv_time", stats_in = .stats) |
130 | 12x |
.formats <- get_formats_from_stats(.stats, .formats) |
131 | 12x |
.labels <- get_labels_from_stats(.stats, .labels) %>% labels_use_control(control, lbls_custom) |
132 | 12x |
.indent_mods <- get_indents_from_stats(.stats, .indent_mods) |
133 | ||
134 | 12x |
x_stats <- x_stats[.stats] |
135 | ||
136 |
# Auto format handling |
|
137 | 12x |
.formats <- apply_auto_formatting(.formats, x_stats, .df_row, .var) |
138 | ||
139 | 12x |
cell_fns <- setNames(vector("list", length = length(x_stats)), .labels) |
140 | 12x |
if ("range" %in% names(x_stats) && ref_fn_censor) { |
141 | 12x |
if (x_stats[["range"]][1] == rng_censor_lwr && x_stats[["range"]][2] == rng_censor_upr) { |
142 | 1x |
cell_fns[[.labels[["range"]]]] <- "Censored observations: range minimum & maximum" |
143 | 11x |
} else if (x_stats[["range"]][1] == rng_censor_lwr) { |
144 | 2x |
cell_fns[[.labels[["range"]]]] <- "Censored observation: range minimum" |
145 | 9x |
} else if (x_stats[["range"]][2] == rng_censor_upr) { |
146 | 1x |
cell_fns[[.labels[["range"]]]] <- "Censored observation: range maximum" |
147 |
} |
|
148 |
} |
|
149 | ||
150 | 12x |
in_rows( |
151 | 12x |
.list = x_stats, |
152 | 12x |
.formats = .formats, |
153 | 12x |
.names = .labels, |
154 | 12x |
.labels = .labels, |
155 | 12x |
.indent_mods = .indent_mods, |
156 | 12x |
.format_na_strs = na_str, |
157 | 12x |
.cell_footnotes = cell_fns |
158 |
) |
|
159 |
} |
|
160 | ||
161 |
#' @describeIn survival_time Layout-creating function which can take statistics function arguments |
|
162 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
163 |
#' |
|
164 |
#' @return |
|
165 |
#' * `surv_time()` returns a layout object suitable for passing to further layouting functions, |
|
166 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
167 |
#' the statistics from `s_surv_time()` to the table layout. |
|
168 |
#' |
|
169 |
#' @examples |
|
170 |
#' basic_table() %>% |
|
171 |
#' split_cols_by(var = "ARMCD") %>% |
|
172 |
#' add_colcounts() %>% |
|
173 |
#' surv_time( |
|
174 |
#' vars = "AVAL", |
|
175 |
#' var_labels = "Survival Time (Months)", |
|
176 |
#' is_event = "is_event", |
|
177 |
#' control = control_surv_time(conf_level = 0.9, conf_type = "log-log") |
|
178 |
#' ) %>% |
|
179 |
#' build_table(df = adtte_f) |
|
180 |
#' |
|
181 |
#' @export |
|
182 |
#' @order 2 |
|
183 |
surv_time <- function(lyt, |
|
184 |
vars, |
|
185 |
is_event, |
|
186 |
control = control_surv_time(), |
|
187 |
ref_fn_censor = TRUE, |
|
188 |
na_str = default_na_str(), |
|
189 |
nested = TRUE, |
|
190 |
..., |
|
191 |
var_labels = "Time to Event", |
|
192 |
show_labels = "visible", |
|
193 |
table_names = vars, |
|
194 |
.stats = c("median", "median_ci", "quantiles", "range"), |
|
195 |
.formats = NULL, |
|
196 |
.labels = NULL, |
|
197 |
.indent_mods = c(median_ci = 1L)) { |
|
198 | 3x |
extra_args <- list( |
199 | 3x |
.stats = .stats, .formats = .formats, .labels = .labels, .indent_mods = .indent_mods, na_str = na_str, |
200 | 3x |
is_event = is_event, control = control, ref_fn_censor = ref_fn_censor, ... |
201 |
) |
|
202 | ||
203 | 3x |
analyze( |
204 | 3x |
lyt = lyt, |
205 | 3x |
vars = vars, |
206 | 3x |
afun = a_surv_time, |
207 | 3x |
var_labels = var_labels, |
208 | 3x |
show_labels = show_labels, |
209 | 3x |
table_names = table_names, |
210 | 3x |
na_str = na_str, |
211 | 3x |
nested = nested, |
212 | 3x |
extra_args = extra_args |
213 |
) |
|
214 |
} |
1 |
#' Kaplan-Meier Plot |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' From a survival model, a graphic is rendered along with tabulated annotation |
|
6 |
#' including the number of patient at risk at given time and the median survival |
|
7 |
#' per group. |
|
8 |
#' |
|
9 |
#' @inheritParams grid::gTree |
|
10 |
#' @inheritParams argument_convention |
|
11 |
#' @param df (`data.frame`)\cr data set containing all analysis variables. |
|
12 |
#' @param variables (named `list`)\cr variable names. Details are: |
|
13 |
#' * `tte` (`numeric`)\cr variable indicating time-to-event duration values. |
|
14 |
#' * `is_event` (`logical`)\cr event variable. `TRUE` if event, `FALSE` if time to event is censored. |
|
15 |
#' * `arm` (`factor`)\cr the treatment group variable. |
|
16 |
#' * `strat` (`character` or `NULL`)\cr variable names indicating stratification factors. |
|
17 |
#' @param control_surv (`list`)\cr parameters for comparison details, specified by using |
|
18 |
#' the helper function [control_surv_timepoint()]. Some possible parameter options are: |
|
19 |
#' * `conf_level` (`proportion`)\cr confidence level of the interval for survival rate. |
|
20 |
#' * `conf_type` (`string`)\cr `"plain"` (default), `"log"`, `"log-log"` for confidence interval type, |
|
21 |
#' see more in [survival::survfit()]. Note that the option "none" is no longer supported. |
|
22 |
#' @param xticks (`numeric`, `number`, or `NULL`)\cr numeric vector of ticks or single number with spacing |
|
23 |
#' between ticks on the x axis. If `NULL` (default), [labeling::extended()] is used to determine |
|
24 |
#' an optimal tick position on the x axis. |
|
25 |
#' @param yval (`string`)\cr value of y-axis. Options are `Survival` (default) and `Failure` probability. |
|
26 |
#' @param censor_show (`flag`)\cr whether to show censored. |
|
27 |
#' @param xlab (`string`)\cr label of x-axis. |
|
28 |
#' @param ylab (`string`)\cr label of y-axis. |
|
29 |
#' @param ylim (`vector` of `numeric`)\cr vector of length 2 containing lower and upper limits for the y-axis. |
|
30 |
#' If `NULL` (default), the minimum and maximum y-values displayed are used as limits. |
|
31 |
#' @param title (`string`)\cr title for plot. |
|
32 |
#' @param footnotes (`string`)\cr footnotes for plot. |
|
33 |
#' @param col (`character`)\cr lines colors. Length of a vector should be equal |
|
34 |
#' to number of strata from [survival::survfit()]. |
|
35 |
#' @param lty (`numeric`)\cr line type. Length of a vector should be equal |
|
36 |
#' to number of strata from [survival::survfit()]. |
|
37 |
#' @param lwd (`numeric`)\cr line width. Length of a vector should be equal |
|
38 |
#' to number of strata from [survival::survfit()]. |
|
39 |
#' @param pch (`numeric`, `string`)\cr value or character of points symbol to indicate censored cases. |
|
40 |
#' @param size (`numeric`)\cr size of censored point, a class of `unit`. |
|
41 |
#' @param max_time (`numeric`)\cr maximum value to show on X axis. Only data values less than or up to |
|
42 |
#' this threshold value will be plotted (defaults to `NULL`). |
|
43 |
#' @param font_size (`number`)\cr font size to be used. |
|
44 |
#' @param ci_ribbon (`flag`)\cr draw the confidence interval around the Kaplan-Meier curve. |
|
45 |
#' @param ggtheme (`theme`)\cr a graphical theme as provided by `ggplot2` to control outlook of the Kaplan-Meier curve. |
|
46 |
#' @param annot_at_risk (`flag`)\cr compute and add the annotation table reporting the number of patient at risk |
|
47 |
#' matching the main grid of the Kaplan-Meier curve. |
|
48 |
#' @param annot_at_risk_title (`flag`)\cr whether the "Patients at Risk" title should be added above the `annot_at_risk` |
|
49 |
#' table. Has no effect if `annot_at_risk` is `FALSE`. Defaults to `TRUE`. |
|
50 |
#' @param annot_surv_med (`flag`)\cr compute and add the annotation table on the Kaplan-Meier curve estimating the |
|
51 |
#' median survival time per group. |
|
52 |
#' @param annot_coxph (`flag`)\cr add the annotation table from a [survival::coxph()] model. |
|
53 |
#' @param annot_stats (`string`)\cr statistics annotations to add to the plot. Options are |
|
54 |
#' `median` (median survival follow-up time) and `min` (minimum survival follow-up time). |
|
55 |
#' @param annot_stats_vlines (`flag`)\cr add vertical lines corresponding to each of the statistics |
|
56 |
#' specified by `annot_stats`. If `annot_stats` is `NULL` no lines will be added. |
|
57 |
#' @param control_coxph_pw (`list`)\cr parameters for comparison details, specified by using |
|
58 |
#' the helper function [control_coxph()]. Some possible parameter options are: |
|
59 |
#' * `pval_method` (`string`)\cr p-value method for testing hazard ratio = 1. |
|
60 |
#' Default method is `"log-rank"`, can also be set to `"wald"` or `"likelihood"`. |
|
61 |
#' * `ties` (`string`)\cr method for tie handling. Default is `"efron"`, |
|
62 |
#' can also be set to `"breslow"` or `"exact"`. See more in [survival::coxph()] |
|
63 |
#' * `conf_level` (`proportion`)\cr confidence level of the interval for HR. |
|
64 |
#' @param ref_group_coxph (`character`)\cr level of arm variable to use as reference group in calculations for |
|
65 |
#' `annot_coxph` table. If `NULL` (default), uses the first level of the arm variable. |
|
66 |
#' @param annot_coxph_ref_lbls (`flag`)\cr whether the reference group should be explicitly printed in labels for the |
|
67 |
#' `annot_coxph` table. If `FALSE` (default), only comparison groups will be printed in `annot_coxph` table labels. |
|
68 |
#' @param position_coxph (`numeric`)\cr x and y positions for plotting [survival::coxph()] model. |
|
69 |
#' @param position_surv_med (`numeric`)\cr x and y positions for plotting annotation table estimating median survival |
|
70 |
#' time per group. |
|
71 |
#' @param width_annots (named `list` of `unit`s)\cr a named list of widths for annotation tables with names `surv_med` |
|
72 |
#' (median survival time table) and `coxph` ([survival::coxph()] model table), where each value is the width |
|
73 |
#' (in units) to implement when printing the annotation table. |
|
74 |
#' |
|
75 |
#' @return A `grob` of class `gTree`. |
|
76 |
#' |
|
77 |
#' @examples |
|
78 |
#' \donttest{ |
|
79 |
#' library(dplyr) |
|
80 |
#' library(ggplot2) |
|
81 |
#' library(survival) |
|
82 |
#' library(grid) |
|
83 |
#' library(nestcolor) |
|
84 |
#' |
|
85 |
#' df <- tern_ex_adtte %>% |
|
86 |
#' filter(PARAMCD == "OS") %>% |
|
87 |
#' mutate(is_event = CNSR == 0) |
|
88 |
#' variables <- list(tte = "AVAL", is_event = "is_event", arm = "ARMCD") |
|
89 |
#' |
|
90 |
#' # 1. Example - basic option |
|
91 |
#' |
|
92 |
#' res <- g_km(df = df, variables = variables) |
|
93 |
#' res <- g_km(df = df, variables = variables, yval = "Failure") |
|
94 |
#' res <- g_km( |
|
95 |
#' df = df, |
|
96 |
#' variables = variables, |
|
97 |
#' control_surv = control_surv_timepoint(conf_level = 0.9), |
|
98 |
#' col = c("grey25", "grey50", "grey75"), |
|
99 |
#' annot_at_risk_title = FALSE |
|
100 |
#' ) |
|
101 |
#' res <- g_km(df = df, variables = variables, ggtheme = theme_minimal()) |
|
102 |
#' res <- g_km(df = df, variables = variables, ggtheme = theme_minimal(), lty = 1:3) |
|
103 |
#' res <- g_km(df = df, variables = variables, max = 2000) |
|
104 |
#' res <- g_km( |
|
105 |
#' df = df, |
|
106 |
#' variables = variables, |
|
107 |
#' annot_stats = c("min", "median"), |
|
108 |
#' annot_stats_vlines = TRUE |
|
109 |
#' ) |
|
110 |
#' |
|
111 |
#' # 2. Example - Arrange several KM curve on a single graph device |
|
112 |
#' |
|
113 |
#' # 2.1 Use case: A general graph on the top, a zoom on the bottom. |
|
114 |
#' grid.newpage() |
|
115 |
#' lyt <- grid.layout(nrow = 2, ncol = 1) %>% |
|
116 |
#' viewport(layout = .) %>% |
|
117 |
#' pushViewport() |
|
118 |
#' |
|
119 |
#' res <- g_km( |
|
120 |
#' df = df, variables = variables, newpage = FALSE, annot_surv_med = FALSE, |
|
121 |
#' vp = viewport(layout.pos.row = 1, layout.pos.col = 1) |
|
122 |
#' ) |
|
123 |
#' res <- g_km( |
|
124 |
#' df = df, variables = variables, max = 1000, newpage = FALSE, annot_surv_med = FALSE, |
|
125 |
#' ggtheme = theme_dark(), |
|
126 |
#' vp = viewport(layout.pos.row = 2, layout.pos.col = 1) |
|
127 |
#' ) |
|
128 |
#' |
|
129 |
#' # 2.1 Use case: No annotations on top, annotated graph on bottom |
|
130 |
#' grid.newpage() |
|
131 |
#' lyt <- grid.layout(nrow = 2, ncol = 1) %>% |
|
132 |
#' viewport(layout = .) %>% |
|
133 |
#' pushViewport() |
|
134 |
#' |
|
135 |
#' res <- g_km( |
|
136 |
#' df = df, variables = variables, newpage = FALSE, |
|
137 |
#' annot_surv_med = FALSE, annot_at_risk = FALSE, |
|
138 |
#' vp = viewport(layout.pos.row = 1, layout.pos.col = 1) |
|
139 |
#' ) |
|
140 |
#' res <- g_km( |
|
141 |
#' df = df, variables = variables, max = 2000, newpage = FALSE, annot_surv_med = FALSE, |
|
142 |
#' annot_at_risk = TRUE, |
|
143 |
#' ggtheme = theme_dark(), |
|
144 |
#' vp = viewport(layout.pos.row = 2, layout.pos.col = 1) |
|
145 |
#' ) |
|
146 |
#' |
|
147 |
#' # Add annotation from a pairwise coxph analysis |
|
148 |
#' g_km( |
|
149 |
#' df = df, variables = variables, |
|
150 |
#' annot_coxph = TRUE |
|
151 |
#' ) |
|
152 |
#' |
|
153 |
#' # Change widths/sizes of surv_med and coxph annotation tables. |
|
154 |
#' g_km( |
|
155 |
#' df = df, variables = c(variables, list(strat = "SEX")), |
|
156 |
#' annot_coxph = TRUE, |
|
157 |
#' width_annots = list(surv_med = grid::unit(2, "in"), coxph = grid::unit(3, "in")) |
|
158 |
#' ) |
|
159 |
#' |
|
160 |
#' g_km( |
|
161 |
#' df = df, variables = c(variables, list(strat = "SEX")), |
|
162 |
#' font_size = 15, |
|
163 |
#' annot_coxph = TRUE, |
|
164 |
#' control_coxph = control_coxph(pval_method = "wald", ties = "exact", conf_level = 0.99), |
|
165 |
#' position_coxph = c(0.5, 0.5) |
|
166 |
#' ) |
|
167 |
#' |
|
168 |
#' # Change position of the treatment group annotation table. |
|
169 |
#' g_km( |
|
170 |
#' df = df, variables = c(variables, list(strat = "SEX")), |
|
171 |
#' font_size = 15, |
|
172 |
#' annot_coxph = TRUE, |
|
173 |
#' control_coxph = control_coxph(pval_method = "wald", ties = "exact", conf_level = 0.99), |
|
174 |
#' position_surv_med = c(1, 0.7) |
|
175 |
#' ) |
|
176 |
#' } |
|
177 |
#' |
|
178 |
#' @export |
|
179 |
g_km <- function(df, |
|
180 |
variables, |
|
181 |
control_surv = control_surv_timepoint(), |
|
182 |
col = NULL, |
|
183 |
lty = NULL, |
|
184 |
lwd = .5, |
|
185 |
censor_show = TRUE, |
|
186 |
pch = 3, |
|
187 |
size = 2, |
|
188 |
max_time = NULL, |
|
189 |
xticks = NULL, |
|
190 |
xlab = "Days", |
|
191 |
yval = c("Survival", "Failure"), |
|
192 |
ylab = paste(yval, "Probability"), |
|
193 |
ylim = NULL, |
|
194 |
title = NULL, |
|
195 |
footnotes = NULL, |
|
196 |
draw = TRUE, |
|
197 |
newpage = TRUE, |
|
198 |
gp = NULL, |
|
199 |
vp = NULL, |
|
200 |
name = NULL, |
|
201 |
font_size = 12, |
|
202 |
ci_ribbon = FALSE, |
|
203 |
ggtheme = nestcolor::theme_nest(), |
|
204 |
annot_at_risk = TRUE, |
|
205 |
annot_at_risk_title = TRUE, |
|
206 |
annot_surv_med = TRUE, |
|
207 |
annot_coxph = FALSE, |
|
208 |
annot_stats = NULL, |
|
209 |
annot_stats_vlines = FALSE, |
|
210 |
control_coxph_pw = control_coxph(), |
|
211 |
ref_group_coxph = NULL, |
|
212 |
annot_coxph_ref_lbls = FALSE, |
|
213 |
position_coxph = c(-0.03, -0.02), |
|
214 |
position_surv_med = c(0.95, 0.9), |
|
215 |
width_annots = list(surv_med = grid::unit(0.3, "npc"), coxph = grid::unit(0.4, "npc"))) { |
|
216 | 9x |
checkmate::assert_list(variables) |
217 | 9x |
checkmate::assert_subset(c("tte", "arm", "is_event"), names(variables)) |
218 | 9x |
checkmate::assert_string(title, null.ok = TRUE) |
219 | 9x |
checkmate::assert_string(footnotes, null.ok = TRUE) |
220 | 9x |
checkmate::assert_character(col, null.ok = TRUE) |
221 | 9x |
checkmate::assert_subset(annot_stats, c("median", "min")) |
222 | 9x |
checkmate::assert_logical(annot_stats_vlines) |
223 | 9x |
checkmate::assert_true(all(sapply(width_annots, grid::is.unit))) |
224 | ||
225 | 9x |
tte <- variables$tte |
226 | 9x |
is_event <- variables$is_event |
227 | 9x |
arm <- variables$arm |
228 | ||
229 | 9x |
assert_valid_factor(df[[arm]]) |
230 | 9x |
assert_df_with_variables(df, list(tte = tte, is_event = is_event, arm = arm)) |
231 | 9x |
checkmate::assert_logical(df[[is_event]], min.len = 1, any.missing = FALSE) |
232 | 9x |
checkmate::assert_numeric(df[[tte]], min.len = 1, any.missing = FALSE) |
233 | ||
234 | 9x |
armval <- as.character(unique(df[[arm]])) |
235 | 9x |
if (annot_coxph && length(armval) < 2) { |
236 | ! |
stop(paste( |
237 | ! |
"When `annot_coxph` = TRUE, `df` must contain at least 2 levels of `variables$arm`", |
238 | ! |
"in order to calculate the hazard ratio." |
239 |
)) |
|
240 | 9x |
} else if (length(armval) > 1) { |
241 | 9x |
armval <- NULL |
242 |
} |
|
243 | 9x |
yval <- match.arg(yval) |
244 | 9x |
formula <- stats::as.formula(paste0("survival::Surv(", tte, ", ", is_event, ") ~ ", arm)) |
245 | 9x |
fit_km <- survival::survfit( |
246 | 9x |
formula = formula, |
247 | 9x |
data = df, |
248 | 9x |
conf.int = control_surv$conf_level, |
249 | 9x |
conf.type = control_surv$conf_type |
250 |
) |
|
251 | 9x |
data_plot <- h_data_plot( |
252 | 9x |
fit_km = fit_km, |
253 | 9x |
armval = armval, |
254 | 9x |
max_time = max_time |
255 |
) |
|
256 | ||
257 | 9x |
xticks <- h_xticks(data = data_plot, xticks = xticks, max_time = max_time) |
258 | 9x |
gg <- h_ggkm( |
259 | 9x |
data = data_plot, |
260 | 9x |
censor_show = censor_show, |
261 | 9x |
pch = pch, |
262 | 9x |
size = size, |
263 | 9x |
xticks = xticks, |
264 | 9x |
xlab = xlab, |
265 | 9x |
yval = yval, |
266 | 9x |
ylab = ylab, |
267 | 9x |
ylim = ylim, |
268 | 9x |
title = title, |
269 | 9x |
footnotes = footnotes, |
270 | 9x |
max_time = max_time, |
271 | 9x |
lwd = lwd, |
272 | 9x |
lty = lty, |
273 | 9x |
col = col, |
274 | 9x |
ggtheme = ggtheme, |
275 | 9x |
ci_ribbon = ci_ribbon |
276 |
) |
|
277 | ||
278 | 9x |
if (!is.null(annot_stats)) { |
279 | ! |
if ("median" %in% annot_stats) { |
280 | ! |
fit_km_all <- survival::survfit( |
281 | ! |
formula = stats::as.formula(paste0("survival::Surv(", tte, ", ", is_event, ") ~ ", 1)), |
282 | ! |
data = df, |
283 | ! |
conf.int = control_surv$conf_level, |
284 | ! |
conf.type = control_surv$conf_type |
285 |
) |
|
286 | ! |
gg <- gg + |
287 | ! |
geom_text( |
288 | ! |
size = 8 / ggplot2::.pt, col = 1, |
289 | ! |
x = stats::median(fit_km_all) + 0.065 * max(data_plot$time), |
290 | ! |
y = ifelse(yval == "Survival", 0.62, 0.38), |
291 | ! |
label = paste("Median F/U:\n", round(stats::median(fit_km_all), 1), tolower(df$AVALU[1])) |
292 |
) |
|
293 | ! |
if (annot_stats_vlines) { |
294 | ! |
gg <- gg + |
295 | ! |
geom_segment(aes(x = stats::median(fit_km_all), xend = stats::median(fit_km_all), y = -Inf, yend = Inf), |
296 | ! |
linetype = 2, col = "darkgray" |
297 |
) |
|
298 |
} |
|
299 |
} |
|
300 | ! |
if ("min" %in% annot_stats) { |
301 | ! |
min_fu <- min(df[[tte]]) |
302 | ! |
gg <- gg + |
303 | ! |
geom_text( |
304 | ! |
size = 8 / ggplot2::.pt, col = 1, |
305 | ! |
x = min_fu + max(data_plot$time) * ifelse(yval == "Survival", 0.05, 0.07), |
306 | ! |
y = ifelse(yval == "Survival", 1.0, 0.05), |
307 | ! |
label = paste("Min. F/U:\n", round(min_fu, 1), tolower(df$AVALU[1])) |
308 |
) |
|
309 | ! |
if (annot_stats_vlines) { |
310 | ! |
gg <- gg + |
311 | ! |
geom_segment(aes(x = min_fu, xend = min_fu, y = Inf, yend = -Inf), linetype = 2, col = "darkgray") |
312 |
} |
|
313 |
} |
|
314 | ! |
gg <- gg + ggplot2::guides(fill = ggplot2::guide_legend(override.aes = list(shape = NA, label = ""))) |
315 |
} |
|
316 | ||
317 | 9x |
g_el <- h_decompose_gg(gg) |
318 | ||
319 | 9x |
if (annot_at_risk) { |
320 |
# This is the content of the table that will be below the graph. |
|
321 | 7x |
annot_tbl <- summary(fit_km, time = xticks) |
322 | 7x |
annot_tbl <- if (is.null(fit_km$strata)) { |
323 | ! |
data.frame( |
324 | ! |
n.risk = annot_tbl$n.risk, |
325 | ! |
time = annot_tbl$time, |
326 | ! |
strata = as.factor(armval) |
327 |
) |
|
328 |
} else { |
|
329 | 7x |
strata_lst <- strsplit(sub("=", "equals", levels(annot_tbl$strata)), "equals") |
330 | 7x |
levels(annot_tbl$strata) <- matrix(unlist(strata_lst), ncol = 2, byrow = TRUE)[, 2] |
331 | 7x |
data.frame( |
332 | 7x |
n.risk = annot_tbl$n.risk, |
333 | 7x |
time = annot_tbl$time, |
334 | 7x |
strata = annot_tbl$strata |
335 |
) |
|
336 |
} |
|
337 | ||
338 | 7x |
grobs_patient <- h_grob_tbl_at_risk( |
339 | 7x |
data = data_plot, |
340 | 7x |
annot_tbl = annot_tbl, |
341 | 7x |
xlim = max(max_time, data_plot$time, xticks), |
342 | 7x |
title = annot_at_risk_title |
343 |
) |
|
344 |
} |
|
345 | ||
346 | 9x |
if (annot_at_risk || annot_surv_med || annot_coxph) { |
347 | 7x |
lyt <- h_km_layout( |
348 | 7x |
data = data_plot, g_el = g_el, title = title, footnotes = footnotes, |
349 | 7x |
annot_at_risk = annot_at_risk, annot_at_risk_title = annot_at_risk_title |
350 |
) |
|
351 | 7x |
at_risk_ttl <- as.numeric(annot_at_risk_title) |
352 | 7x |
ttl_row <- as.numeric(!is.null(title)) |
353 | 7x |
foot_row <- as.numeric(!is.null(footnotes)) |
354 | 7x |
km_grob <- grid::gTree( |
355 | 7x |
vp = grid::viewport(layout = lyt, height = .95, width = .95), |
356 | 7x |
children = grid::gList( |
357 |
# Title. |
|
358 | 7x |
if (ttl_row == 1) { |
359 | 1x |
grid::gTree( |
360 | 1x |
vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2), |
361 | 1x |
children = grid::gList(grid::textGrob(label = title, x = grid::unit(0, "npc"), hjust = 0)) |
362 |
) |
|
363 |
}, |
|
364 | ||
365 |
# The Kaplan - Meier curve (top-right corner). |
|
366 | 7x |
grid::gTree( |
367 | 7x |
vp = grid::viewport(layout.pos.row = 1 + ttl_row, layout.pos.col = 2), |
368 | 7x |
children = grid::gList(g_el$panel) |
369 |
), |
|
370 | ||
371 |
# Survfit summary table (top-right corner). |
|
372 | 7x |
if (annot_surv_med) { |
373 | 6x |
grid::gTree( |
374 | 6x |
vp = grid::viewport(layout.pos.row = 1 + ttl_row, layout.pos.col = 2), |
375 | 6x |
children = h_grob_median_surv( |
376 | 6x |
fit_km = fit_km, |
377 | 6x |
armval = armval, |
378 | 6x |
x = position_surv_med[1], |
379 | 6x |
y = position_surv_med[2], |
380 | 6x |
width = if (!is.null(width_annots[["surv_med"]])) width_annots[["surv_med"]] else grid::unit(0.3, "npc"), |
381 | 6x |
ttheme = gridExtra::ttheme_default(base_size = font_size) |
382 |
) |
|
383 |
) |
|
384 |
}, |
|
385 | 7x |
if (annot_coxph) { |
386 | 2x |
grid::gTree( |
387 | 2x |
vp = grid::viewport(layout.pos.row = 1 + ttl_row, layout.pos.col = 2), |
388 | 2x |
children = h_grob_coxph( |
389 | 2x |
df = df, |
390 | 2x |
variables = variables, |
391 | 2x |
control_coxph_pw = control_coxph_pw, |
392 | 2x |
ref_group_coxph = ref_group_coxph, |
393 | 2x |
annot_coxph_ref_lbls = annot_coxph_ref_lbls, |
394 | 2x |
x = position_coxph[1], |
395 | 2x |
y = position_coxph[2], |
396 | 2x |
width = if (!is.null(width_annots[["coxph"]])) width_annots[["coxph"]] else grid::unit(0.4, "npc"), |
397 | 2x |
ttheme = gridExtra::ttheme_default( |
398 | 2x |
base_size = font_size, |
399 | 2x |
padding = grid::unit(c(1, .5), "lines"), |
400 | 2x |
core = list(bg_params = list(fill = c("grey95", "grey90"), alpha = .5)) |
401 |
) |
|
402 |
) |
|
403 |
) |
|
404 |
}, |
|
405 | ||
406 |
# Add the y-axis annotation (top-left corner). |
|
407 | 7x |
grid::gTree( |
408 | 7x |
vp = grid::viewport(layout.pos.row = 1 + ttl_row, layout.pos.col = 1), |
409 | 7x |
children = h_grob_y_annot(ylab = g_el$ylab, yaxis = g_el$yaxis) |
410 |
), |
|
411 | ||
412 |
# Add the x-axis annotation (second row below the Kaplan Meier Curve). |
|
413 | 7x |
grid::gTree( |
414 | 7x |
vp = grid::viewport(layout.pos.row = 2 + ttl_row, layout.pos.col = 2), |
415 | 7x |
children = grid::gList(rbind(g_el$xaxis, g_el$xlab)) |
416 |
), |
|
417 | ||
418 |
# Add the legend. |
|
419 | 7x |
grid::gTree( |
420 | 7x |
vp = grid::viewport(layout.pos.row = 3 + ttl_row, layout.pos.col = 2), |
421 | 7x |
children = grid::gList(g_el$guide) |
422 |
), |
|
423 | ||
424 |
# Add the table with patient-at-risk numbers. |
|
425 | 7x |
if (annot_at_risk && annot_at_risk_title) { |
426 | 7x |
grid::gTree( |
427 | 7x |
vp = grid::viewport(layout.pos.row = 4 + ttl_row, layout.pos.col = 1), |
428 | 7x |
children = grobs_patient$title |
429 |
) |
|
430 |
}, |
|
431 | 7x |
if (annot_at_risk) { |
432 | 7x |
grid::gTree( |
433 | 7x |
vp = grid::viewport(layout.pos.row = 4 + at_risk_ttl + ttl_row, layout.pos.col = 2), |
434 | 7x |
children = grobs_patient$at_risk |
435 |
) |
|
436 |
}, |
|
437 | 7x |
if (annot_at_risk) { |
438 | 7x |
grid::gTree( |
439 | 7x |
vp = grid::viewport(layout.pos.row = 4 + at_risk_ttl + ttl_row, layout.pos.col = 1), |
440 | 7x |
children = grobs_patient$label |
441 |
) |
|
442 |
}, |
|
443 | 7x |
if (annot_at_risk) { |
444 |
# Add the x-axis for the table. |
|
445 | 7x |
grid::gTree( |
446 | 7x |
vp = grid::viewport(layout.pos.row = 5 + at_risk_ttl + ttl_row, layout.pos.col = 2), |
447 | 7x |
children = grid::gList(rbind(g_el$xaxis, g_el$xlab)) |
448 |
) |
|
449 |
}, |
|
450 | ||
451 |
# Footnotes. |
|
452 | 7x |
if (foot_row == 1) { |
453 | 1x |
grid::gTree( |
454 | 1x |
vp = grid::viewport( |
455 | 1x |
layout.pos.row = ifelse(annot_at_risk, 6 + at_risk_ttl + ttl_row, 4 + ttl_row), |
456 | 1x |
layout.pos.col = 2 |
457 |
), |
|
458 | 1x |
children = grid::gList(grid::textGrob(label = footnotes, x = grid::unit(0, "npc"), hjust = 0)) |
459 |
) |
|
460 |
} |
|
461 |
) |
|
462 |
) |
|
463 | ||
464 | 7x |
result <- grid::gTree( |
465 | 7x |
vp = vp, |
466 | 7x |
gp = gp, |
467 | 7x |
name = name, |
468 | 7x |
children = grid::gList(km_grob) |
469 |
) |
|
470 |
} else { |
|
471 | 2x |
result <- grid::gTree( |
472 | 2x |
vp = vp, |
473 | 2x |
gp = gp, |
474 | 2x |
name = name, |
475 | 2x |
children = grid::gList(ggplot2::ggplotGrob(gg)) |
476 |
) |
|
477 |
} |
|
478 | ||
479 | 9x |
if (newpage && draw) grid::grid.newpage() |
480 | 9x |
if (draw) grid::grid.draw(result) |
481 | 9x |
invisible(result) |
482 |
} |
|
483 | ||
484 |
#' Helper function: tidy survival fit |
|
485 |
#' |
|
486 |
#' @description `r lifecycle::badge("stable")` |
|
487 |
#' |
|
488 |
#' Convert the survival fit data into a data frame designed for plotting |
|
489 |
#' within `g_km`. |
|
490 |
#' |
|
491 |
#' This starts from the [broom::tidy()] result, and then: |
|
492 |
#' * Post-processes the `strata` column into a factor. |
|
493 |
#' * Extends each stratum by an additional first row with time 0 and probability 1 so that |
|
494 |
#' downstream plot lines start at those coordinates. |
|
495 |
#' * Adds a `censor` column. |
|
496 |
#' * Filters the rows before `max_time`. |
|
497 |
#' |
|
498 |
#' @inheritParams g_km |
|
499 |
#' @param fit_km (`survfit`)\cr result of [survival::survfit()]. |
|
500 |
#' @param armval (`string`)\cr used as strata name when treatment arm variable only has one level. Default is `"All"`. |
|
501 |
#' |
|
502 |
#' @return A `tibble` with columns `time`, `n.risk`, `n.event`, `n.censor`, `estimate`, `std.error`, `conf.high`, |
|
503 |
#' `conf.low`, `strata`, and `censor`. |
|
504 |
#' |
|
505 |
#' @examples |
|
506 |
#' \donttest{ |
|
507 |
#' library(dplyr) |
|
508 |
#' library(survival) |
|
509 |
#' |
|
510 |
#' # Test with multiple arms |
|
511 |
#' tern_ex_adtte %>% |
|
512 |
#' filter(PARAMCD == "OS") %>% |
|
513 |
#' survfit(form = Surv(AVAL, 1 - CNSR) ~ ARMCD, data = .) %>% |
|
514 |
#' h_data_plot() |
|
515 |
#' |
|
516 |
#' # Test with single arm |
|
517 |
#' tern_ex_adtte %>% |
|
518 |
#' filter(PARAMCD == "OS", ARMCD == "ARM B") %>% |
|
519 |
#' survfit(form = Surv(AVAL, 1 - CNSR) ~ ARMCD, data = .) %>% |
|
520 |
#' h_data_plot(armval = "ARM B") |
|
521 |
#' } |
|
522 |
#' |
|
523 |
#' @export |
|
524 |
h_data_plot <- function(fit_km, |
|
525 |
armval = "All", |
|
526 |
max_time = NULL) { |
|
527 | 16x |
y <- broom::tidy(fit_km) |
528 | ||
529 | 16x |
if (!is.null(fit_km$strata)) { |
530 | 16x |
fit_km_var_level <- strsplit(sub("=", "equals", names(fit_km$strata)), "equals") |
531 | 16x |
strata_levels <- vapply(fit_km_var_level, FUN = "[", FUN.VALUE = "a", i = 2) |
532 | 16x |
strata_var_level <- strsplit(sub("=", "equals", y$strata), "equals") |
533 | 16x |
y$strata <- factor( |
534 | 16x |
vapply(strata_var_level, FUN = "[", FUN.VALUE = "a", i = 2), |
535 | 16x |
levels = strata_levels |
536 |
) |
|
537 |
} else { |
|
538 | ! |
y$strata <- armval |
539 |
} |
|
540 | ||
541 | 16x |
y_by_strata <- split(y, y$strata) |
542 | 16x |
y_by_strata_extended <- lapply( |
543 | 16x |
y_by_strata, |
544 | 16x |
FUN = function(tbl) { |
545 | 47x |
first_row <- tbl[1L, ] |
546 | 47x |
first_row$time <- 0 |
547 | 47x |
first_row$n.risk <- sum(first_row[, c("n.risk", "n.event", "n.censor")]) |
548 | 47x |
first_row$n.event <- first_row$n.censor <- 0 |
549 | 47x |
first_row$estimate <- first_row$conf.high <- first_row$conf.low <- 1 |
550 | 47x |
first_row$std.error <- 0 |
551 | 47x |
rbind( |
552 | 47x |
first_row, |
553 | 47x |
tbl |
554 |
) |
|
555 |
} |
|
556 |
) |
|
557 | 16x |
y <- do.call(rbind, y_by_strata_extended) |
558 | ||
559 | 16x |
y$censor <- ifelse(y$n.censor > 0, y$estimate, NA) |
560 | 16x |
if (!is.null(max_time)) { |
561 | 3x |
y <- y[y$time <= max(max_time), ] |
562 |
} |
|
563 | 16x |
y |
564 |
} |
|
565 | ||
566 |
#' Helper function: x tick positions |
|
567 |
#' |
|
568 |
#' @description `r lifecycle::badge("stable")` |
|
569 |
#' |
|
570 |
#' Calculate the positions of ticks on the x-axis. However, if `xticks` already |
|
571 |
#' exists it is kept as is. It is based on the same function `ggplot2` relies on, |
|
572 |
#' and is required in the graphic and the patient-at-risk annotation table. |
|
573 |
#' |
|
574 |
#' @inheritParams g_km |
|
575 |
#' @inheritParams h_ggkm |
|
576 |
#' |
|
577 |
#' @return A vector of positions to use for x-axis ticks on a `ggplot` object. |
|
578 |
#' |
|
579 |
#' @examples |
|
580 |
#' \donttest{ |
|
581 |
#' library(dplyr) |
|
582 |
#' library(survival) |
|
583 |
#' |
|
584 |
#' data <- tern_ex_adtte %>% |
|
585 |
#' filter(PARAMCD == "OS") %>% |
|
586 |
#' survfit(form = Surv(AVAL, 1 - CNSR) ~ ARMCD, data = .) %>% |
|
587 |
#' h_data_plot() |
|
588 |
#' |
|
589 |
#' h_xticks(data) |
|
590 |
#' h_xticks(data, xticks = seq(0, 3000, 500)) |
|
591 |
#' h_xticks(data, xticks = 500) |
|
592 |
#' h_xticks(data, xticks = 500, max_time = 6000) |
|
593 |
#' h_xticks(data, xticks = c(0, 500), max_time = 300) |
|
594 |
#' h_xticks(data, xticks = 500, max_time = 300) |
|
595 |
#' } |
|
596 |
#' |
|
597 |
#' @export |
|
598 |
h_xticks <- function(data, xticks = NULL, max_time = NULL) { |
|
599 | 16x |
if (is.null(xticks)) { |
600 | 10x |
if (is.null(max_time)) { |
601 | 8x |
labeling::extended(range(data$time)[1], range(data$time)[2], m = 5) |
602 |
} else { |
|
603 | 2x |
labeling::extended(range(data$time)[1], max(range(data$time)[2], max_time), m = 5) |
604 |
} |
|
605 | 6x |
} else if (checkmate::test_number(xticks)) { |
606 | 3x |
if (is.null(max_time)) { |
607 | 2x |
seq(0, max(data$time), xticks) |
608 |
} else { |
|
609 | 1x |
seq(0, max(data$time, max_time), xticks) |
610 |
} |
|
611 | 3x |
} else if (is.numeric(xticks)) { |
612 | 2x |
xticks |
613 |
} else { |
|
614 | 1x |
stop( |
615 | 1x |
paste( |
616 | 1x |
"xticks should be either `NULL`", |
617 | 1x |
"or a single number (interval between x ticks)", |
618 | 1x |
"or a numeric vector (position of ticks on the x axis)" |
619 |
) |
|
620 |
) |
|
621 |
} |
|
622 |
} |
|
623 | ||
624 |
#' Helper function: KM plot |
|
625 |
#' |
|
626 |
#' @description `r lifecycle::badge("stable")` |
|
627 |
#' |
|
628 |
#' Draw the Kaplan-Meier plot using `ggplot2`. |
|
629 |
#' |
|
630 |
#' @inheritParams g_km |
|
631 |
#' @param data (`data.frame`)\cr survival data as pre-processed by `h_data_plot`. |
|
632 |
#' |
|
633 |
#' @return A `ggplot` object. |
|
634 |
#' |
|
635 |
#' @examples |
|
636 |
#' \donttest{ |
|
637 |
#' library(dplyr) |
|
638 |
#' library(survival) |
|
639 |
#' |
|
640 |
#' fit_km <- tern_ex_adtte %>% |
|
641 |
#' filter(PARAMCD == "OS") %>% |
|
642 |
#' survfit(form = Surv(AVAL, 1 - CNSR) ~ ARMCD, data = .) |
|
643 |
#' data_plot <- h_data_plot(fit_km = fit_km) |
|
644 |
#' xticks <- h_xticks(data = data_plot) |
|
645 |
#' gg <- h_ggkm( |
|
646 |
#' data = data_plot, |
|
647 |
#' censor_show = TRUE, |
|
648 |
#' xticks = xticks, |
|
649 |
#' xlab = "Days", |
|
650 |
#' yval = "Survival", |
|
651 |
#' ylab = "Survival Probability", |
|
652 |
#' title = "Survival" |
|
653 |
#' ) |
|
654 |
#' gg |
|
655 |
#' } |
|
656 |
#' |
|
657 |
#' @export |
|
658 |
h_ggkm <- function(data, |
|
659 |
xticks = NULL, |
|
660 |
yval = "Survival", |
|
661 |
censor_show, |
|
662 |
xlab, |
|
663 |
ylab, |
|
664 |
ylim = NULL, |
|
665 |
title, |
|
666 |
footnotes = NULL, |
|
667 |
max_time = NULL, |
|
668 |
lwd = 1, |
|
669 |
lty = NULL, |
|
670 |
pch = 3, |
|
671 |
size = 2, |
|
672 |
col = NULL, |
|
673 |
ci_ribbon = FALSE, |
|
674 |
ggtheme = nestcolor::theme_nest()) { |
|
675 | 9x |
checkmate::assert_numeric(lty, null.ok = TRUE) |
676 | 9x |
checkmate::assert_character(col, null.ok = TRUE) |
677 | ||
678 | 9x |
if (is.null(ylim)) { |
679 | 9x |
data_lims <- data |
680 | 1x |
if (yval == "Failure") data_lims[["estimate"]] <- 1 - data_lims[["estimate"]] |
681 | 9x |
if (!is.null(max_time)) { |
682 | 1x |
y_lwr <- min(data_lims[data_lims$time < max_time, ][["estimate"]]) |
683 | 1x |
y_upr <- max(data_lims[data_lims$time < max_time, ][["estimate"]]) |
684 |
} else { |
|
685 | 8x |
y_lwr <- min(data_lims[["estimate"]]) |
686 | 8x |
y_upr <- max(data_lims[["estimate"]]) |
687 |
} |
|
688 | 9x |
ylim <- c(y_lwr, y_upr) |
689 |
} |
|
690 | 9x |
checkmate::assert_numeric(ylim, finite = TRUE, any.missing = FALSE, len = 2, sorted = TRUE) |
691 | ||
692 |
# change estimates of survival to estimates of failure (1 - survival) |
|
693 | 9x |
if (yval == "Failure") { |
694 | 1x |
data$estimate <- 1 - data$estimate |
695 | 1x |
data[c("conf.high", "conf.low")] <- list(1 - data$conf.low, 1 - data$conf.high) |
696 | 1x |
data$censor <- 1 - data$censor |
697 |
} |
|
698 | ||
699 | 9x |
gg <- { |
700 | 9x |
ggplot2::ggplot( |
701 | 9x |
data = data, |
702 | 9x |
mapping = ggplot2::aes( |
703 | 9x |
x = .data[["time"]], |
704 | 9x |
y = .data[["estimate"]], |
705 | 9x |
ymin = .data[["conf.low"]], |
706 | 9x |
ymax = .data[["conf.high"]], |
707 | 9x |
color = .data[["strata"]], |
708 | 9x |
fill = .data[["strata"]] |
709 |
) |
|
710 |
) + |
|
711 | 9x |
ggplot2::geom_hline(yintercept = 0) |
712 |
} |
|
713 | ||
714 | 9x |
if (ci_ribbon) { |
715 | 1x |
gg <- gg + ggplot2::geom_ribbon(alpha = .3, lty = 0) |
716 |
} |
|
717 | ||
718 | 9x |
gg <- if (is.null(lty)) { |
719 | 8x |
gg + |
720 | 8x |
ggplot2::geom_step(linewidth = lwd) |
721 | 9x |
} else if (checkmate::test_number(lty)) { |
722 | 1x |
gg + |
723 | 1x |
ggplot2::geom_step(linewidth = lwd, lty = lty) |
724 | 9x |
} else if (is.numeric(lty)) { |
725 | ! |
gg + |
726 | ! |
ggplot2::geom_step(mapping = ggplot2::aes(linetype = .data[["strata"]]), linewidth = lwd) + |
727 | ! |
ggplot2::scale_linetype_manual(values = lty) |
728 |
} |
|
729 | ||
730 | 9x |
gg <- gg + |
731 | 9x |
ggplot2::coord_cartesian(ylim = ylim) + |
732 | 9x |
ggplot2::labs(x = xlab, y = ylab, title = title, caption = footnotes) |
733 | ||
734 | 9x |
if (!is.null(col)) { |
735 | ! |
gg <- gg + |
736 | ! |
ggplot2::scale_color_manual(values = col) + |
737 | ! |
ggplot2::scale_fill_manual(values = col) |
738 |
} |
|
739 | 9x |
if (censor_show) { |
740 | 9x |
dt <- data[data$n.censor != 0, ] |
741 | 9x |
dt$censor_lbl <- factor("Censored") |
742 | ||
743 | 9x |
gg <- gg + ggplot2::geom_point( |
744 | 9x |
data = dt, |
745 | 9x |
ggplot2::aes( |
746 | 9x |
x = .data[["time"]], |
747 | 9x |
y = .data[["censor"]], |
748 | 9x |
shape = .data[["censor_lbl"]] |
749 |
), |
|
750 | 9x |
size = size, |
751 | 9x |
show.legend = TRUE, |
752 | 9x |
inherit.aes = TRUE |
753 |
) + |
|
754 | 9x |
ggplot2::scale_shape_manual(name = NULL, values = pch) + |
755 | 9x |
ggplot2::guides( |
756 | 9x |
shape = ggplot2::guide_legend(override.aes = list(linetype = NA)), |
757 | 9x |
fill = ggplot2::guide_legend(override.aes = list(shape = NA)) |
758 |
) |
|
759 |
} |
|
760 | ||
761 | 9x |
if (!is.null(max_time) && !is.null(xticks)) { |
762 | 1x |
gg <- gg + ggplot2::scale_x_continuous(breaks = xticks, limits = c(min(0, xticks), max(c(xticks, max_time)))) |
763 | 8x |
} else if (!is.null(xticks)) { |
764 | 8x |
if (max(data$time) <= max(xticks)) { |
765 | 7x |
gg <- gg + ggplot2::scale_x_continuous(breaks = xticks, limits = c(min(0, min(xticks)), max(xticks))) |
766 |
} else { |
|
767 | 1x |
gg <- gg + ggplot2::scale_x_continuous(breaks = xticks) |
768 |
} |
|
769 | ! |
} else if (!is.null(max_time)) { |
770 | ! |
gg <- gg + ggplot2::scale_x_continuous(limits = c(0, max_time)) |
771 |
} |
|
772 | ||
773 | 9x |
if (!is.null(ggtheme)) { |
774 | 9x |
gg <- gg + ggtheme |
775 |
} |
|
776 | ||
777 | 9x |
gg + ggplot2::theme( |
778 | 9x |
legend.position = "bottom", |
779 | 9x |
legend.title = ggplot2::element_blank(), |
780 | 9x |
legend.key.height = unit(0.02, "npc"), |
781 | 9x |
panel.grid.major.x = ggplot2::element_line(linewidth = 2) |
782 |
) |
|
783 |
} |
|
784 | ||
785 |
#' `ggplot` Decomposition |
|
786 |
#' |
|
787 |
#' @description `r lifecycle::badge("stable")` |
|
788 |
#' |
|
789 |
#' The elements composing the `ggplot` are extracted and organized in a `list`. |
|
790 |
#' |
|
791 |
#' @param gg (`ggplot`)\cr a graphic to decompose. |
|
792 |
#' |
|
793 |
#' @return A named `list` with elements: |
|
794 |
#' * `panel`: The panel. |
|
795 |
#' * `yaxis`: The y-axis. |
|
796 |
#' * `xaxis`: The x-axis. |
|
797 |
#' * `xlab`: The x-axis label. |
|
798 |
#' * `ylab`: The y-axis label. |
|
799 |
#' * `guide`: The legend. |
|
800 |
#' |
|
801 |
#' @examples |
|
802 |
#' \donttest{ |
|
803 |
#' library(dplyr) |
|
804 |
#' library(survival) |
|
805 |
#' library(grid) |
|
806 |
#' |
|
807 |
#' fit_km <- tern_ex_adtte %>% |
|
808 |
#' filter(PARAMCD == "OS") %>% |
|
809 |
#' survfit(form = Surv(AVAL, 1 - CNSR) ~ ARMCD, data = .) |
|
810 |
#' data_plot <- h_data_plot(fit_km = fit_km) |
|
811 |
#' xticks <- h_xticks(data = data_plot) |
|
812 |
#' gg <- h_ggkm( |
|
813 |
#' data = data_plot, |
|
814 |
#' yval = "Survival", |
|
815 |
#' censor_show = TRUE, |
|
816 |
#' xticks = xticks, xlab = "Days", ylab = "Survival Probability", |
|
817 |
#' title = "tt", |
|
818 |
#' footnotes = "ff" |
|
819 |
#' ) |
|
820 |
#' |
|
821 |
#' g_el <- h_decompose_gg(gg) |
|
822 |
#' grid::grid.newpage() |
|
823 |
#' grid.rect(gp = grid::gpar(lty = 1, col = "red", fill = "gray85", lwd = 5)) |
|
824 |
#' grid::grid.draw(g_el$panel) |
|
825 |
#' |
|
826 |
#' grid::grid.newpage() |
|
827 |
#' grid.rect(gp = grid::gpar(lty = 1, col = "royalblue", fill = "gray85", lwd = 5)) |
|
828 |
#' grid::grid.draw(with(g_el, cbind(ylab, yaxis))) |
|
829 |
#' } |
|
830 |
#' |
|
831 |
#' @export |
|
832 |
h_decompose_gg <- function(gg) { |
|
833 | 9x |
g_el <- ggplot2::ggplotGrob(gg) |
834 | 9x |
y <- c( |
835 | 9x |
panel = "panel", |
836 | 9x |
yaxis = "axis-l", |
837 | 9x |
xaxis = "axis-b", |
838 | 9x |
xlab = "xlab-b", |
839 | 9x |
ylab = "ylab-l", |
840 | 9x |
guide = "guide" |
841 |
) |
|
842 | 9x |
lapply(X = y, function(x) gtable::gtable_filter(g_el, x)) |
843 |
} |
|
844 | ||
845 |
#' Helper: KM Layout |
|
846 |
#' |
|
847 |
#' @description `r lifecycle::badge("stable")` |
|
848 |
#' |
|
849 |
#' Prepares a (5 rows) x (2 cols) layout for the Kaplan-Meier curve. |
|
850 |
#' |
|
851 |
#' @inheritParams g_km |
|
852 |
#' @inheritParams h_ggkm |
|
853 |
#' @param g_el (`list` of `gtable`)\cr list as obtained by `h_decompose_gg()`. |
|
854 |
#' @param annot_at_risk (`flag`)\cr compute and add the annotation table reporting the number of |
|
855 |
#' patient at risk matching the main grid of the Kaplan-Meier curve. |
|
856 |
#' |
|
857 |
#' @return A grid layout. |
|
858 |
#' |
|
859 |
#' @details The layout corresponds to a grid of two columns and five rows of unequal dimensions. Most of the |
|
860 |
#' dimension are fixed, only the curve is flexible and will accommodate with the remaining free space. |
|
861 |
#' * The left column gets the annotation of the `ggplot` (y-axis) and the names of the strata for the patient |
|
862 |
#' at risk tabulation. The main constraint is about the width of the columns which must allow the writing of |
|
863 |
#' the strata name. |
|
864 |
#' * The right column receive the `ggplot`, the legend, the x-axis and the patient at risk table. |
|
865 |
#' |
|
866 |
#' @examples |
|
867 |
#' \donttest{ |
|
868 |
#' library(dplyr) |
|
869 |
#' library(survival) |
|
870 |
#' library(grid) |
|
871 |
#' |
|
872 |
#' fit_km <- tern_ex_adtte %>% |
|
873 |
#' filter(PARAMCD == "OS") %>% |
|
874 |
#' survfit(form = Surv(AVAL, 1 - CNSR) ~ ARMCD, data = .) |
|
875 |
#' data_plot <- h_data_plot(fit_km = fit_km) |
|
876 |
#' xticks <- h_xticks(data = data_plot) |
|
877 |
#' gg <- h_ggkm( |
|
878 |
#' data = data_plot, |
|
879 |
#' censor_show = TRUE, |
|
880 |
#' xticks = xticks, xlab = "Days", ylab = "Survival Probability", |
|
881 |
#' title = "tt", footnotes = "ff", yval = "Survival" |
|
882 |
#' ) |
|
883 |
#' g_el <- h_decompose_gg(gg) |
|
884 |
#' lyt <- h_km_layout(data = data_plot, g_el = g_el, title = "t", footnotes = "f") |
|
885 |
#' grid.show.layout(lyt) |
|
886 |
#' } |
|
887 |
#' |
|
888 |
#' @export |
|
889 |
h_km_layout <- function(data, g_el, title, footnotes, annot_at_risk = TRUE, annot_at_risk_title = TRUE) { |
|
890 | 7x |
txtlines <- levels(as.factor(data$strata)) |
891 | 7x |
nlines <- nlevels(as.factor(data$strata)) |
892 | 7x |
col_annot_width <- max( |
893 | 7x |
c( |
894 | 7x |
as.numeric(grid::convertX(g_el$yaxis$width + g_el$ylab$width, "pt")), |
895 | 7x |
as.numeric( |
896 | 7x |
grid::convertX( |
897 | 7x |
grid::stringWidth(txtlines) + grid::unit(7, "pt"), "pt" |
898 |
) |
|
899 |
) |
|
900 |
) |
|
901 |
) |
|
902 | ||
903 | 7x |
ttl_row <- as.numeric(!is.null(title)) |
904 | 7x |
foot_row <- as.numeric(!is.null(footnotes)) |
905 | 7x |
no_tbl_ind <- c() |
906 | 7x |
ht_x <- c() |
907 | 7x |
ht_units <- c() |
908 | ||
909 | 7x |
if (ttl_row == 1) { |
910 | 1x |
no_tbl_ind <- c(no_tbl_ind, TRUE) |
911 | 1x |
ht_x <- c(ht_x, 2) |
912 | 1x |
ht_units <- c(ht_units, "lines") |
913 |
} |
|
914 | ||
915 | 7x |
no_tbl_ind <- c(no_tbl_ind, rep(TRUE, 3), rep(FALSE, 2)) |
916 | 7x |
ht_x <- c( |
917 | 7x |
ht_x, |
918 | 7x |
1, |
919 | 7x |
grid::convertX(with(g_el, xaxis$height + ylab$width), "pt") + grid::unit(5, "pt"), |
920 | 7x |
grid::convertX(g_el$guide$heights, "pt") + grid::unit(2, "pt"), |
921 | 7x |
1, |
922 | 7x |
nlines + 0.5, |
923 | 7x |
grid::convertX(with(g_el, xaxis$height + ylab$width), "pt") |
924 |
) |
|
925 | 7x |
ht_units <- c( |
926 | 7x |
ht_units, |
927 | 7x |
"null", |
928 | 7x |
"pt", |
929 | 7x |
"pt", |
930 | 7x |
"lines", |
931 | 7x |
"lines", |
932 | 7x |
"pt" |
933 |
) |
|
934 | ||
935 | 7x |
if (foot_row == 1) { |
936 | 1x |
no_tbl_ind <- c(no_tbl_ind, TRUE) |
937 | 1x |
ht_x <- c(ht_x, 1) |
938 | 1x |
ht_units <- c(ht_units, "lines") |
939 |
} |
|
940 | 7x |
if (annot_at_risk) { |
941 | 7x |
no_at_risk_tbl <- rep(TRUE, 6 + ttl_row + foot_row) |
942 | 7x |
if (!annot_at_risk_title) { |
943 | ! |
no_at_risk_tbl[length(no_at_risk_tbl) - 2 - foot_row] <- FALSE |
944 |
} |
|
945 |
} else { |
|
946 | ! |
no_at_risk_tbl <- no_tbl_ind |
947 |
} |
|
948 | ||
949 | 7x |
grid::grid.layout( |
950 | 7x |
nrow = sum(no_at_risk_tbl), ncol = 2, |
951 | 7x |
widths = grid::unit(c(col_annot_width, 1), c("pt", "null")), |
952 | 7x |
heights = grid::unit( |
953 | 7x |
x = ht_x[no_at_risk_tbl], |
954 | 7x |
units = ht_units[no_at_risk_tbl] |
955 |
) |
|
956 |
) |
|
957 |
} |
|
958 | ||
959 |
#' Helper: Patient-at-Risk Grobs |
|
960 |
#' |
|
961 |
#' @description `r lifecycle::badge("stable")` |
|
962 |
#' |
|
963 |
#' Two graphical objects are obtained, one corresponding to row labeling and the second to the table of |
|
964 |
#' numbers of patients at risk. If `title = TRUE`, a third object corresponding to the table title is |
|
965 |
#' also obtained. |
|
966 |
#' |
|
967 |
#' @inheritParams g_km |
|
968 |
#' @inheritParams h_ggkm |
|
969 |
#' @param annot_tbl (`data.frame`)\cr annotation as prepared by [survival::summary.survfit()] which |
|
970 |
#' includes the number of patients at risk at given time points. |
|
971 |
#' @param xlim (`numeric`)\cr the maximum value on the x-axis (used to |
|
972 |
#' ensure the at risk table aligns with the KM graph). |
|
973 |
#' @param title (`flag`)\cr whether the "Patients at Risk" title should be added above the `annot_at_risk` |
|
974 |
#' table. Has no effect if `annot_at_risk` is `FALSE`. Defaults to `TRUE`. |
|
975 |
#' |
|
976 |
#' @return A named `list` of two `gTree` objects if `title = FALSE`: `at_risk` and `label`, or three |
|
977 |
#' `gTree` objects if `title = TRUE`: `at_risk`, `label`, and `title`. |
|
978 |
#' |
|
979 |
#' @examples |
|
980 |
#' \donttest{ |
|
981 |
#' library(dplyr) |
|
982 |
#' library(survival) |
|
983 |
#' library(grid) |
|
984 |
#' |
|
985 |
#' fit_km <- tern_ex_adtte %>% |
|
986 |
#' filter(PARAMCD == "OS") %>% |
|
987 |
#' survfit(form = Surv(AVAL, 1 - CNSR) ~ ARMCD, data = .) |
|
988 |
#' |
|
989 |
#' data_plot <- h_data_plot(fit_km = fit_km) |
|
990 |
#' |
|
991 |
#' xticks <- h_xticks(data = data_plot) |
|
992 |
#' |
|
993 |
#' gg <- h_ggkm( |
|
994 |
#' data = data_plot, |
|
995 |
#' censor_show = TRUE, |
|
996 |
#' xticks = xticks, xlab = "Days", ylab = "Survival Probability", |
|
997 |
#' title = "tt", footnotes = "ff", yval = "Survival" |
|
998 |
#' ) |
|
999 |
#' |
|
1000 |
#' # The annotation table reports the patient at risk for a given strata and |
|
1001 |
#' # time (`xticks`). |
|
1002 |
#' annot_tbl <- summary(fit_km, time = xticks) |
|
1003 |
#' if (is.null(fit_km$strata)) { |
|
1004 |
#' annot_tbl <- with(annot_tbl, data.frame(n.risk = n.risk, time = time, strata = "All")) |
|
1005 |
#' } else { |
|
1006 |
#' strata_lst <- strsplit(sub("=", "equals", levels(annot_tbl$strata)), "equals") |
|
1007 |
#' levels(annot_tbl$strata) <- matrix(unlist(strata_lst), ncol = 2, byrow = TRUE)[, 2] |
|
1008 |
#' annot_tbl <- data.frame( |
|
1009 |
#' n.risk = annot_tbl$n.risk, |
|
1010 |
#' time = annot_tbl$time, |
|
1011 |
#' strata = annot_tbl$strata |
|
1012 |
#' ) |
|
1013 |
#' } |
|
1014 |
#' |
|
1015 |
#' # The annotation table is transformed into a grob. |
|
1016 |
#' tbl <- h_grob_tbl_at_risk(data = data_plot, annot_tbl = annot_tbl, xlim = max(xticks)) |
|
1017 |
#' |
|
1018 |
#' # For the representation, the layout is estimated for which the decomposition |
|
1019 |
#' # of the graphic element is necessary. |
|
1020 |
#' g_el <- h_decompose_gg(gg) |
|
1021 |
#' lyt <- h_km_layout(data = data_plot, g_el = g_el, title = "t", footnotes = "f") |
|
1022 |
#' |
|
1023 |
#' grid::grid.newpage() |
|
1024 |
#' pushViewport(viewport(layout = lyt, height = .95, width = .95)) |
|
1025 |
#' grid.rect(gp = grid::gpar(lty = 1, col = "purple", fill = "gray85", lwd = 1)) |
|
1026 |
#' pushViewport(viewport(layout.pos.row = 3:4, layout.pos.col = 2)) |
|
1027 |
#' grid.rect(gp = grid::gpar(lty = 1, col = "orange", fill = "gray85", lwd = 1)) |
|
1028 |
#' grid::grid.draw(tbl$at_risk) |
|
1029 |
#' popViewport() |
|
1030 |
#' pushViewport(viewport(layout.pos.row = 3:4, layout.pos.col = 1)) |
|
1031 |
#' grid.rect(gp = grid::gpar(lty = 1, col = "green3", fill = "gray85", lwd = 1)) |
|
1032 |
#' grid::grid.draw(tbl$label) |
|
1033 |
#' } |
|
1034 |
#' |
|
1035 |
#' @export |
|
1036 |
h_grob_tbl_at_risk <- function(data, annot_tbl, xlim, title = TRUE) { |
|
1037 | 7x |
txtlines <- levels(as.factor(data$strata)) |
1038 | 7x |
nlines <- nlevels(as.factor(data$strata)) |
1039 | 7x |
y_int <- annot_tbl$time[2] - annot_tbl$time[1] |
1040 | 7x |
annot_tbl <- expand.grid( |
1041 | 7x |
time = seq(0, xlim, y_int), |
1042 | 7x |
strata = unique(annot_tbl$strata) |
1043 | 7x |
) %>% dplyr::left_join(annot_tbl, by = c("time", "strata")) |
1044 | 7x |
annot_tbl[is.na(annot_tbl)] <- 0 |
1045 | 7x |
y_str_unit <- as.numeric(annot_tbl$strata) |
1046 | 7x |
vp_table <- grid::plotViewport(margins = grid::unit(c(0, 0, 0, 0), "lines")) |
1047 | 7x |
if (title) { |
1048 | 7x |
gb_table_title <- grid::gList( |
1049 | 7x |
grid::textGrob( |
1050 | 7x |
label = "Patients at Risk:", |
1051 | 7x |
x = 1, |
1052 | 7x |
y = grid::unit(0.2, "native"), |
1053 | 7x |
gp = grid::gpar(fontface = "bold", fontsize = 10) |
1054 |
) |
|
1055 |
) |
|
1056 |
} |
|
1057 | 7x |
gb_table_left_annot <- grid::gList( |
1058 | 7x |
grid::rectGrob( |
1059 | 7x |
x = 0, y = grid::unit(c(1:nlines) - 1, "lines"), |
1060 | 7x |
gp = grid::gpar(fill = c("gray95", "gray90"), alpha = 1, col = "white"), |
1061 | 7x |
height = grid::unit(1, "lines"), just = "bottom", hjust = 0 |
1062 |
), |
|
1063 | 7x |
grid::textGrob( |
1064 | 7x |
label = unique(annot_tbl$strata), |
1065 | 7x |
x = 0.5, |
1066 | 7x |
y = grid::unit( |
1067 | 7x |
(max(unique(y_str_unit)) - unique(y_str_unit)) + 0.75, |
1068 | 7x |
"native" |
1069 |
), |
|
1070 | 7x |
gp = grid::gpar(fontface = "italic", fontsize = 10) |
1071 |
) |
|
1072 |
) |
|
1073 | 7x |
gb_patient_at_risk <- grid::gList( |
1074 | 7x |
grid::rectGrob( |
1075 | 7x |
x = 0, y = grid::unit(c(1:nlines) - 1, "lines"), |
1076 | 7x |
gp = grid::gpar(fill = c("gray95", "gray90"), alpha = 1, col = "white"), |
1077 | 7x |
height = grid::unit(1, "lines"), just = "bottom", hjust = 0 |
1078 |
), |
|
1079 | 7x |
grid::textGrob( |
1080 | 7x |
label = annot_tbl$n.risk, |
1081 | 7x |
x = grid::unit(annot_tbl$time, "native"), |
1082 | 7x |
y = grid::unit( |
1083 | 7x |
(max(y_str_unit) - y_str_unit) + .5, |
1084 | 7x |
"line" |
1085 | 7x |
) # maybe native |
1086 |
) |
|
1087 |
) |
|
1088 | ||
1089 | 7x |
ret <- list( |
1090 | 7x |
at_risk = grid::gList( |
1091 | 7x |
grid::gTree( |
1092 | 7x |
vp = vp_table, |
1093 | 7x |
children = grid::gList( |
1094 | 7x |
grid::gTree( |
1095 | 7x |
vp = grid::dataViewport( |
1096 | 7x |
xscale = c(0, xlim) + c(-0.05, 0.05) * xlim, |
1097 | 7x |
yscale = c(0, nlines + 1), |
1098 | 7x |
extension = c(0.05, 0) |
1099 |
), |
|
1100 | 7x |
children = grid::gList(gb_patient_at_risk) |
1101 |
) |
|
1102 |
) |
|
1103 |
) |
|
1104 |
), |
|
1105 | 7x |
label = grid::gList( |
1106 | 7x |
grid::gTree( |
1107 | 7x |
vp = grid::viewport(width = max(grid::stringWidth(txtlines))), |
1108 | 7x |
children = grid::gList( |
1109 | 7x |
grid::gTree( |
1110 | 7x |
vp = grid::dataViewport( |
1111 | 7x |
xscale = 0:1, |
1112 | 7x |
yscale = c(0, nlines + 1), |
1113 | 7x |
extension = c(0.0, 0) |
1114 |
), |
|
1115 | 7x |
children = grid::gList(gb_table_left_annot) |
1116 |
) |
|
1117 |
) |
|
1118 |
) |
|
1119 |
) |
|
1120 |
) |
|
1121 | ||
1122 | 7x |
if (title) { |
1123 | 7x |
ret[["title"]] <- grid::gList( |
1124 | 7x |
grid::gTree( |
1125 | 7x |
vp = grid::viewport(width = max(grid::stringWidth(txtlines))), |
1126 | 7x |
children = grid::gList( |
1127 | 7x |
grid::gTree( |
1128 | 7x |
vp = grid::dataViewport( |
1129 | 7x |
xscale = 0:1, |
1130 | 7x |
yscale = c(0, 1), |
1131 | 7x |
extension = c(0, 0) |
1132 |
), |
|
1133 | 7x |
children = grid::gList(gb_table_title) |
1134 |
) |
|
1135 |
) |
|
1136 |
) |
|
1137 |
) |
|
1138 |
} |
|
1139 | ||
1140 | 7x |
ret |
1141 |
} |
|
1142 | ||
1143 |
#' Helper Function: Survival Estimations |
|
1144 |
#' |
|
1145 |
#' @description `r lifecycle::badge("stable")` |
|
1146 |
#' |
|
1147 |
#' Transform a survival fit to a table with groups in rows characterized by N, median and confidence interval. |
|
1148 |
#' |
|
1149 |
#' @inheritParams h_data_plot |
|
1150 |
#' |
|
1151 |
#' @return A summary table with statistics `N`, `Median`, and `XX% CI` (`XX` taken from `fit_km`). |
|
1152 |
#' |
|
1153 |
#' @examples |
|
1154 |
#' \donttest{ |
|
1155 |
#' library(dplyr) |
|
1156 |
#' library(survival) |
|
1157 |
#' |
|
1158 |
#' adtte <- tern_ex_adtte %>% filter(PARAMCD == "OS") |
|
1159 |
#' fit <- survfit( |
|
1160 |
#' form = Surv(AVAL, 1 - CNSR) ~ ARMCD, |
|
1161 |
#' data = adtte |
|
1162 |
#' ) |
|
1163 |
#' h_tbl_median_surv(fit_km = fit) |
|
1164 |
#' } |
|
1165 |
#' |
|
1166 |
#' @export |
|
1167 |
h_tbl_median_surv <- function(fit_km, armval = "All") { |
|
1168 | 7x |
y <- if (is.null(fit_km$strata)) { |
1169 | ! |
as.data.frame(t(summary(fit_km)$table), row.names = armval) |
1170 |
} else { |
|
1171 | 7x |
tbl <- summary(fit_km)$table |
1172 | 7x |
rownames_lst <- strsplit(sub("=", "equals", rownames(tbl)), "equals") |
1173 | 7x |
rownames(tbl) <- matrix(unlist(rownames_lst), ncol = 2, byrow = TRUE)[, 2] |
1174 | 7x |
as.data.frame(tbl) |
1175 |
} |
|
1176 | 7x |
conf.int <- summary(fit_km)$conf.int # nolint |
1177 | 7x |
y$records <- round(y$records) |
1178 | 7x |
y$median <- signif(y$median, 4) |
1179 | 7x |
y$`CI` <- paste0( |
1180 | 7x |
"(", signif(y[[paste0(conf.int, "LCL")]], 4), ", ", signif(y[[paste0(conf.int, "UCL")]], 4), ")" |
1181 |
) |
|
1182 | 7x |
stats::setNames( |
1183 | 7x |
y[c("records", "median", "CI")], |
1184 | 7x |
c("N", "Median", f_conf_level(conf.int)) |
1185 |
) |
|
1186 |
} |
|
1187 | ||
1188 |
#' Helper Function: Survival Estimation Grob |
|
1189 |
#' |
|
1190 |
#' @description `r lifecycle::badge("stable")` |
|
1191 |
#' |
|
1192 |
#' The survival fit is transformed in a grob containing a table with groups in |
|
1193 |
#' rows characterized by N, median and 95% confidence interval. |
|
1194 |
#' |
|
1195 |
#' @inheritParams g_km |
|
1196 |
#' @inheritParams h_data_plot |
|
1197 |
#' @param ttheme (`list`)\cr see [gridExtra::ttheme_default()]. |
|
1198 |
#' @param x (`numeric`)\cr a value between 0 and 1 specifying x-location. |
|
1199 |
#' @param y (`numeric`)\cr a value between 0 and 1 specifying y-location. |
|
1200 |
#' @param width (`unit`)\cr width (as a unit) to use when printing the grob. |
|
1201 |
#' |
|
1202 |
#' @return A `grob` of a table containing statistics `N`, `Median`, and `XX% CI` (`XX` taken from `fit_km`). |
|
1203 |
#' |
|
1204 |
#' @examples |
|
1205 |
#' \donttest{ |
|
1206 |
#' library(dplyr) |
|
1207 |
#' library(survival) |
|
1208 |
#' library(grid) |
|
1209 |
#' |
|
1210 |
#' grid::grid.newpage() |
|
1211 |
#' grid.rect(gp = grid::gpar(lty = 1, col = "pink", fill = "gray85", lwd = 1)) |
|
1212 |
#' tern_ex_adtte %>% |
|
1213 |
#' filter(PARAMCD == "OS") %>% |
|
1214 |
#' survfit(form = Surv(AVAL, 1 - CNSR) ~ ARMCD, data = .) %>% |
|
1215 |
#' h_grob_median_surv() %>% |
|
1216 |
#' grid::grid.draw() |
|
1217 |
#' } |
|
1218 |
#' |
|
1219 |
#' @export |
|
1220 |
h_grob_median_surv <- function(fit_km, |
|
1221 |
armval = "All", |
|
1222 |
x = 0.9, |
|
1223 |
y = 0.9, |
|
1224 |
width = grid::unit(0.3, "npc"), |
|
1225 |
ttheme = gridExtra::ttheme_default()) { |
|
1226 | 6x |
data <- h_tbl_median_surv(fit_km, armval = armval) |
1227 | ||
1228 | 6x |
width <- grid::convertUnit(grid::unit(as.numeric(width), grid::unitType(width)), "in") |
1229 | 6x |
height <- width * (nrow(data) + 1) / 12 |
1230 | ||
1231 | 6x |
w <- paste(" ", c( |
1232 | 6x |
rownames(data)[which.max(nchar(rownames(data)))], |
1233 | 6x |
sapply(names(data), function(x) c(x, data[[x]])[which.max(nchar(c(x, data[[x]])))]) |
1234 |
)) |
|
1235 | 6x |
w_unit <- grid::convertWidth(grid::stringWidth(w), "in", valueOnly = TRUE) |
1236 | ||
1237 | 6x |
w_txt <- sapply(1:64, function(x) { |
1238 | 384x |
graphics::par(ps = x) |
1239 | 384x |
graphics::strwidth(w[4], units = "in") |
1240 |
}) |
|
1241 | 6x |
f_size_w <- which.max(w_txt[w_txt < as.numeric((w_unit / sum(w_unit)) * width)[4]]) |
1242 | ||
1243 | 6x |
h_txt <- sapply(1:64, function(x) { |
1244 | 384x |
graphics::par(ps = x) |
1245 | 384x |
graphics::strheight(grid::stringHeight("X"), units = "in") |
1246 |
}) |
|
1247 | 6x |
f_size_h <- which.max(h_txt[h_txt < as.numeric(grid::unit(as.numeric(height) / 4, grid::unitType(height)))]) |
1248 | ||
1249 | 6x |
if (ttheme$core$fg_params$fontsize == 12) { |
1250 | 6x |
ttheme$core$fg_params$fontsize <- min(f_size_w, f_size_h) |
1251 | 6x |
ttheme$colhead$fg_params$fontsize <- min(f_size_w, f_size_h) |
1252 | 6x |
ttheme$rowhead$fg_params$fontsize <- min(f_size_w, f_size_h) |
1253 |
} |
|
1254 | ||
1255 | 6x |
gt <- gridExtra::tableGrob( |
1256 | 6x |
d = data, |
1257 | 6x |
theme = ttheme |
1258 |
) |
|
1259 | 6x |
gt$widths <- ((w_unit / sum(w_unit)) * width) |
1260 | 6x |
gt$heights <- rep(grid::unit(as.numeric(height) / 4, grid::unitType(height)), nrow(gt)) |
1261 | ||
1262 | 6x |
vp <- grid::viewport( |
1263 | 6x |
x = grid::unit(x, "npc") + grid::unit(1, "lines"), |
1264 | 6x |
y = grid::unit(y, "npc") + grid::unit(1.5, "lines"), |
1265 | 6x |
height = height, |
1266 | 6x |
width = width, |
1267 | 6x |
just = c("right", "top") |
1268 |
) |
|
1269 | ||
1270 | 6x |
grid::gList( |
1271 | 6x |
grid::gTree( |
1272 | 6x |
vp = vp, |
1273 | 6x |
children = grid::gList(gt) |
1274 |
) |
|
1275 |
) |
|
1276 |
} |
|
1277 | ||
1278 |
#' Helper: Grid Object with y-axis Annotation |
|
1279 |
#' |
|
1280 |
#' @description `r lifecycle::badge("stable")` |
|
1281 |
#' |
|
1282 |
#' Build the y-axis annotation from a decomposed `ggplot`. |
|
1283 |
#' |
|
1284 |
#' @param ylab (`gtable`)\cr the y-lab as a graphical object derived from a `ggplot`. |
|
1285 |
#' @param yaxis (`gtable`)\cr the y-axis as a graphical object derived from a `ggplot`. |
|
1286 |
#' |
|
1287 |
#' @return a `gTree` object containing the y-axis annotation from a `ggplot`. |
|
1288 |
#' |
|
1289 |
#' @examples |
|
1290 |
#' \donttest{ |
|
1291 |
#' library(dplyr) |
|
1292 |
#' library(survival) |
|
1293 |
#' library(grid) |
|
1294 |
#' |
|
1295 |
#' fit_km <- tern_ex_adtte %>% |
|
1296 |
#' filter(PARAMCD == "OS") %>% |
|
1297 |
#' survfit(form = Surv(AVAL, 1 - CNSR) ~ ARMCD, data = .) |
|
1298 |
#' data_plot <- h_data_plot(fit_km = fit_km) |
|
1299 |
#' xticks <- h_xticks(data = data_plot) |
|
1300 |
#' gg <- h_ggkm( |
|
1301 |
#' data = data_plot, |
|
1302 |
#' censor_show = TRUE, |
|
1303 |
#' xticks = xticks, xlab = "Days", ylab = "Survival Probability", |
|
1304 |
#' title = "title", footnotes = "footnotes", yval = "Survival" |
|
1305 |
#' ) |
|
1306 |
#' |
|
1307 |
#' g_el <- h_decompose_gg(gg) |
|
1308 |
#' |
|
1309 |
#' grid::grid.newpage() |
|
1310 |
#' pvp <- grid::plotViewport(margins = c(5, 4, 2, 20)) |
|
1311 |
#' pushViewport(pvp) |
|
1312 |
#' grid::grid.draw(h_grob_y_annot(ylab = g_el$ylab, yaxis = g_el$yaxis)) |
|
1313 |
#' grid.rect(gp = grid::gpar(lty = 1, col = "gray35", fill = NA)) |
|
1314 |
#' } |
|
1315 |
#' |
|
1316 |
#' @export |
|
1317 |
h_grob_y_annot <- function(ylab, yaxis) { |
|
1318 | 7x |
grid::gList( |
1319 | 7x |
grid::gTree( |
1320 | 7x |
vp = grid::viewport( |
1321 | 7x |
width = grid::convertX(yaxis$width + ylab$width, "pt"), |
1322 | 7x |
x = grid::unit(1, "npc"), |
1323 | 7x |
just = "right" |
1324 |
), |
|
1325 | 7x |
children = grid::gList(cbind(ylab, yaxis)) |
1326 |
) |
|
1327 |
) |
|
1328 |
} |
|
1329 | ||
1330 |
#' Helper Function: Pairwise `CoxPH` table |
|
1331 |
#' |
|
1332 |
#' @description `r lifecycle::badge("stable")` |
|
1333 |
#' |
|
1334 |
#' Create a `data.frame` of pairwise stratified or unstratified `CoxPH` analysis results. |
|
1335 |
#' |
|
1336 |
#' @inheritParams g_km |
|
1337 |
#' |
|
1338 |
#' @return A `data.frame` containing statistics `HR`, `XX% CI` (`XX` taken from `control_coxph_pw`), |
|
1339 |
#' and `p-value (log-rank)`. |
|
1340 |
#' |
|
1341 |
#' @examples |
|
1342 |
#' \donttest{ |
|
1343 |
#' library(dplyr) |
|
1344 |
#' |
|
1345 |
#' adtte <- tern_ex_adtte %>% |
|
1346 |
#' filter(PARAMCD == "OS") %>% |
|
1347 |
#' mutate(is_event = CNSR == 0) |
|
1348 |
#' |
|
1349 |
#' h_tbl_coxph_pairwise( |
|
1350 |
#' df = adtte, |
|
1351 |
#' variables = list(tte = "AVAL", is_event = "is_event", arm = "ARM"), |
|
1352 |
#' control_coxph_pw = control_coxph(conf_level = 0.9) |
|
1353 |
#' ) |
|
1354 |
#' } |
|
1355 |
#' |
|
1356 |
#' @export |
|
1357 |
h_tbl_coxph_pairwise <- function(df, |
|
1358 |
variables, |
|
1359 |
ref_group_coxph = NULL, |
|
1360 |
control_coxph_pw = control_coxph(), |
|
1361 |
annot_coxph_ref_lbls = FALSE) { |
|
1362 | 4x |
assert_df_with_variables(df, variables) |
1363 | 4x |
checkmate::assert_choice(ref_group_coxph, levels(df[[variables$arm]]), null.ok = TRUE) |
1364 | 4x |
checkmate::assert_flag(annot_coxph_ref_lbls) |
1365 | ||
1366 | 4x |
arm <- variables$arm |
1367 | 4x |
df[[arm]] <- factor(df[[arm]]) |
1368 | ||
1369 | 4x |
ref_group <- if (!is.null(ref_group_coxph)) ref_group_coxph else levels(df[[variables$arm]])[1] |
1370 | 4x |
comp_group <- setdiff(levels(df[[arm]]), ref_group) |
1371 | ||
1372 | 4x |
results <- Map(function(comp) { |
1373 | 8x |
res <- s_coxph_pairwise( |
1374 | 8x |
df = df[df[[arm]] == comp, , drop = FALSE], |
1375 | 8x |
.ref_group = df[df[[arm]] == ref_group, , drop = FALSE], |
1376 | 8x |
.in_ref_col = FALSE, |
1377 | 8x |
.var = variables$tte, |
1378 | 8x |
is_event = variables$is_event, |
1379 | 8x |
strat = variables$strat, |
1380 | 8x |
control = control_coxph_pw |
1381 |
) |
|
1382 | 8x |
res_df <- data.frame( |
1383 | 8x |
hr = format(round(res$hr, 2), nsmall = 2), |
1384 | 8x |
hr_ci = paste0( |
1385 | 8x |
"(", format(round(res$hr_ci[1], 2), nsmall = 2), ", ", |
1386 | 8x |
format(round(res$hr_ci[2], 2), nsmall = 2), ")" |
1387 |
), |
|
1388 | 8x |
pvalue = if (res$pvalue < 0.0001) "<0.0001" else format(round(res$pvalue, 4), 4), |
1389 | 8x |
stringsAsFactors = FALSE |
1390 |
) |
|
1391 | 8x |
colnames(res_df) <- c("HR", vapply(res[c("hr_ci", "pvalue")], obj_label, FUN.VALUE = "character")) |
1392 | 8x |
row.names(res_df) <- comp |
1393 | 8x |
res_df |
1394 | 4x |
}, comp_group) |
1395 | 1x |
if (annot_coxph_ref_lbls) names(results) <- paste(comp_group, "vs.", ref_group) |
1396 | ||
1397 | 4x |
do.call(rbind, results) |
1398 |
} |
|
1399 | ||
1400 |
#' Helper Function: `CoxPH` Grob |
|
1401 |
#' |
|
1402 |
#' @description `r lifecycle::badge("stable")` |
|
1403 |
#' |
|
1404 |
#' Grob of `rtable` output from [h_tbl_coxph_pairwise()] |
|
1405 |
#' |
|
1406 |
#' @inheritParams h_grob_median_surv |
|
1407 |
#' @param ... arguments will be passed to [h_tbl_coxph_pairwise()]. |
|
1408 |
#' @param x (`numeric`)\cr a value between 0 and 1 specifying x-location. |
|
1409 |
#' @param y (`numeric`)\cr a value between 0 and 1 specifying y-location. |
|
1410 |
#' @param width (`unit`)\cr width (as a unit) to use when printing the grob. |
|
1411 |
#' |
|
1412 |
#' @return A `grob` of a table containing statistics `HR`, `XX% CI` (`XX` taken from `control_coxph_pw`), |
|
1413 |
#' and `p-value (log-rank)`. |
|
1414 |
#' |
|
1415 |
#' @examples |
|
1416 |
#' \donttest{ |
|
1417 |
#' library(dplyr) |
|
1418 |
#' library(survival) |
|
1419 |
#' library(grid) |
|
1420 |
#' |
|
1421 |
#' grid::grid.newpage() |
|
1422 |
#' grid.rect(gp = grid::gpar(lty = 1, col = "pink", fill = "gray85", lwd = 1)) |
|
1423 |
#' data <- tern_ex_adtte %>% |
|
1424 |
#' filter(PARAMCD == "OS") %>% |
|
1425 |
#' mutate(is_event = CNSR == 0) |
|
1426 |
#' tbl_grob <- h_grob_coxph( |
|
1427 |
#' df = data, |
|
1428 |
#' variables = list(tte = "AVAL", is_event = "is_event", arm = "ARMCD"), |
|
1429 |
#' control_coxph_pw = control_coxph(conf_level = 0.9), x = 0.5, y = 0.5 |
|
1430 |
#' ) |
|
1431 |
#' grid::grid.draw(tbl_grob) |
|
1432 |
#' } |
|
1433 |
#' |
|
1434 |
#' @export |
|
1435 |
h_grob_coxph <- function(..., |
|
1436 |
x = 0, |
|
1437 |
y = 0, |
|
1438 |
width = grid::unit(0.4, "npc"), |
|
1439 |
ttheme = gridExtra::ttheme_default( |
|
1440 |
padding = grid::unit(c(1, .5), "lines"), |
|
1441 |
core = list(bg_params = list(fill = c("grey95", "grey90"), alpha = .5)) |
|
1442 |
)) { |
|
1443 | 3x |
data <- h_tbl_coxph_pairwise(...) |
1444 | ||
1445 | 3x |
width <- grid::convertUnit(grid::unit(as.numeric(width), grid::unitType(width)), "in") |
1446 | 3x |
height <- width * (nrow(data) + 1) / 12 |
1447 | ||
1448 | 3x |
w <- paste(" ", c( |
1449 | 3x |
rownames(data)[which.max(nchar(rownames(data)))], |
1450 | 3x |
sapply(names(data), function(x) c(x, data[[x]])[which.max(nchar(c(x, data[[x]])))]) |
1451 |
)) |
|
1452 | 3x |
w_unit <- grid::convertWidth(grid::stringWidth(w), "in", valueOnly = TRUE) |
1453 | ||
1454 | 3x |
w_txt <- sapply(1:64, function(x) { |
1455 | 192x |
graphics::par(ps = x) |
1456 | 192x |
graphics::strwidth(w[4], units = "in") |
1457 |
}) |
|
1458 | 3x |
f_size_w <- which.max(w_txt[w_txt < as.numeric((w_unit / sum(w_unit)) * width)[4]]) |
1459 | ||
1460 | 3x |
h_txt <- sapply(1:64, function(x) { |
1461 | 192x |
graphics::par(ps = x) |
1462 | 192x |
graphics::strheight(grid::stringHeight("X"), units = "in") |
1463 |
}) |
|
1464 | 3x |
f_size_h <- which.max(h_txt[h_txt < as.numeric(grid::unit(as.numeric(height) / 4, grid::unitType(height)))]) |
1465 | ||
1466 | 3x |
if (ttheme$core$fg_params$fontsize == 12) { |
1467 | 3x |
ttheme$core$fg_params$fontsize <- min(f_size_w, f_size_h) |
1468 | 3x |
ttheme$colhead$fg_params$fontsize <- min(f_size_w, f_size_h) |
1469 | 3x |
ttheme$rowhead$fg_params$fontsize <- min(f_size_w, f_size_h) |
1470 |
} |
|
1471 | ||
1472 | 3x |
tryCatch( |
1473 | 3x |
expr = { |
1474 | 3x |
gt <- gridExtra::tableGrob( |
1475 | 3x |
d = data, |
1476 | 3x |
theme = ttheme |
1477 | 3x |
) # ERROR 'data' must be of a vector type, was 'NULL' |
1478 | 3x |
gt$widths <- ((w_unit / sum(w_unit)) * width) |
1479 | 3x |
gt$heights <- rep(grid::unit(as.numeric(height) / 4, grid::unitType(height)), nrow(gt)) |
1480 | 3x |
vp <- grid::viewport( |
1481 | 3x |
x = grid::unit(x, "npc") + grid::unit(1, "lines"), |
1482 | 3x |
y = grid::unit(y, "npc") + grid::unit(1.5, "lines"), |
1483 | 3x |
height = height, |
1484 | 3x |
width = width, |
1485 | 3x |
just = c("left", "bottom") |
1486 |
) |
|
1487 | 3x |
grid::gList( |
1488 | 3x |
grid::gTree( |
1489 | 3x |
vp = vp, |
1490 | 3x |
children = grid::gList(gt) |
1491 |
) |
|
1492 |
) |
|
1493 |
}, |
|
1494 | 3x |
error = function(w) { |
1495 | ! |
message(paste( |
1496 | ! |
"Warning: Cox table will not be displayed as there is", |
1497 | ! |
"not any level to be compared in the arm variable." |
1498 |
)) |
|
1499 | ! |
return( |
1500 | ! |
grid::gList( |
1501 | ! |
grid::gTree( |
1502 | ! |
vp = NULL, |
1503 | ! |
children = NULL |
1504 |
) |
|
1505 |
) |
|
1506 |
) |
|
1507 |
} |
|
1508 |
) |
|
1509 |
} |
1 |
#' Cox Proportional Hazards Regression |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Fits a Cox regression model and estimates hazard ratio to describe the effect size in a survival analysis. |
|
6 |
#' |
|
7 |
#' @inheritParams argument_convention |
|
8 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("summarize_coxreg")` |
|
9 |
#' to see available statistics for this function. |
|
10 |
#' |
|
11 |
#' @details Cox models are the most commonly used methods to estimate the magnitude of |
|
12 |
#' the effect in survival analysis. It assumes proportional hazards: the ratio |
|
13 |
#' of the hazards between groups (e.g., two arms) is constant over time. |
|
14 |
#' This ratio is referred to as the "hazard ratio" (HR) and is one of the |
|
15 |
#' most commonly reported metrics to describe the effect size in survival |
|
16 |
#' analysis (NEST Team, 2020). |
|
17 |
#' |
|
18 |
#' @seealso [fit_coxreg] for relevant fitting functions, [h_cox_regression] for relevant |
|
19 |
#' helper functions, and [tidy_coxreg] for custom tidy methods. |
|
20 |
#' |
|
21 |
#' @examples |
|
22 |
#' library(survival) |
|
23 |
#' |
|
24 |
#' # Testing dataset [survival::bladder]. |
|
25 |
#' set.seed(1, kind = "Mersenne-Twister") |
|
26 |
#' dta_bladder <- with( |
|
27 |
#' data = bladder[bladder$enum < 5, ], |
|
28 |
#' tibble::tibble( |
|
29 |
#' TIME = stop, |
|
30 |
#' STATUS = event, |
|
31 |
#' ARM = as.factor(rx), |
|
32 |
#' COVAR1 = as.factor(enum) %>% formatters::with_label("A Covariate Label"), |
|
33 |
#' COVAR2 = factor( |
|
34 |
#' sample(as.factor(enum)), |
|
35 |
#' levels = 1:4, labels = c("F", "F", "M", "M") |
|
36 |
#' ) %>% formatters::with_label("Sex (F/M)") |
|
37 |
#' ) |
|
38 |
#' ) |
|
39 |
#' dta_bladder$AGE <- sample(20:60, size = nrow(dta_bladder), replace = TRUE) |
|
40 |
#' dta_bladder$STUDYID <- factor("X") |
|
41 |
#' |
|
42 |
#' u1_variables <- list( |
|
43 |
#' time = "TIME", event = "STATUS", arm = "ARM", covariates = c("COVAR1", "COVAR2") |
|
44 |
#' ) |
|
45 |
#' |
|
46 |
#' u2_variables <- list(time = "TIME", event = "STATUS", covariates = c("COVAR1", "COVAR2")) |
|
47 |
#' |
|
48 |
#' m1_variables <- list( |
|
49 |
#' time = "TIME", event = "STATUS", arm = "ARM", covariates = c("COVAR1", "COVAR2") |
|
50 |
#' ) |
|
51 |
#' |
|
52 |
#' m2_variables <- list(time = "TIME", event = "STATUS", covariates = c("COVAR1", "COVAR2")) |
|
53 |
#' |
|
54 |
#' @name cox_regression |
|
55 |
#' @order 1 |
|
56 |
NULL |
|
57 | ||
58 |
#' @describeIn cox_regression Statistics function that transforms results tabulated |
|
59 |
#' from [fit_coxreg_univar()] or [fit_coxreg_multivar()] into a list. |
|
60 |
#' |
|
61 |
#' @param model_df (`data.frame`)\cr contains the resulting model fit from a [fit_coxreg] |
|
62 |
#' function with tidying applied via [broom::tidy()]. |
|
63 |
#' @param .stats (`character`)\cr the name of statistics to be reported among: |
|
64 |
#' * `n`: number of observations (univariate only) |
|
65 |
#' * `hr`: hazard ratio |
|
66 |
#' * `ci`: confidence interval |
|
67 |
#' * `pval`: p-value of the treatment effect |
|
68 |
#' * `pval_inter`: p-value of the interaction effect between the treatment and the covariate (univariate only) |
|
69 |
#' @param .which_vars (`character`)\cr which rows should statistics be returned for from the given model. |
|
70 |
#' Defaults to "all". Other options include "var_main" for main effects, `"inter"` for interaction effects, |
|
71 |
#' and `"multi_lvl"` for multivariate model covariate level rows. When `.which_vars` is "all" specific |
|
72 |
#' variables can be selected by specifying `.var_nms`. |
|
73 |
#' @param .var_nms (`character`)\cr the `term` value of rows in `df` for which `.stats` should be returned. Typically |
|
74 |
#' this is the name of a variable. If using variable labels, `var` should be a vector of both the desired |
|
75 |
#' variable name and the variable label in that order to see all `.stats` related to that variable. When `.which_vars` |
|
76 |
#' is `"var_main"` `.var_nms` should be only the variable name. |
|
77 |
#' |
|
78 |
#' @return |
|
79 |
#' * `s_coxreg()` returns the selected statistic for from the Cox regression model for the selected variable(s). |
|
80 |
#' |
|
81 |
#' @examples |
|
82 |
#' # s_coxreg |
|
83 |
#' |
|
84 |
#' # Univariate |
|
85 |
#' univar_model <- fit_coxreg_univar(variables = u1_variables, data = dta_bladder) |
|
86 |
#' df1 <- broom::tidy(univar_model) |
|
87 |
#' |
|
88 |
#' s_coxreg(model_df = df1, .stats = "hr") |
|
89 |
#' |
|
90 |
#' # Univariate with interactions |
|
91 |
#' univar_model_inter <- fit_coxreg_univar( |
|
92 |
#' variables = u1_variables, control = control_coxreg(interaction = TRUE), data = dta_bladder |
|
93 |
#' ) |
|
94 |
#' df1_inter <- broom::tidy(univar_model_inter) |
|
95 |
#' |
|
96 |
#' s_coxreg(model_df = df1_inter, .stats = "hr", .which_vars = "inter", .var_nms = "COVAR1") |
|
97 |
#' |
|
98 |
#' # Univariate without treatment arm - only "COVAR2" covariate effects |
|
99 |
#' univar_covs_model <- fit_coxreg_univar(variables = u2_variables, data = dta_bladder) |
|
100 |
#' df1_covs <- broom::tidy(univar_covs_model) |
|
101 |
#' |
|
102 |
#' s_coxreg(model_df = df1_covs, .stats = "hr", .var_nms = c("COVAR2", "Sex (F/M)")) |
|
103 |
#' |
|
104 |
#' # Multivariate. |
|
105 |
#' multivar_model <- fit_coxreg_multivar(variables = m1_variables, data = dta_bladder) |
|
106 |
#' df2 <- broom::tidy(multivar_model) |
|
107 |
#' |
|
108 |
#' s_coxreg(model_df = df2, .stats = "pval", .which_vars = "var_main", .var_nms = "COVAR1") |
|
109 |
#' s_coxreg( |
|
110 |
#' model_df = df2, .stats = "pval", .which_vars = "multi_lvl", |
|
111 |
#' .var_nms = c("COVAR1", "A Covariate Label") |
|
112 |
#' ) |
|
113 |
#' |
|
114 |
#' # Multivariate without treatment arm - only "COVAR1" main effect |
|
115 |
#' multivar_covs_model <- fit_coxreg_multivar(variables = m2_variables, data = dta_bladder) |
|
116 |
#' df2_covs <- broom::tidy(multivar_covs_model) |
|
117 |
#' |
|
118 |
#' s_coxreg(model_df = df2_covs, .stats = "hr") |
|
119 |
#' |
|
120 |
#' @export |
|
121 |
s_coxreg <- function(model_df, .stats, .which_vars = "all", .var_nms = NULL) { |
|
122 | 194x |
assert_df_with_variables(model_df, list(term = "term", stat = .stats)) |
123 | 194x |
checkmate::assert_multi_class(model_df$term, classes = c("factor", "character")) |
124 | 194x |
model_df$term <- as.character(model_df$term) |
125 | 194x |
.var_nms <- .var_nms[!is.na(.var_nms)] |
126 | ||
127 | 192x |
if (length(.var_nms) > 0) model_df <- model_df[model_df$term %in% .var_nms, ] |
128 | 39x |
if (.which_vars == "multi_lvl") model_df$term <- tail(.var_nms, 1) |
129 | ||
130 |
# We need a list with names corresponding to the stats to display of equal length to the list of stats. |
|
131 | 194x |
y <- split(model_df, f = model_df$term, drop = FALSE) |
132 | 194x |
y <- stats::setNames(y, nm = rep(.stats, length(y))) |
133 | ||
134 | 194x |
if (.which_vars == "var_main") { |
135 | 84x |
y <- lapply(y, function(x) x[1, ]) # only main effect |
136 | 110x |
} else if (.which_vars %in% c("inter", "multi_lvl")) { |
137 | 80x |
y <- lapply(y, function(x) if (nrow(y[[1]]) > 1) x[-1, ] else x) # exclude main effect |
138 |
} |
|
139 | ||
140 | 194x |
lapply( |
141 | 194x |
X = y, |
142 | 194x |
FUN = function(x) { |
143 | 198x |
z <- as.list(x[[.stats]]) |
144 | 198x |
stats::setNames(z, nm = x$term_label) |
145 |
} |
|
146 |
) |
|
147 |
} |
|
148 | ||
149 |
#' @describeIn cox_regression Analysis function which is used as `afun` in [rtables::analyze()] |
|
150 |
#' and `cfun` in [rtables::summarize_row_groups()] within `summarize_coxreg()`. |
|
151 |
#' |
|
152 |
#' @param eff (`flag`)\cr whether treatment effect should be calculated. Defaults to `FALSE`. |
|
153 |
#' @param var_main (`flag`)\cr whether main effects should be calculated. Defaults to `FALSE`. |
|
154 |
#' @param na_str (`string`)\cr custom string to replace all `NA` values with. Defaults to `""`. |
|
155 |
#' @param cache_env (`environment`)\cr an environment object used to cache the regression model in order to |
|
156 |
#' avoid repeatedly fitting the same model for every row in the table. Defaults to `NULL` (no caching). |
|
157 |
#' @param varlabels (`list`)\cr a named list corresponds to the names of variables found in data, passed |
|
158 |
#' as a named list and corresponding to time, event, arm, strata, and covariates terms. If arm is missing |
|
159 |
#' from variables, then only Cox model(s) including the covariates will be fitted and the corresponding |
|
160 |
#' effect estimates will be tabulated later. |
|
161 |
#' |
|
162 |
#' @return |
|
163 |
#' * `a_coxreg()` returns formatted [rtables::CellValue()]. |
|
164 |
#' |
|
165 |
#' @examples |
|
166 |
#' a_coxreg( |
|
167 |
#' df = dta_bladder, |
|
168 |
#' labelstr = "Label 1", |
|
169 |
#' variables = u1_variables, |
|
170 |
#' .spl_context = list(value = "COVAR1"), |
|
171 |
#' .stats = "n", |
|
172 |
#' .formats = "xx" |
|
173 |
#' ) |
|
174 |
#' |
|
175 |
#' a_coxreg( |
|
176 |
#' df = dta_bladder, |
|
177 |
#' labelstr = "", |
|
178 |
#' variables = u1_variables, |
|
179 |
#' .spl_context = list(value = "COVAR2"), |
|
180 |
#' .stats = "pval", |
|
181 |
#' .formats = "xx.xxxx" |
|
182 |
#' ) |
|
183 |
#' |
|
184 |
#' @export |
|
185 |
a_coxreg <- function(df, |
|
186 |
labelstr, |
|
187 |
eff = FALSE, |
|
188 |
var_main = FALSE, |
|
189 |
multivar = FALSE, |
|
190 |
variables, |
|
191 |
at = list(), |
|
192 |
control = control_coxreg(), |
|
193 |
.spl_context, |
|
194 |
.stats, |
|
195 |
.formats, |
|
196 |
.indent_mods = NULL, |
|
197 |
na_level = lifecycle::deprecated(), |
|
198 |
na_str = "", |
|
199 |
cache_env = NULL) { |
|
200 | 191x |
if (lifecycle::is_present(na_level)) { |
201 | ! |
lifecycle::deprecate_warn("0.9.1", "a_coxreg(na_level)", "a_coxreg(na_str)") |
202 | ! |
na_str <- na_level |
203 |
} |
|
204 | ||
205 | 191x |
cov_no_arm <- !multivar && !"arm" %in% names(variables) && control$interaction # special case: univar no arm |
206 | 191x |
cov <- tail(.spl_context$value, 1) # current variable/covariate |
207 | 191x |
var_lbl <- formatters::var_labels(df)[cov] # check for df labels |
208 | 191x |
if (length(labelstr) > 1) { |
209 | ! |
labelstr <- if (cov %in% names(labelstr)) labelstr[[cov]] else var_lbl # use df labels if none |
210 | 191x |
} else if (!is.na(var_lbl) && labelstr == cov && cov %in% variables$covariates) { |
211 | 62x |
labelstr <- var_lbl |
212 |
} |
|
213 | 191x |
if (eff || multivar || cov_no_arm) { |
214 | 82x |
control$interaction <- FALSE |
215 |
} else { |
|
216 | 109x |
variables$covariates <- cov |
217 | 40x |
if (var_main) control$interaction <- TRUE |
218 |
} |
|
219 | ||
220 | 191x |
if (is.null(cache_env[[cov]])) { |
221 | 30x |
if (!multivar) { |
222 | 23x |
model <- fit_coxreg_univar(variables = variables, data = df, at = at, control = control) %>% broom::tidy() |
223 |
} else { |
|
224 | 7x |
model <- fit_coxreg_multivar(variables = variables, data = df, control = control) %>% broom::tidy() |
225 |
} |
|
226 | 30x |
cache_env[[cov]] <- model |
227 |
} else { |
|
228 | 161x |
model <- cache_env[[cov]] |
229 |
} |
|
230 | 109x |
if (!multivar && !var_main) model[, "pval_inter"] <- NA_real_ |
231 | ||
232 | 191x |
if (cov_no_arm || (!cov_no_arm && !"arm" %in% names(variables) && is.numeric(df[[cov]]))) { |
233 | 15x |
multivar <- TRUE |
234 | 3x |
if (!cov_no_arm) var_main <- TRUE |
235 |
} |
|
236 | ||
237 | 191x |
vars_coxreg <- list(which_vars = "all", var_nms = NULL) |
238 | 191x |
if (eff) { |
239 | 40x |
if (multivar && !var_main) { # multivar treatment level |
240 | 6x |
var_lbl_arm <- formatters::var_labels(df)[[variables$arm]] |
241 | 6x |
vars_coxreg[c("var_nms", "which_vars")] <- list(c(variables$arm, var_lbl_arm), "multi_lvl") |
242 |
} else { # treatment effect |
|
243 | 34x |
vars_coxreg["var_nms"] <- variables$arm |
244 | 6x |
if (var_main) vars_coxreg["which_vars"] <- "var_main" |
245 |
} |
|
246 |
} else { |
|
247 | 151x |
if (!multivar || (multivar && var_main && !is.numeric(df[[cov]]))) { # covariate effect/level |
248 | 118x |
vars_coxreg[c("var_nms", "which_vars")] <- list(cov, "var_main") |
249 | 33x |
} else if (multivar) { # multivar covariate level |
250 | 33x |
vars_coxreg[c("var_nms", "which_vars")] <- list(c(cov, var_lbl), "multi_lvl") |
251 | 6x |
if (var_main) model[cov, .stats] <- NA_real_ |
252 |
} |
|
253 | 40x |
if (!multivar && !var_main && control$interaction) vars_coxreg["which_vars"] <- "inter" # interaction effect |
254 |
} |
|
255 | 191x |
var_vals <- s_coxreg(model, .stats, .which_vars = vars_coxreg$which_vars, .var_nms = vars_coxreg$var_nms)[[1]] |
256 | 191x |
var_names <- if (all(grepl("\\(reference = ", names(var_vals))) && labelstr != tail(.spl_context$value, 1)) { |
257 | 21x |
paste(c(labelstr, tail(strsplit(names(var_vals), " ")[[1]], 3)), collapse = " ") # "reference" main effect labels |
258 | 191x |
} else if ((!multivar && !eff && !(!var_main && control$interaction) && nchar(labelstr) > 0) || |
259 | 191x |
(multivar && var_main && is.numeric(df[[cov]]))) { # nolint |
260 | 47x |
labelstr # other main effect labels |
261 | 191x |
} else if (multivar && !eff && !var_main && is.numeric(df[[cov]])) { |
262 | 6x |
"All" # multivar numeric covariate |
263 |
} else { |
|
264 | 117x |
names(var_vals) |
265 |
} |
|
266 | 191x |
in_rows( |
267 | 191x |
.list = var_vals, .names = var_names, .labels = var_names, .indent_mods = .indent_mods, |
268 | 191x |
.formats = stats::setNames(rep(.formats, length(var_names)), var_names), |
269 | 191x |
.format_na_strs = stats::setNames(rep(na_str, length(var_names)), var_names) |
270 |
) |
|
271 |
} |
|
272 | ||
273 |
#' @describeIn cox_regression Layout-creating function which creates a Cox regression summary table |
|
274 |
#' layout. This function is a wrapper for several `rtables` layouting functions. This function |
|
275 |
#' is a wrapper for [rtables::analyze_colvars()] and [rtables::summarize_row_groups()]. |
|
276 |
#' |
|
277 |
#' @inheritParams fit_coxreg_univar |
|
278 |
#' @param multivar (`flag`)\cr Defaults to `FALSE`. If `TRUE` multivariate Cox regression will run, otherwise |
|
279 |
#' univariate Cox regression will run. |
|
280 |
#' @param common_var (`character`)\cr the name of a factor variable in the dataset which takes the same value |
|
281 |
#' for all rows. This should be created during pre-processing if no such variable currently exists. |
|
282 |
#' @param .section_div (`character`)\cr string which should be repeated as a section divider between sections. |
|
283 |
#' Defaults to `NA` for no section divider. If a vector of two strings are given, the first will be used between |
|
284 |
#' treatment and covariate sections and the second between different covariates. |
|
285 |
#' |
|
286 |
#' @return |
|
287 |
#' * `summarize_coxreg()` returns a layout object suitable for passing to further layouting functions, |
|
288 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add a Cox regression table |
|
289 |
#' containing the chosen statistics to the table layout. |
|
290 |
#' |
|
291 |
#' @seealso [fit_coxreg_univar()] and [fit_coxreg_multivar()] which also take the `variables`, `data`, |
|
292 |
#' `at` (univariate only), and `control` arguments but return unformatted univariate and multivariate |
|
293 |
#' Cox regression models, respectively. |
|
294 |
#' |
|
295 |
#' @examples |
|
296 |
#' # summarize_coxreg |
|
297 |
#' |
|
298 |
#' result_univar <- basic_table() %>% |
|
299 |
#' summarize_coxreg(variables = u1_variables) %>% |
|
300 |
#' build_table(dta_bladder) |
|
301 |
#' result_univar |
|
302 |
#' |
|
303 |
#' result_univar_covs <- basic_table() %>% |
|
304 |
#' summarize_coxreg( |
|
305 |
#' variables = u2_variables, |
|
306 |
#' ) %>% |
|
307 |
#' build_table(dta_bladder) |
|
308 |
#' result_univar_covs |
|
309 |
#' |
|
310 |
#' result_multivar <- basic_table() %>% |
|
311 |
#' summarize_coxreg( |
|
312 |
#' variables = m1_variables, |
|
313 |
#' multivar = TRUE, |
|
314 |
#' ) %>% |
|
315 |
#' build_table(dta_bladder) |
|
316 |
#' result_multivar |
|
317 |
#' |
|
318 |
#' result_multivar_covs <- basic_table() %>% |
|
319 |
#' summarize_coxreg( |
|
320 |
#' variables = m2_variables, |
|
321 |
#' multivar = TRUE, |
|
322 |
#' varlabels = c("Covariate 1", "Covariate 2") # custom labels |
|
323 |
#' ) %>% |
|
324 |
#' build_table(dta_bladder) |
|
325 |
#' result_multivar_covs |
|
326 |
#' |
|
327 |
#' @export |
|
328 |
#' @order 2 |
|
329 |
summarize_coxreg <- function(lyt, |
|
330 |
variables, |
|
331 |
control = control_coxreg(), |
|
332 |
at = list(), |
|
333 |
multivar = FALSE, |
|
334 |
common_var = "STUDYID", |
|
335 |
.stats = c("n", "hr", "ci", "pval", "pval_inter"), |
|
336 |
.formats = c( |
|
337 |
n = "xx", hr = "xx.xx", ci = "(xx.xx, xx.xx)", |
|
338 |
pval = "x.xxxx | (<0.0001)", pval_inter = "x.xxxx | (<0.0001)" |
|
339 |
), |
|
340 |
varlabels = NULL, |
|
341 |
.indent_mods = NULL, |
|
342 |
na_level = lifecycle::deprecated(), |
|
343 |
na_str = "", |
|
344 |
.section_div = NA_character_) { |
|
345 | 11x |
if (lifecycle::is_present(na_level)) { |
346 | ! |
lifecycle::deprecate_warn("0.9.1", "summarize_coxreg(na_level)", "summarize_coxreg(na_str)") |
347 | ! |
na_str <- na_level |
348 |
} |
|
349 | ||
350 | 11x |
if (multivar && control$interaction) { |
351 | 1x |
warning(paste( |
352 | 1x |
"Interactions are not available for multivariate cox regression using summarize_coxreg.", |
353 | 1x |
"The model will be calculated without interaction effects." |
354 |
)) |
|
355 |
} |
|
356 | 11x |
if (control$interaction && !"arm" %in% names(variables)) { |
357 | 1x |
stop("To include interactions please specify 'arm' in variables.") |
358 |
} |
|
359 | ||
360 | 10x |
.stats <- if (!"arm" %in% names(variables) || multivar) { # only valid statistics |
361 | 4x |
intersect(c("hr", "ci", "pval"), .stats) |
362 | 10x |
} else if (control$interaction) { |
363 | 4x |
intersect(c("n", "hr", "ci", "pval", "pval_inter"), .stats) |
364 |
} else { |
|
365 | 2x |
intersect(c("n", "hr", "ci", "pval"), .stats) |
366 |
} |
|
367 | 10x |
stat_labels <- c( |
368 | 10x |
n = "n", hr = "Hazard Ratio", ci = paste0(control$conf_level * 100, "% CI"), |
369 | 10x |
pval = "p-value", pval_inter = "Interaction p-value" |
370 |
) |
|
371 | 10x |
stat_labels <- stat_labels[names(stat_labels) %in% .stats] |
372 | 10x |
.formats <- .formats[names(.formats) %in% .stats] |
373 | 10x |
env <- new.env() # create caching environment |
374 | ||
375 | 10x |
lyt <- lyt %>% |
376 | 10x |
split_cols_by_multivar( |
377 | 10x |
vars = rep(common_var, length(.stats)), |
378 | 10x |
varlabels = stat_labels, |
379 | 10x |
extra_args = list( |
380 | 10x |
.stats = .stats, .formats = .formats, .indent_mods = .indent_mods, na_str = rep(na_str, length(.stats)), |
381 | 10x |
cache_env = replicate(length(.stats), list(env)) |
382 |
) |
|
383 |
) |
|
384 | ||
385 | 10x |
if ("arm" %in% names(variables)) { # treatment effect |
386 | 8x |
lyt <- lyt %>% |
387 | 8x |
split_rows_by( |
388 | 8x |
common_var, |
389 | 8x |
split_label = "Treatment:", |
390 | 8x |
label_pos = "visible", |
391 | 8x |
child_labels = "hidden", |
392 | 8x |
section_div = head(.section_div, 1) |
393 |
) |
|
394 | 8x |
if (!multivar) { |
395 | 6x |
lyt <- lyt %>% |
396 | 6x |
analyze_colvars( |
397 | 6x |
afun = a_coxreg, |
398 | 6x |
na_str = na_str, |
399 | 6x |
extra_args = list( |
400 | 6x |
variables = variables, control = control, multivar = multivar, eff = TRUE, var_main = multivar, |
401 | 6x |
labelstr = "" |
402 |
) |
|
403 |
) |
|
404 |
} else { # treatment level effects |
|
405 | 2x |
lyt <- lyt %>% |
406 | 2x |
summarize_row_groups( |
407 | 2x |
cfun = a_coxreg, |
408 | 2x |
na_str = na_str, |
409 | 2x |
extra_args = list( |
410 | 2x |
variables = variables, control = control, multivar = multivar, eff = TRUE, var_main = multivar |
411 |
) |
|
412 |
) %>% |
|
413 | 2x |
analyze_colvars( |
414 | 2x |
afun = a_coxreg, |
415 | 2x |
na_str = na_str, |
416 | 2x |
extra_args = list(eff = TRUE, control = control, variables = variables, multivar = multivar, labelstr = "") |
417 |
) |
|
418 |
} |
|
419 |
} |
|
420 | ||
421 | 10x |
if ("covariates" %in% names(variables)) { # covariate main effects |
422 | 10x |
lyt <- lyt %>% |
423 | 10x |
split_rows_by_multivar( |
424 | 10x |
vars = variables$covariates, |
425 | 10x |
varlabels = varlabels, |
426 | 10x |
split_label = "Covariate:", |
427 | 10x |
nested = FALSE, |
428 | 10x |
child_labels = if (multivar || control$interaction || !"arm" %in% names(variables)) "default" else "hidden", |
429 | 10x |
section_div = tail(.section_div, 1) |
430 |
) |
|
431 | 10x |
if (multivar || control$interaction || !"arm" %in% names(variables)) { |
432 | 8x |
lyt <- lyt %>% |
433 | 8x |
summarize_row_groups( |
434 | 8x |
cfun = a_coxreg, |
435 | 8x |
na_str = na_str, |
436 | 8x |
extra_args = list( |
437 | 8x |
variables = variables, at = at, control = control, multivar = multivar, |
438 | 8x |
var_main = if (multivar) multivar else control$interaction |
439 |
) |
|
440 |
) |
|
441 |
} else { |
|
442 | ! |
if (!is.null(varlabels)) names(varlabels) <- variables$covariates |
443 | 2x |
lyt <- lyt %>% |
444 | 2x |
analyze_colvars( |
445 | 2x |
afun = a_coxreg, |
446 | 2x |
na_str = na_str, |
447 | 2x |
extra_args = list( |
448 | 2x |
variables = variables, at = at, control = control, multivar = multivar, |
449 | 2x |
var_main = if (multivar) multivar else control$interaction, |
450 | 2x |
labelstr = if (is.null(varlabels)) "" else varlabels |
451 |
) |
|
452 |
) |
|
453 |
} |
|
454 | ||
455 | 2x |
if (!"arm" %in% names(variables)) control$interaction <- TRUE # special case: univar no arm |
456 | 10x |
if (multivar || control$interaction) { # covariate level effects |
457 | 8x |
lyt <- lyt %>% |
458 | 8x |
analyze_colvars( |
459 | 8x |
afun = a_coxreg, |
460 | 8x |
na_str = na_str, |
461 | 8x |
extra_args = list(variables = variables, at = at, control = control, multivar = multivar, labelstr = ""), |
462 | 8x |
indent_mod = if (!"arm" %in% names(variables) || multivar) 0L else -1L |
463 |
) |
|
464 |
} |
|
465 |
} |
|
466 | ||
467 | 10x |
lyt |
468 |
} |
1 |
#' Helper Functions for Tabulating Survival Duration by Subgroup |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Helper functions that tabulate in a data frame statistics such as median survival |
|
6 |
#' time and hazard ratio for population subgroups. |
|
7 |
#' |
|
8 |
#' @inheritParams argument_convention |
|
9 |
#' @inheritParams survival_coxph_pairwise |
|
10 |
#' @inheritParams survival_duration_subgroups |
|
11 |
#' @param arm (`factor`)\cr the treatment group variable. |
|
12 |
#' |
|
13 |
#' @details Main functionality is to prepare data for use in a layout-creating function. |
|
14 |
#' |
|
15 |
#' @examples |
|
16 |
#' library(dplyr) |
|
17 |
#' library(forcats) |
|
18 |
#' |
|
19 |
#' adtte <- tern_ex_adtte |
|
20 |
#' |
|
21 |
#' # Save variable labels before data processing steps. |
|
22 |
#' adtte_labels <- formatters::var_labels(adtte) |
|
23 |
#' |
|
24 |
#' adtte_f <- adtte %>% |
|
25 |
#' filter( |
|
26 |
#' PARAMCD == "OS", |
|
27 |
#' ARM %in% c("B: Placebo", "A: Drug X"), |
|
28 |
#' SEX %in% c("M", "F") |
|
29 |
#' ) %>% |
|
30 |
#' mutate( |
|
31 |
#' # Reorder levels of ARM to display reference arm before treatment arm. |
|
32 |
#' ARM = droplevels(fct_relevel(ARM, "B: Placebo")), |
|
33 |
#' SEX = droplevels(SEX), |
|
34 |
#' is_event = CNSR == 0 |
|
35 |
#' ) |
|
36 |
#' labels <- c("ARM" = adtte_labels[["ARM"]], "SEX" = adtte_labels[["SEX"]], "is_event" = "Event Flag") |
|
37 |
#' formatters::var_labels(adtte_f)[names(labels)] <- labels |
|
38 |
#' |
|
39 |
#' @name h_survival_duration_subgroups |
|
40 |
NULL |
|
41 | ||
42 |
#' @describeIn h_survival_duration_subgroups helper to prepare a data frame of median survival times by arm. |
|
43 |
#' |
|
44 |
#' @return |
|
45 |
#' * `h_survtime_df()` returns a `data.frame` with columns `arm`, `n`, `n_events`, and `median`. |
|
46 |
#' |
|
47 |
#' @examples |
|
48 |
#' # Extract median survival time for one group. |
|
49 |
#' h_survtime_df( |
|
50 |
#' tte = adtte_f$AVAL, |
|
51 |
#' is_event = adtte_f$is_event, |
|
52 |
#' arm = adtte_f$ARM |
|
53 |
#' ) |
|
54 |
#' |
|
55 |
#' @export |
|
56 |
h_survtime_df <- function(tte, is_event, arm) { |
|
57 | 61x |
checkmate::assert_numeric(tte) |
58 | 60x |
checkmate::assert_logical(is_event, len = length(tte)) |
59 | 60x |
assert_valid_factor(arm, len = length(tte)) |
60 | ||
61 | 60x |
df_tte <- data.frame( |
62 | 60x |
tte = tte, |
63 | 60x |
is_event = is_event, |
64 | 60x |
stringsAsFactors = FALSE |
65 |
) |
|
66 | ||
67 |
# Delete NAs |
|
68 | 60x |
non_missing_rows <- stats::complete.cases(df_tte) |
69 | 60x |
df_tte <- df_tte[non_missing_rows, ] |
70 | 60x |
arm <- arm[non_missing_rows] |
71 | ||
72 | 60x |
lst_tte <- split(df_tte, arm) |
73 | 60x |
lst_results <- Map(function(x, arm) { |
74 | 120x |
if (nrow(x) > 0) { |
75 | 116x |
s_surv <- s_surv_time(x, .var = "tte", is_event = "is_event") |
76 | 116x |
median_est <- unname(as.numeric(s_surv$median)) |
77 | 116x |
n_events <- sum(x$is_event) |
78 |
} else { |
|
79 | 4x |
median_est <- NA |
80 | 4x |
n_events <- NA |
81 |
} |
|
82 | ||
83 | 120x |
data.frame( |
84 | 120x |
arm = arm, |
85 | 120x |
n = nrow(x), |
86 | 120x |
n_events = n_events, |
87 | 120x |
median = median_est, |
88 | 120x |
stringsAsFactors = FALSE |
89 |
) |
|
90 | 60x |
}, lst_tte, names(lst_tte)) |
91 | ||
92 | 60x |
df <- do.call(rbind, args = c(lst_results, make.row.names = FALSE)) |
93 | 60x |
df$arm <- factor(df$arm, levels = levels(arm)) |
94 | 60x |
df |
95 |
} |
|
96 | ||
97 |
#' @describeIn h_survival_duration_subgroups summarizes median survival times by arm and across subgroups |
|
98 |
#' in a data frame. `variables` corresponds to the names of variables found in `data`, passed as a named list and |
|
99 |
#' requires elements `tte`, `is_event`, `arm` and optionally `subgroups`. `groups_lists` optionally specifies |
|
100 |
#' groupings for `subgroups` variables. |
|
101 |
#' |
|
102 |
#' @return |
|
103 |
#' * `h_survtime_subgroups_df()` returns a `data.frame` with columns `arm`, `n`, `n_events`, `median`, `subgroup`, |
|
104 |
#' `var`, `var_label`, and `row_type`. |
|
105 |
#' |
|
106 |
#' @examples |
|
107 |
#' # Extract median survival time for multiple groups. |
|
108 |
#' h_survtime_subgroups_df( |
|
109 |
#' variables = list( |
|
110 |
#' tte = "AVAL", |
|
111 |
#' is_event = "is_event", |
|
112 |
#' arm = "ARM", |
|
113 |
#' subgroups = c("SEX", "BMRKR2") |
|
114 |
#' ), |
|
115 |
#' data = adtte_f |
|
116 |
#' ) |
|
117 |
#' |
|
118 |
#' # Define groupings for BMRKR2 levels. |
|
119 |
#' h_survtime_subgroups_df( |
|
120 |
#' variables = list( |
|
121 |
#' tte = "AVAL", |
|
122 |
#' is_event = "is_event", |
|
123 |
#' arm = "ARM", |
|
124 |
#' subgroups = c("SEX", "BMRKR2") |
|
125 |
#' ), |
|
126 |
#' data = adtte_f, |
|
127 |
#' groups_lists = list( |
|
128 |
#' BMRKR2 = list( |
|
129 |
#' "low" = "LOW", |
|
130 |
#' "low/medium" = c("LOW", "MEDIUM"), |
|
131 |
#' "low/medium/high" = c("LOW", "MEDIUM", "HIGH") |
|
132 |
#' ) |
|
133 |
#' ) |
|
134 |
#' ) |
|
135 |
#' |
|
136 |
#' @export |
|
137 |
h_survtime_subgroups_df <- function(variables, |
|
138 |
data, |
|
139 |
groups_lists = list(), |
|
140 |
label_all = "All Patients") { |
|
141 | 12x |
checkmate::assert_character(variables$tte) |
142 | 12x |
checkmate::assert_character(variables$is_event) |
143 | 12x |
checkmate::assert_character(variables$arm) |
144 | 12x |
checkmate::assert_character(variables$subgroups, null.ok = TRUE) |
145 | ||
146 | 12x |
assert_df_with_variables(data, variables) |
147 | ||
148 | 12x |
checkmate::assert_string(label_all) |
149 | ||
150 |
# Add All Patients. |
|
151 | 12x |
result_all <- h_survtime_df(data[[variables$tte]], data[[variables$is_event]], data[[variables$arm]]) |
152 | 12x |
result_all$subgroup <- label_all |
153 | 12x |
result_all$var <- "ALL" |
154 | 12x |
result_all$var_label <- label_all |
155 | 12x |
result_all$row_type <- "content" |
156 | ||
157 |
# Add Subgroups. |
|
158 | 12x |
if (is.null(variables$subgroups)) { |
159 | 3x |
result_all |
160 |
} else { |
|
161 | 9x |
l_data <- h_split_by_subgroups(data, variables$subgroups, groups_lists = groups_lists) |
162 | 9x |
l_result <- lapply(l_data, function(grp) { |
163 | 45x |
result <- h_survtime_df(grp$df[[variables$tte]], grp$df[[variables$is_event]], grp$df[[variables$arm]]) |
164 | 45x |
result_labels <- grp$df_labels[rep(1, times = nrow(result)), ] |
165 | 45x |
cbind(result, result_labels) |
166 |
}) |
|
167 | 9x |
result_subgroups <- do.call(rbind, args = c(l_result, make.row.names = FALSE)) |
168 | 9x |
result_subgroups$row_type <- "analysis" |
169 | 9x |
rbind( |
170 | 9x |
result_all, |
171 | 9x |
result_subgroups |
172 |
) |
|
173 |
} |
|
174 |
} |
|
175 | ||
176 |
#' @describeIn h_survival_duration_subgroups helper to prepare a data frame with estimates of |
|
177 |
#' treatment hazard ratio. |
|
178 |
#' |
|
179 |
#' @param strata_data (`factor`, `data.frame` or `NULL`)\cr required if stratified analysis is performed. |
|
180 |
#' |
|
181 |
#' @return |
|
182 |
#' * `h_coxph_df()` returns a `data.frame` with columns `arm`, `n_tot`, `n_tot_events`, `hr`, `lcl`, `ucl`, |
|
183 |
#' `conf_level`, `pval` and `pval_label`. |
|
184 |
#' |
|
185 |
#' @examples |
|
186 |
#' # Extract hazard ratio for one group. |
|
187 |
#' h_coxph_df(adtte_f$AVAL, adtte_f$is_event, adtte_f$ARM) |
|
188 |
#' |
|
189 |
#' # Extract hazard ratio for one group with stratification factor. |
|
190 |
#' h_coxph_df(adtte_f$AVAL, adtte_f$is_event, adtte_f$ARM, strata_data = adtte_f$STRATA1) |
|
191 |
#' |
|
192 |
#' @export |
|
193 |
h_coxph_df <- function(tte, is_event, arm, strata_data = NULL, control = control_coxph()) { |
|
194 | 64x |
checkmate::assert_numeric(tte) |
195 | 64x |
checkmate::assert_logical(is_event, len = length(tte)) |
196 | 64x |
assert_valid_factor(arm, n.levels = 2, len = length(tte)) |
197 | ||
198 | 64x |
df_tte <- data.frame(tte = tte, is_event = is_event) |
199 | 64x |
strata_vars <- NULL |
200 | ||
201 | 64x |
if (!is.null(strata_data)) { |
202 | 5x |
if (is.data.frame(strata_data)) { |
203 | 4x |
strata_vars <- names(strata_data) |
204 | 4x |
checkmate::assert_data_frame(strata_data, nrows = nrow(df_tte)) |
205 | 4x |
assert_df_with_factors(strata_data, as.list(stats::setNames(strata_vars, strata_vars))) |
206 |
} else { |
|
207 | 1x |
assert_valid_factor(strata_data, len = nrow(df_tte)) |
208 | 1x |
strata_vars <- "strata_data" |
209 |
} |
|
210 | 5x |
df_tte[strata_vars] <- strata_data |
211 |
} |
|
212 | ||
213 | 64x |
l_df <- split(df_tte, arm) |
214 | ||
215 | 64x |
if (nrow(l_df[[1]]) > 0 && nrow(l_df[[2]]) > 0) { |
216 |
# Hazard ratio and CI. |
|
217 | 60x |
result <- s_coxph_pairwise( |
218 | 60x |
df = l_df[[2]], |
219 | 60x |
.ref_group = l_df[[1]], |
220 | 60x |
.in_ref_col = FALSE, |
221 | 60x |
.var = "tte", |
222 | 60x |
is_event = "is_event", |
223 | 60x |
strat = strata_vars, |
224 | 60x |
control = control |
225 |
) |
|
226 | ||
227 | 60x |
df <- data.frame( |
228 |
# Dummy column needed downstream to create a nested header. |
|
229 | 60x |
arm = " ", |
230 | 60x |
n_tot = unname(as.numeric(result$n_tot)), |
231 | 60x |
n_tot_events = unname(as.numeric(result$n_tot_events)), |
232 | 60x |
hr = unname(as.numeric(result$hr)), |
233 | 60x |
lcl = unname(result$hr_ci[1]), |
234 | 60x |
ucl = unname(result$hr_ci[2]), |
235 | 60x |
conf_level = control[["conf_level"]], |
236 | 60x |
pval = as.numeric(result$pvalue), |
237 | 60x |
pval_label = obj_label(result$pvalue), |
238 | 60x |
stringsAsFactors = FALSE |
239 |
) |
|
240 |
} else if ( |
|
241 | 4x |
(nrow(l_df[[1]]) == 0 && nrow(l_df[[2]]) > 0) || |
242 | 4x |
(nrow(l_df[[1]]) > 0 && nrow(l_df[[2]]) == 0) |
243 |
) { |
|
244 | 4x |
df_tte_complete <- df_tte[stats::complete.cases(df_tte), ] |
245 | 4x |
df <- data.frame( |
246 |
# Dummy column needed downstream to create a nested header. |
|
247 | 4x |
arm = " ", |
248 | 4x |
n_tot = nrow(df_tte_complete), |
249 | 4x |
n_tot_events = sum(df_tte_complete$is_event), |
250 | 4x |
hr = NA, |
251 | 4x |
lcl = NA, |
252 | 4x |
ucl = NA, |
253 | 4x |
conf_level = control[["conf_level"]], |
254 | 4x |
pval = NA, |
255 | 4x |
pval_label = NA, |
256 | 4x |
stringsAsFactors = FALSE |
257 |
) |
|
258 |
} else { |
|
259 | ! |
df <- data.frame( |
260 |
# Dummy column needed downstream to create a nested header. |
|
261 | ! |
arm = " ", |
262 | ! |
n_tot = 0L, |
263 | ! |
n_tot_events = 0L, |
264 | ! |
hr = NA, |
265 | ! |
lcl = NA, |
266 | ! |
ucl = NA, |
267 | ! |
conf_level = control[["conf_level"]], |
268 | ! |
pval = NA, |
269 | ! |
pval_label = NA, |
270 | ! |
stringsAsFactors = FALSE |
271 |
) |
|
272 |
} |
|
273 | ||
274 | 64x |
df |
275 |
} |
|
276 | ||
277 |
#' @describeIn h_survival_duration_subgroups summarizes estimates of the treatment hazard ratio |
|
278 |
#' across subgroups in a data frame. `variables` corresponds to the names of variables found in |
|
279 |
#' `data`, passed as a named list and requires elements `tte`, `is_event`, `arm` and |
|
280 |
#' optionally `subgroups` and `strat`. `groups_lists` optionally specifies |
|
281 |
#' groupings for `subgroups` variables. |
|
282 |
#' |
|
283 |
#' @return |
|
284 |
#' * `h_coxph_subgroups_df()` returns a `data.frame` with columns `arm`, `n_tot`, `n_tot_events`, `hr`, |
|
285 |
#' `lcl`, `ucl`, `conf_level`, `pval`, `pval_label`, `subgroup`, `var`, `var_label`, and `row_type`. |
|
286 |
#' |
|
287 |
#' @examples |
|
288 |
#' # Extract hazard ratio for multiple groups. |
|
289 |
#' h_coxph_subgroups_df( |
|
290 |
#' variables = list( |
|
291 |
#' tte = "AVAL", |
|
292 |
#' is_event = "is_event", |
|
293 |
#' arm = "ARM", |
|
294 |
#' subgroups = c("SEX", "BMRKR2") |
|
295 |
#' ), |
|
296 |
#' data = adtte_f |
|
297 |
#' ) |
|
298 |
#' |
|
299 |
#' # Define groupings of BMRKR2 levels. |
|
300 |
#' h_coxph_subgroups_df( |
|
301 |
#' variables = list( |
|
302 |
#' tte = "AVAL", |
|
303 |
#' is_event = "is_event", |
|
304 |
#' arm = "ARM", |
|
305 |
#' subgroups = c("SEX", "BMRKR2") |
|
306 |
#' ), |
|
307 |
#' data = adtte_f, |
|
308 |
#' groups_lists = list( |
|
309 |
#' BMRKR2 = list( |
|
310 |
#' "low" = "LOW", |
|
311 |
#' "low/medium" = c("LOW", "MEDIUM"), |
|
312 |
#' "low/medium/high" = c("LOW", "MEDIUM", "HIGH") |
|
313 |
#' ) |
|
314 |
#' ) |
|
315 |
#' ) |
|
316 |
#' |
|
317 |
#' # Extract hazard ratio for multiple groups with stratification factors. |
|
318 |
#' h_coxph_subgroups_df( |
|
319 |
#' variables = list( |
|
320 |
#' tte = "AVAL", |
|
321 |
#' is_event = "is_event", |
|
322 |
#' arm = "ARM", |
|
323 |
#' subgroups = c("SEX", "BMRKR2"), |
|
324 |
#' strat = c("STRATA1", "STRATA2") |
|
325 |
#' ), |
|
326 |
#' data = adtte_f |
|
327 |
#' ) |
|
328 |
#' |
|
329 |
#' @export |
|
330 |
h_coxph_subgroups_df <- function(variables, |
|
331 |
data, |
|
332 |
groups_lists = list(), |
|
333 |
control = control_coxph(), |
|
334 |
label_all = "All Patients") { |
|
335 | 13x |
checkmate::assert_character(variables$tte) |
336 | 13x |
checkmate::assert_character(variables$is_event) |
337 | 13x |
checkmate::assert_character(variables$arm) |
338 | 13x |
checkmate::assert_character(variables$subgroups, null.ok = TRUE) |
339 | 13x |
checkmate::assert_character(variables$strat, null.ok = TRUE) |
340 | 13x |
assert_df_with_factors(data, list(val = variables$arm), min.levels = 2, max.levels = 2) |
341 | 13x |
assert_df_with_variables(data, variables) |
342 | 13x |
checkmate::assert_string(label_all) |
343 | ||
344 |
# Add All Patients. |
|
345 | 13x |
result_all <- h_coxph_df( |
346 | 13x |
tte = data[[variables$tte]], |
347 | 13x |
is_event = data[[variables$is_event]], |
348 | 13x |
arm = data[[variables$arm]], |
349 | 13x |
strata_data = if (is.null(variables$strat)) NULL else data[variables$strat], |
350 | 13x |
control = control |
351 |
) |
|
352 | 13x |
result_all$subgroup <- label_all |
353 | 13x |
result_all$var <- "ALL" |
354 | 13x |
result_all$var_label <- label_all |
355 | 13x |
result_all$row_type <- "content" |
356 | ||
357 |
# Add Subgroups. |
|
358 | 13x |
if (is.null(variables$subgroups)) { |
359 | 3x |
result_all |
360 |
} else { |
|
361 | 10x |
l_data <- h_split_by_subgroups(data, variables$subgroups, groups_lists = groups_lists) |
362 | ||
363 | 10x |
l_result <- lapply(l_data, function(grp) { |
364 | 47x |
result <- h_coxph_df( |
365 | 47x |
tte = grp$df[[variables$tte]], |
366 | 47x |
is_event = grp$df[[variables$is_event]], |
367 | 47x |
arm = grp$df[[variables$arm]], |
368 | 47x |
strata_data = if (is.null(variables$strat)) NULL else grp$df[variables$strat], |
369 | 47x |
control = control |
370 |
) |
|
371 | 47x |
result_labels <- grp$df_labels[rep(1, times = nrow(result)), ] |
372 | 47x |
cbind(result, result_labels) |
373 |
}) |
|
374 | ||
375 | 10x |
result_subgroups <- do.call(rbind, args = c(l_result, make.row.names = FALSE)) |
376 | 10x |
result_subgroups$row_type <- "analysis" |
377 | ||
378 | 10x |
rbind( |
379 | 10x |
result_all, |
380 | 10x |
result_subgroups |
381 |
) |
|
382 |
} |
|
383 |
} |
|
384 | ||
385 |
#' Split Dataframe by Subgroups |
|
386 |
#' |
|
387 |
#' @description `r lifecycle::badge("stable")` |
|
388 |
#' |
|
389 |
#' Split a dataframe into a non-nested list of subsets. |
|
390 |
#' |
|
391 |
#' @inheritParams argument_convention |
|
392 |
#' @inheritParams survival_duration_subgroups |
|
393 |
#' @param data (`data.frame`)\cr dataset to split. |
|
394 |
#' @param subgroups (`character`)\cr names of factor variables from `data` used to create subsets. |
|
395 |
#' Unused levels not present in `data` are dropped. Note that the order in this vector |
|
396 |
#' determines the order in the downstream table. |
|
397 |
#' |
|
398 |
#' @return A list with subset data (`df`) and metadata about the subset (`df_labels`). |
|
399 |
#' |
|
400 |
#' @details Main functionality is to prepare data for use in forest plot layouts. |
|
401 |
#' |
|
402 |
#' @examples |
|
403 |
#' df <- data.frame( |
|
404 |
#' x = c(1:5), |
|
405 |
#' y = factor(c("A", "B", "A", "B", "A"), levels = c("A", "B", "C")), |
|
406 |
#' z = factor(c("C", "C", "D", "D", "D"), levels = c("D", "C")) |
|
407 |
#' ) |
|
408 |
#' formatters::var_labels(df) <- paste("label for", names(df)) |
|
409 |
#' |
|
410 |
#' h_split_by_subgroups( |
|
411 |
#' data = df, |
|
412 |
#' subgroups = c("y", "z") |
|
413 |
#' ) |
|
414 |
#' |
|
415 |
#' h_split_by_subgroups( |
|
416 |
#' data = df, |
|
417 |
#' subgroups = c("y", "z"), |
|
418 |
#' groups_lists = list( |
|
419 |
#' y = list("AB" = c("A", "B"), "C" = "C") |
|
420 |
#' ) |
|
421 |
#' ) |
|
422 |
#' |
|
423 |
#' @export |
|
424 |
h_split_by_subgroups <- function(data, |
|
425 |
subgroups, |
|
426 |
groups_lists = list()) { |
|
427 | 52x |
checkmate::assert_character(subgroups, min.len = 1, any.missing = FALSE) |
428 | 52x |
checkmate::assert_list(groups_lists, names = "named") |
429 | 52x |
checkmate::assert_subset(names(groups_lists), subgroups) |
430 | 52x |
assert_df_with_factors(data, as.list(stats::setNames(subgroups, subgroups))) |
431 | ||
432 | 52x |
data_labels <- unname(formatters::var_labels(data)) |
433 | 52x |
df_subgroups <- data[, subgroups, drop = FALSE] |
434 | 52x |
subgroup_labels <- formatters::var_labels(df_subgroups, fill = TRUE) |
435 | ||
436 | 52x |
l_labels <- Map(function(grp_i, name_i) { |
437 | 93x |
existing_levels <- levels(droplevels(grp_i)) |
438 | 93x |
grp_levels <- if (name_i %in% names(groups_lists)) { |
439 |
# For this variable groupings are defined. We check which groups are contained in the data. |
|
440 | 11x |
group_list_i <- groups_lists[[name_i]] |
441 | 11x |
group_has_levels <- vapply(group_list_i, function(lvls) any(lvls %in% existing_levels), TRUE) |
442 | 11x |
names(which(group_has_levels)) |
443 |
} else { |
|
444 | 82x |
existing_levels |
445 |
} |
|
446 | 93x |
df_labels <- data.frame( |
447 | 93x |
subgroup = grp_levels, |
448 | 93x |
var = name_i, |
449 | 93x |
var_label = unname(subgroup_labels[name_i]), |
450 | 93x |
stringsAsFactors = FALSE # Rationale is that subgroups may not be unique. |
451 |
) |
|
452 | 52x |
}, df_subgroups, names(df_subgroups)) |
453 | ||
454 |
# Create a dataframe with one row per subgroup. |
|
455 | 52x |
df_labels <- do.call(rbind, args = c(l_labels, make.row.names = FALSE)) |
456 | 52x |
row_label <- paste0(df_labels$var, ".", df_labels$subgroup) |
457 | 52x |
row_split_var <- factor(row_label, levels = row_label) |
458 | ||
459 |
# Create a list of data subsets. |
|
460 | 52x |
lapply(split(df_labels, row_split_var), function(row_i) { |
461 | 233x |
which_row <- if (row_i$var %in% names(groups_lists)) { |
462 | 31x |
data[[row_i$var]] %in% groups_lists[[row_i$var]][[row_i$subgroup]] |
463 |
} else { |
|
464 | 202x |
data[[row_i$var]] == row_i$subgroup |
465 |
} |
|
466 | 233x |
df <- data[which_row, ] |
467 | 233x |
rownames(df) <- NULL |
468 | 233x |
formatters::var_labels(df) <- data_labels |
469 | ||
470 | 233x |
list( |
471 | 233x |
df = df, |
472 | 233x |
df_labels = data.frame(row_i, row.names = NULL) |
473 |
) |
|
474 |
}) |
|
475 |
} |
1 |
#' Helper Function for Deriving Analysis Datasets for `LBT13` and `LBT14` |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Helper function that merges `ADSL` and `ADLB` datasets so that missing lab test records are inserted in the |
|
6 |
#' output dataset. Remember that `na_level` must match the needed pre-processing |
|
7 |
#' done with [df_explicit_na()] to have the desired output. |
|
8 |
#' |
|
9 |
#' @param adsl (`data.frame`)\cr `ADSL` dataframe. |
|
10 |
#' @param adlb (`data.frame`)\cr `ADLB` dataframe. |
|
11 |
#' @param worst_flag (named `vector`)\cr Worst post-baseline lab flag variable. |
|
12 |
#' @param by_visit (`logical`)\cr defaults to `FALSE` to generate worst grade per patient. |
|
13 |
#' If worst grade per patient per visit is specified for `worst_flag`, then |
|
14 |
#' `by_visit` should be `TRUE` to generate worst grade patient per visit. |
|
15 |
#' @param no_fillin_visits (named `character`)\cr Visits that are not considered for post-baseline worst toxicity |
|
16 |
#' grade. Defaults to `c("SCREENING", "BASELINE")`. |
|
17 |
#' |
|
18 |
#' @return `df` containing variables shared between `adlb` and `adsl` along with variables `PARAM`, `PARAMCD`, |
|
19 |
#' `ATOXGR`, and `BTOXGR` relevant for analysis. Optionally, `AVISIT` are `AVISITN` are included when |
|
20 |
#' `by_visit = TRUE` and `no_fillin_visits = c("SCREENING", "BASELINE")`. |
|
21 |
#' |
|
22 |
#' @details In the result data missing records will be created for the following situations: |
|
23 |
#' * Patients who are present in `adsl` but have no lab data in `adlb` (both baseline and post-baseline). |
|
24 |
#' * Patients who do not have any post-baseline lab values. |
|
25 |
#' * Patients without any post-baseline values flagged as the worst. |
|
26 |
#' |
|
27 |
#' @examples |
|
28 |
#' # `h_adsl_adlb_merge_using_worst_flag` |
|
29 |
#' adlb_out <- h_adsl_adlb_merge_using_worst_flag( |
|
30 |
#' tern_ex_adsl, |
|
31 |
#' tern_ex_adlb, |
|
32 |
#' worst_flag = c("WGRHIFL" = "Y") |
|
33 |
#' ) |
|
34 |
#' |
|
35 |
#' # `h_adsl_adlb_merge_using_worst_flag` by visit example |
|
36 |
#' adlb_out_by_visit <- h_adsl_adlb_merge_using_worst_flag( |
|
37 |
#' tern_ex_adsl, |
|
38 |
#' tern_ex_adlb, |
|
39 |
#' worst_flag = c("WGRLOVFL" = "Y"), |
|
40 |
#' by_visit = TRUE |
|
41 |
#' ) |
|
42 |
#' |
|
43 |
#' @export |
|
44 |
h_adsl_adlb_merge_using_worst_flag <- function(adsl, # nolint |
|
45 |
adlb, |
|
46 |
worst_flag = c("WGRHIFL" = "Y"), |
|
47 |
by_visit = FALSE, |
|
48 |
no_fillin_visits = c("SCREENING", "BASELINE")) { |
|
49 | 5x |
col_names <- names(worst_flag) |
50 | 5x |
filter_values <- worst_flag |
51 | ||
52 | 5x |
temp <- Map( |
53 | 5x |
function(x, y) which(adlb[[x]] == y), |
54 | 5x |
col_names, |
55 | 5x |
filter_values |
56 |
) |
|
57 | ||
58 | 5x |
position_satisfy_filters <- Reduce(intersect, temp) |
59 | ||
60 | 5x |
adsl_adlb_common_columns <- intersect(colnames(adsl), colnames(adlb)) |
61 | 5x |
columns_from_adlb <- c("USUBJID", "PARAM", "PARAMCD", "AVISIT", "AVISITN", "ATOXGR", "BTOXGR") |
62 | ||
63 | 5x |
adlb_f <- adlb[position_satisfy_filters, ] %>% |
64 | 5x |
dplyr::filter(!.data[["AVISIT"]] %in% no_fillin_visits) |
65 | 5x |
adlb_f <- adlb_f[, columns_from_adlb] |
66 | ||
67 | 5x |
avisits_grid <- adlb %>% |
68 | 5x |
dplyr::filter(!.data[["AVISIT"]] %in% no_fillin_visits) %>% |
69 | 5x |
dplyr::pull(.data[["AVISIT"]]) %>% |
70 | 5x |
unique() |
71 | ||
72 | 5x |
if (by_visit) { |
73 | 1x |
adsl_lb <- expand.grid( |
74 | 1x |
USUBJID = unique(adsl$USUBJID), |
75 | 1x |
AVISIT = avisits_grid, |
76 | 1x |
PARAMCD = unique(adlb$PARAMCD) |
77 |
) |
|
78 | ||
79 | 1x |
adsl_lb <- adsl_lb %>% |
80 | 1x |
dplyr::left_join(unique(adlb[c("AVISIT", "AVISITN")]), by = "AVISIT") %>% |
81 | 1x |
dplyr::left_join(unique(adlb[c("PARAM", "PARAMCD")]), by = "PARAMCD") |
82 | ||
83 | 1x |
adsl1 <- adsl[, adsl_adlb_common_columns] |
84 | 1x |
adsl_lb <- adsl1 %>% merge(adsl_lb, by = "USUBJID") |
85 | ||
86 | 1x |
by_variables_from_adlb <- c("USUBJID", "AVISIT", "AVISITN", "PARAMCD", "PARAM") |
87 | ||
88 | 1x |
adlb_btoxgr <- adlb %>% |
89 | 1x |
dplyr::select(c("USUBJID", "PARAMCD", "BTOXGR")) %>% |
90 | 1x |
unique() %>% |
91 | 1x |
dplyr::rename("BTOXGR_MAP" = "BTOXGR") |
92 | ||
93 | 1x |
adlb_out <- merge( |
94 | 1x |
adlb_f, |
95 | 1x |
adsl_lb, |
96 | 1x |
by = by_variables_from_adlb, |
97 | 1x |
all = TRUE, |
98 | 1x |
sort = FALSE |
99 |
) |
|
100 | 1x |
adlb_out <- adlb_out %>% |
101 | 1x |
dplyr::left_join(adlb_btoxgr, by = c("USUBJID", "PARAMCD")) %>% |
102 | 1x |
dplyr::mutate(BTOXGR = .data$BTOXGR_MAP) %>% |
103 | 1x |
dplyr::select(-"BTOXGR_MAP") |
104 | ||
105 | 1x |
adlb_var_labels <- c( |
106 | 1x |
formatters::var_labels(adlb[by_variables_from_adlb]), |
107 | 1x |
formatters::var_labels(adlb[columns_from_adlb[!columns_from_adlb %in% by_variables_from_adlb]]), |
108 | 1x |
formatters::var_labels(adsl[adsl_adlb_common_columns[adsl_adlb_common_columns != "USUBJID"]]) |
109 |
) |
|
110 |
} else { |
|
111 | 4x |
adsl_lb <- expand.grid( |
112 | 4x |
USUBJID = unique(adsl$USUBJID), |
113 | 4x |
PARAMCD = unique(adlb$PARAMCD) |
114 |
) |
|
115 | ||
116 | 4x |
adsl_lb <- adsl_lb %>% dplyr::left_join(unique(adlb[c("PARAM", "PARAMCD")]), by = "PARAMCD") |
117 | ||
118 | 4x |
adsl1 <- adsl[, adsl_adlb_common_columns] |
119 | 4x |
adsl_lb <- adsl1 %>% merge(adsl_lb, by = "USUBJID") |
120 | ||
121 | 4x |
by_variables_from_adlb <- c("USUBJID", "PARAMCD", "PARAM") |
122 | ||
123 | 4x |
adlb_out <- merge( |
124 | 4x |
adlb_f, |
125 | 4x |
adsl_lb, |
126 | 4x |
by = by_variables_from_adlb, |
127 | 4x |
all = TRUE, |
128 | 4x |
sort = FALSE |
129 |
) |
|
130 | ||
131 | 4x |
adlb_var_labels <- c( |
132 | 4x |
formatters::var_labels(adlb[by_variables_from_adlb]), |
133 | 4x |
formatters::var_labels(adlb[columns_from_adlb[!columns_from_adlb %in% by_variables_from_adlb]]), |
134 | 4x |
formatters::var_labels(adsl[adsl_adlb_common_columns[adsl_adlb_common_columns != "USUBJID"]]) |
135 |
) |
|
136 |
} |
|
137 | ||
138 | 5x |
adlb_out$ATOXGR <- as.factor(adlb_out$ATOXGR) |
139 | 5x |
adlb_out$BTOXGR <- as.factor(adlb_out$BTOXGR) |
140 | ||
141 | 5x |
formatters::var_labels(adlb_out) <- adlb_var_labels |
142 | ||
143 | 5x |
adlb_out |
144 |
} |
1 |
# Utility functions to cooperate with {rtables} package |
|
2 | ||
3 |
#' Convert Table into Matrix of Strings |
|
4 |
#' |
|
5 |
#' @description `r lifecycle::badge("stable")` |
|
6 |
#' |
|
7 |
#' Helper function to use mostly within tests. `with_spaces`parameter allows |
|
8 |
#' to test not only for content but also indentation and table structure. |
|
9 |
#' `print_txt_to_copy` instead facilitate the testing development by returning a well |
|
10 |
#' formatted text that needs only to be copied and pasted in the expected output. |
|
11 |
#' |
|
12 |
#' @inheritParams formatters::toString |
|
13 |
#' @param x `rtables` table. |
|
14 |
#' @param with_spaces (`logical`)\cr should the tested table keep the indentation and other relevant spaces? |
|
15 |
#' @param print_txt_to_copy (`logical`)\cr utility to have a way to copy the input table directly |
|
16 |
#' into the expected variable instead of copying it too manually. |
|
17 |
#' |
|
18 |
#' @return A `matrix` of `string`s. If `print_txt_to_copy = TRUE` the well formatted printout of the |
|
19 |
#' table will be printed to console, ready to be copied as a expected value. |
|
20 |
#' |
|
21 |
#' @examples |
|
22 |
#' tbl <- basic_table() %>% |
|
23 |
#' split_rows_by("SEX") %>% |
|
24 |
#' split_cols_by("ARM") %>% |
|
25 |
#' analyze("AGE") %>% |
|
26 |
#' build_table(tern_ex_adsl) |
|
27 |
#' |
|
28 |
#' to_string_matrix(tbl, widths = ceiling(propose_column_widths(tbl) / 2)) |
|
29 |
#' |
|
30 |
#' @export |
|
31 |
to_string_matrix <- function(x, widths = NULL, max_width = NULL, |
|
32 |
hsep = formatters::default_hsep(), |
|
33 |
with_spaces = TRUE, print_txt_to_copy = FALSE) { |
|
34 | 5x |
checkmate::assert_flag(with_spaces) |
35 | 5x |
checkmate::assert_flag(print_txt_to_copy) |
36 | 5x |
checkmate::assert_int(max_width, null.ok = TRUE) |
37 | ||
38 | 5x |
if (inherits(x, "MatrixPrintForm")) { |
39 | ! |
tx <- x |
40 |
} else { |
|
41 | 5x |
tx <- matrix_form(x, TRUE) |
42 |
} |
|
43 | ||
44 | 5x |
tf_wrap <- FALSE |
45 | 5x |
if (!is.null(max_width)) { |
46 | ! |
tf_wrap <- TRUE |
47 |
} |
|
48 | ||
49 |
# Producing the matrix to test |
|
50 | 5x |
if (with_spaces) { |
51 | ! |
out <- strsplit(toString(tx, widths = widths, tf_wrap = tf_wrap, max_width = max_width, hsep = hsep), "\\n")[[1]] |
52 |
} else { |
|
53 | 5x |
out <- tx$string |
54 |
} |
|
55 | ||
56 |
# Printing to console formatted output that needs to be copied in "expected" |
|
57 | 5x |
if (print_txt_to_copy) { |
58 | ! |
out_tmp <- out |
59 | ! |
if (!with_spaces) { |
60 | ! |
out_tmp <- apply(out, 1, paste0, collapse = '", "') |
61 |
} |
|
62 | ! |
cat(paste0('c(\n "', paste0(out_tmp, collapse = '",\n "'), '"\n)')) |
63 |
} |
|
64 | ||
65 |
# Return values |
|
66 | 5x |
return(out) |
67 |
} |
|
68 | ||
69 |
#' Blank for Missing Input |
|
70 |
#' |
|
71 |
#' Helper function to use in tabulating model results. |
|
72 |
#' |
|
73 |
#' @param x (`vector`)\cr input for a cell. |
|
74 |
#' |
|
75 |
#' @return An empty `character` vector if all entries in `x` are missing (`NA`), otherwise |
|
76 |
#' the unlisted version of `x`. |
|
77 |
#' |
|
78 |
#' @keywords internal |
|
79 |
unlist_and_blank_na <- function(x) { |
|
80 | 267x |
unl <- unlist(x) |
81 | 267x |
if (all(is.na(unl))) { |
82 | 161x |
character() |
83 |
} else { |
|
84 | 106x |
unl |
85 |
} |
|
86 |
} |
|
87 | ||
88 |
#' Constructor for Content Functions given Data Frame with Flag Input |
|
89 |
#' |
|
90 |
#' This can be useful for tabulating model results. |
|
91 |
#' |
|
92 |
#' @param analysis_var (`string`)\cr variable name for the column containing values to be returned by the |
|
93 |
#' content function. |
|
94 |
#' @param flag_var (`string`)\cr variable name for the logical column identifying which row should be returned. |
|
95 |
#' @param format (`string`)\cr `rtables` format to use. |
|
96 |
#' |
|
97 |
#' @return A content function which gives `df$analysis_var` at the row identified by |
|
98 |
#' `.df_row$flag` in the given format. |
|
99 |
#' |
|
100 |
#' @keywords internal |
|
101 |
cfun_by_flag <- function(analysis_var, |
|
102 |
flag_var, |
|
103 |
format = "xx", |
|
104 |
.indent_mods = NULL) { |
|
105 | 61x |
checkmate::assert_string(analysis_var) |
106 | 61x |
checkmate::assert_string(flag_var) |
107 | 61x |
function(df, labelstr) { |
108 | 265x |
row_index <- which(df[[flag_var]]) |
109 | 265x |
x <- unlist_and_blank_na(df[[analysis_var]][row_index]) |
110 | 265x |
formatters::with_label( |
111 | 265x |
rcell(x, format = format, indent_mod = .indent_mods), |
112 | 265x |
labelstr |
113 |
) |
|
114 |
} |
|
115 |
} |
|
116 | ||
117 |
#' Content Row Function to Add Row Total to Labels |
|
118 |
#' |
|
119 |
#' This takes the label of the latest row split level and adds the row total from `df` in parentheses. |
|
120 |
#' This function differs from [c_label_n_alt()] by taking row counts from `df` rather than |
|
121 |
#' `alt_counts_df`, and is used by [add_rowcounts()] when `alt_counts` is set to `FALSE`. |
|
122 |
#' |
|
123 |
#' @inheritParams argument_convention |
|
124 |
#' |
|
125 |
#' @return A list with formatted [rtables::CellValue()] with the row count value and the correct label. |
|
126 |
#' |
|
127 |
#' @note It is important here to not use `df` but rather `.N_row` in the implementation, because |
|
128 |
#' the former is already split by columns and will refer to the first column of the data only. |
|
129 |
#' |
|
130 |
#' @seealso [c_label_n_alt()] which performs the same function but retrieves row counts from |
|
131 |
#' `alt_counts_df` instead of `df`. |
|
132 |
#' |
|
133 |
#' @keywords internal |
|
134 |
c_label_n <- function(df, |
|
135 |
labelstr, |
|
136 |
.N_row) { # nolint |
|
137 | 270x |
label <- paste0(labelstr, " (N=", .N_row, ")") |
138 | 270x |
in_rows( |
139 | 270x |
.list = list(row_count = formatters::with_label(c(.N_row, .N_row), label)), |
140 | 270x |
.formats = c(row_count = function(x, ...) "") |
141 |
) |
|
142 |
} |
|
143 | ||
144 |
#' Content Row Function to Add `alt_counts_df` Row Total to Labels |
|
145 |
#' |
|
146 |
#' This takes the label of the latest row split level and adds the row total from `alt_counts_df` |
|
147 |
#' in parentheses. This function differs from [c_label_n()] by taking row counts from `alt_counts_df` |
|
148 |
#' rather than `df`, and is used by [add_rowcounts()] when `alt_counts` is set to `TRUE`. |
|
149 |
#' |
|
150 |
#' @inheritParams argument_convention |
|
151 |
#' |
|
152 |
#' @return A list with formatted [rtables::CellValue()] with the row count value and the correct label. |
|
153 |
#' |
|
154 |
#' @seealso [c_label_n()] which performs the same function but retrieves row counts from `df` instead |
|
155 |
#' of `alt_counts_df`. |
|
156 |
#' |
|
157 |
#' @keywords internal |
|
158 |
c_label_n_alt <- function(df, |
|
159 |
labelstr, |
|
160 |
.alt_df_row) { |
|
161 | 7x |
N_row_alt <- nrow(.alt_df_row) # nolint |
162 | 7x |
label <- paste0(labelstr, " (N=", N_row_alt, ")") |
163 | 7x |
in_rows( |
164 | 7x |
.list = list(row_count = formatters::with_label(c(N_row_alt, N_row_alt), label)), |
165 | 7x |
.formats = c(row_count = function(x, ...) "") |
166 |
) |
|
167 |
} |
|
168 | ||
169 |
#' Layout Creating Function to Add Row Total Counts |
|
170 |
#' |
|
171 |
#' @description `r lifecycle::badge("stable")` |
|
172 |
#' |
|
173 |
#' This works analogously to [rtables::add_colcounts()] but on the rows. This function |
|
174 |
#' is a wrapper for [rtables::summarize_row_groups()]. |
|
175 |
#' |
|
176 |
#' @inheritParams argument_convention |
|
177 |
#' @param alt_counts (`flag`)\cr whether row counts should be taken from `alt_counts_df` (`TRUE`) |
|
178 |
#' or from `df` (`FALSE`). Defaults to `FALSE`. |
|
179 |
#' |
|
180 |
#' @return A modified layout where the latest row split labels now have the row-wise |
|
181 |
#' total counts (i.e. without column-based subsetting) attached in parentheses. |
|
182 |
#' |
|
183 |
#' @note Row count values are contained in these row count rows but are not displayed |
|
184 |
#' so that they are not considered zero rows by default when pruning. |
|
185 |
#' |
|
186 |
#' @examples |
|
187 |
#' basic_table() %>% |
|
188 |
#' split_cols_by("ARM") %>% |
|
189 |
#' add_colcounts() %>% |
|
190 |
#' split_rows_by("RACE", split_fun = drop_split_levels) %>% |
|
191 |
#' add_rowcounts() %>% |
|
192 |
#' analyze("AGE", afun = list_wrap_x(summary), format = "xx.xx") %>% |
|
193 |
#' build_table(DM) |
|
194 |
#' |
|
195 |
#' @export |
|
196 |
add_rowcounts <- function(lyt, alt_counts = FALSE) { |
|
197 | 6x |
summarize_row_groups( |
198 | 6x |
lyt, |
199 | 6x |
cfun = if (alt_counts) c_label_n_alt else c_label_n |
200 |
) |
|
201 |
} |
|
202 | ||
203 |
#' Obtain Column Indices |
|
204 |
#' |
|
205 |
#' @description `r lifecycle::badge("stable")` |
|
206 |
#' |
|
207 |
#' Helper function to extract column indices from a `VTableTree` for a given |
|
208 |
#' vector of column names. |
|
209 |
#' |
|
210 |
#' @param table_tree (`VTableTree`)\cr table to extract the indices from. |
|
211 |
#' @param col_names (`character`)\cr vector of column names. |
|
212 |
#' |
|
213 |
#' @return A vector of column indices. |
|
214 |
#' |
|
215 |
#' @export |
|
216 |
h_col_indices <- function(table_tree, col_names) { |
|
217 | 1232x |
checkmate::assert_class(table_tree, "VTableNodeInfo") |
218 | 1232x |
checkmate::assert_subset(col_names, names(attr(col_info(table_tree), "cextra_args")), empty.ok = FALSE) |
219 | 1232x |
match(col_names, names(attr(col_info(table_tree), "cextra_args"))) |
220 |
} |
|
221 | ||
222 |
#' Labels or Names of List Elements |
|
223 |
#' |
|
224 |
#' Internal helper function for working with nested statistic function results which typically |
|
225 |
#' don't have labels but names that we can use. |
|
226 |
#' |
|
227 |
#' @param x a list. |
|
228 |
#' |
|
229 |
#' @return A `character` vector with the labels or names for the list elements. |
|
230 |
#' |
|
231 |
#' @keywords internal |
|
232 |
labels_or_names <- function(x) { |
|
233 | 131x |
checkmate::assert_multi_class(x, c("data.frame", "list")) |
234 | 131x |
labs <- sapply(x, obj_label) |
235 | 131x |
nams <- rlang::names2(x) |
236 | 131x |
label_is_null <- sapply(labs, is.null) |
237 | 131x |
result <- unlist(ifelse(label_is_null, nams, labs)) |
238 | 131x |
return(result) |
239 |
} |
|
240 | ||
241 |
#' Convert to `rtable` |
|
242 |
#' |
|
243 |
#' @description `r lifecycle::badge("stable")` |
|
244 |
#' |
|
245 |
#' This is a new generic function to convert objects to `rtable` tables. |
|
246 |
#' |
|
247 |
#' @param x the object which should be converted to an `rtable`. |
|
248 |
#' @param ... additional arguments for methods. |
|
249 |
#' |
|
250 |
#' @return An `rtables` table object. Note that the concrete class will depend on the method used. |
|
251 |
#' |
|
252 |
#' @export |
|
253 |
as.rtable <- function(x, ...) { # nolint |
|
254 | 3x |
UseMethod("as.rtable", x) |
255 |
} |
|
256 | ||
257 |
#' @describeIn as.rtable method for converting `data.frame` that contain numeric columns to `rtable`. |
|
258 |
#' |
|
259 |
#' @param format the format which should be used for the columns. |
|
260 |
#' |
|
261 |
#' @method as.rtable data.frame |
|
262 |
#' |
|
263 |
#' @examples |
|
264 |
#' x <- data.frame( |
|
265 |
#' a = 1:10, |
|
266 |
#' b = rnorm(10) |
|
267 |
#' ) |
|
268 |
#' as.rtable(x) |
|
269 |
#' |
|
270 |
#' @export |
|
271 |
as.rtable.data.frame <- function(x, format = "xx.xx", ...) { |
|
272 | 3x |
checkmate::assert_numeric(unlist(x)) |
273 | 2x |
do.call( |
274 | 2x |
rtable, |
275 | 2x |
c( |
276 | 2x |
list( |
277 | 2x |
header = labels_or_names(x), |
278 | 2x |
format = format |
279 |
), |
|
280 | 2x |
Map( |
281 | 2x |
function(row, row_name) { |
282 | 20x |
do.call( |
283 | 20x |
rrow, |
284 | 20x |
c(as.list(unname(row)), |
285 | 20x |
row.name = row_name |
286 |
) |
|
287 |
) |
|
288 |
}, |
|
289 | 2x |
row = as.data.frame(t(x)), |
290 | 2x |
row_name = rownames(x) |
291 |
) |
|
292 |
) |
|
293 |
) |
|
294 |
} |
|
295 | ||
296 |
#' Split parameters |
|
297 |
#' |
|
298 |
#' @description `r lifecycle::badge("stable")` |
|
299 |
#' |
|
300 |
#' It divides the data in the vector `param` into the groups defined by `f` based on specified `values`. It is relevant |
|
301 |
#' in `rtables` layers so as to distribute parameters `.stats` or' `.formats` into lists with items corresponding to |
|
302 |
#' specific analysis function. |
|
303 |
#' |
|
304 |
#' @param param (`vector`)\cr the parameter to be split. |
|
305 |
#' @param value (`vector`)\cr the value used to split. |
|
306 |
#' @param f (`list` of `vectors`)\cr the reference to make the split |
|
307 |
#' |
|
308 |
#' @return A named `list` with the same element names as `f`, each containing the elements specified in `.stats`. |
|
309 |
#' |
|
310 |
#' @examples |
|
311 |
#' f <- list( |
|
312 |
#' surv = c("pt_at_risk", "event_free_rate", "rate_se", "rate_ci"), |
|
313 |
#' surv_diff = c("rate_diff", "rate_diff_ci", "ztest_pval") |
|
314 |
#' ) |
|
315 |
#' |
|
316 |
#' .stats <- c("pt_at_risk", "rate_diff") |
|
317 |
#' h_split_param(.stats, .stats, f = f) |
|
318 |
#' |
|
319 |
#' # $surv |
|
320 |
#' # [1] "pt_at_risk" |
|
321 |
#' # |
|
322 |
#' # $surv_diff |
|
323 |
#' # [1] "rate_diff" |
|
324 |
#' |
|
325 |
#' .formats <- c("pt_at_risk" = "xx", "event_free_rate" = "xxx") |
|
326 |
#' h_split_param(.formats, names(.formats), f = f) |
|
327 |
#' |
|
328 |
#' # $surv |
|
329 |
#' # pt_at_risk event_free_rate |
|
330 |
#' # "xx" "xxx" |
|
331 |
#' # |
|
332 |
#' # $surv_diff |
|
333 |
#' # NULL |
|
334 |
#' |
|
335 |
#' @export |
|
336 |
h_split_param <- function(param, |
|
337 |
value, |
|
338 |
f) { |
|
339 | 25x |
y <- lapply(f, function(x) param[value %in% x]) |
340 | 25x |
lapply(y, function(x) if (length(x) == 0) NULL else x) |
341 |
} |
|
342 | ||
343 |
#' Get Selected Statistics Names |
|
344 |
#' |
|
345 |
#' Helper function to be used for creating `afun`. |
|
346 |
#' |
|
347 |
#' @param .stats (`vector` or `NULL`)\cr input to the layout creating function. Note that `NULL` means |
|
348 |
#' in this context that all default statistics should be used. |
|
349 |
#' @param all_stats (`character`)\cr all statistics which can be selected here potentially. |
|
350 |
#' |
|
351 |
#' @return A `character` vector with the selected statistics. |
|
352 |
#' |
|
353 |
#' @keywords internal |
|
354 |
afun_selected_stats <- function(.stats, all_stats) { |
|
355 | 2x |
checkmate::assert_character(.stats, null.ok = TRUE) |
356 | 2x |
checkmate::assert_character(all_stats) |
357 | 2x |
if (is.null(.stats)) { |
358 | 1x |
all_stats |
359 |
} else { |
|
360 | 1x |
intersect(.stats, all_stats) |
361 |
} |
|
362 |
} |
|
363 | ||
364 |
#' Add Variable Labels to Top Left Corner in Table |
|
365 |
#' |
|
366 |
#' @description `r lifecycle::badge("stable")` |
|
367 |
#' |
|
368 |
#' Helper layout creating function to just append the variable labels of a given variables vector |
|
369 |
#' from a given dataset in the top left corner. If a variable label is not found then the |
|
370 |
#' variable name itself is used instead. Multiple variable labels are concatenated with slashes. |
|
371 |
#' |
|
372 |
#' @inheritParams argument_convention |
|
373 |
#' @param vars (`character`)\cr variable names of which the labels are to be looked up in `df`. |
|
374 |
#' @param indent (`integer`)\cr non-negative number of nested indent space, default to 0L which means no indent. |
|
375 |
#' 1L means two spaces indent, 2L means four spaces indent and so on. |
|
376 |
#' |
|
377 |
#' @return A modified layout with the new variable label(s) added to the top-left material. |
|
378 |
#' |
|
379 |
#' @note This is not an optimal implementation of course, since we are using here the data set |
|
380 |
#' itself during the layout creation. When we have a more mature `rtables` implementation then |
|
381 |
#' this will also be improved or not necessary anymore. |
|
382 |
#' |
|
383 |
#' @examples |
|
384 |
#' lyt <- basic_table() %>% |
|
385 |
#' split_cols_by("ARM") %>% |
|
386 |
#' add_colcounts() %>% |
|
387 |
#' split_rows_by("SEX") %>% |
|
388 |
#' append_varlabels(DM, "SEX") %>% |
|
389 |
#' analyze("AGE", afun = mean) %>% |
|
390 |
#' append_varlabels(DM, "AGE", indent = 1) |
|
391 |
#' build_table(lyt, DM) |
|
392 |
#' |
|
393 |
#' lyt <- basic_table() %>% |
|
394 |
#' split_cols_by("ARM") %>% |
|
395 |
#' split_rows_by("SEX") %>% |
|
396 |
#' analyze("AGE", afun = mean) %>% |
|
397 |
#' append_varlabels(DM, c("SEX", "AGE")) |
|
398 |
#' build_table(lyt, DM) |
|
399 |
#' |
|
400 |
#' @export |
|
401 |
append_varlabels <- function(lyt, df, vars, indent = 0L) { |
|
402 | 3x |
if (checkmate::test_flag(indent)) { |
403 | ! |
warning("indent argument is now accepting integers. Boolean indent will be converted to integers.") |
404 | ! |
indent <- as.integer(indent) |
405 |
} |
|
406 | ||
407 | 3x |
checkmate::assert_data_frame(df) |
408 | 3x |
checkmate::assert_character(vars) |
409 | 3x |
checkmate::assert_count(indent) |
410 | ||
411 | 3x |
lab <- formatters::var_labels(df[vars], fill = TRUE) |
412 | 3x |
lab <- paste(lab, collapse = " / ") |
413 | 3x |
space <- paste(rep(" ", indent * 2), collapse = "") |
414 | 3x |
lab <- paste0(space, lab) |
415 | ||
416 | 3x |
append_topleft(lyt, lab) |
417 |
} |
|
418 | ||
419 |
#' Default string replacement for `NA` values |
|
420 |
#' |
|
421 |
#' @description `r lifecycle::badge("stable")` |
|
422 |
#' |
|
423 |
#' The default string used to represent `NA` values. This value is used as the default |
|
424 |
#' value for the `na_str` argument throughout the `tern` package, and printed in place |
|
425 |
#' of `NA` values in output tables. If not specified for each `tern` function by the user |
|
426 |
#' via the `na_str` argument, or in the R environment options via [set_default_na_str()], |
|
427 |
#' then `NA` is used. |
|
428 |
#' |
|
429 |
#' @param na_str (`string`)\cr Single string value to set in the R environment options as |
|
430 |
#' the default value to replace `NA`s. Use `getOption("tern_default_na_str")` to check the |
|
431 |
#' current value set in the R environment (defaults to `NULL` if not set). |
|
432 |
#' |
|
433 |
#' @name default_na_str |
|
434 |
NULL |
|
435 | ||
436 |
#' @describeIn default_na_str Getter for default `NA` value replacement string. |
|
437 |
#' |
|
438 |
#' @return |
|
439 |
#' * `default_na_str` returns the current value if an R environment option has been set |
|
440 |
#' for `"tern_default_na_str"`, or `NA_character_` otherwise. |
|
441 |
#' |
|
442 |
#' @examples |
|
443 |
#' # Default settings |
|
444 |
#' default_na_str() |
|
445 |
#' getOption("tern_default_na_str") |
|
446 |
#' |
|
447 |
#' # Set custom value |
|
448 |
#' set_default_na_str("<Missing>") |
|
449 |
#' |
|
450 |
#' # Settings after value has been set |
|
451 |
#' default_na_str() |
|
452 |
#' getOption("tern_default_na_str") |
|
453 |
#' |
|
454 |
#' @export |
|
455 |
default_na_str <- function() { |
|
456 | 242x |
getOption("tern_default_na_str", default = NA_character_) |
457 |
} |
|
458 | ||
459 |
#' @describeIn default_na_str Setter for default `NA` value replacement string. Sets the |
|
460 |
#' option `"tern_default_na_str"` within the R environment. |
|
461 |
#' |
|
462 |
#' @return |
|
463 |
#' * `set_default_na_str` has no return value. |
|
464 |
#' |
|
465 |
#' @export |
|
466 |
set_default_na_str <- function(na_str) { |
|
467 | 3x |
checkmate::assert_character(na_str, len = 1, null.ok = TRUE) |
468 | 3x |
options("tern_default_na_str" = na_str) |
469 |
} |
1 |
#' Helper Functions for Tabulating Binary Response by Subgroup |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Helper functions that tabulate in a data frame statistics such as response rate |
|
6 |
#' and odds ratio for population subgroups. |
|
7 |
#' |
|
8 |
#' @inheritParams argument_convention |
|
9 |
#' @inheritParams response_subgroups |
|
10 |
#' @param arm (`factor`)\cr the treatment group variable. |
|
11 |
#' |
|
12 |
#' @details Main functionality is to prepare data for use in a layout-creating function. |
|
13 |
#' |
|
14 |
#' @examples |
|
15 |
#' library(dplyr) |
|
16 |
#' library(forcats) |
|
17 |
#' |
|
18 |
#' adrs <- tern_ex_adrs |
|
19 |
#' adrs_labels <- formatters::var_labels(adrs) |
|
20 |
#' |
|
21 |
#' adrs_f <- adrs %>% |
|
22 |
#' filter(PARAMCD == "BESRSPI") %>% |
|
23 |
#' filter(ARM %in% c("A: Drug X", "B: Placebo")) %>% |
|
24 |
#' droplevels() %>% |
|
25 |
#' mutate( |
|
26 |
#' # Reorder levels of factor to make the placebo group the reference arm. |
|
27 |
#' ARM = fct_relevel(ARM, "B: Placebo"), |
|
28 |
#' rsp = AVALC == "CR" |
|
29 |
#' ) |
|
30 |
#' formatters::var_labels(adrs_f) <- c(adrs_labels, "Response") |
|
31 |
#' |
|
32 |
#' @name h_response_subgroups |
|
33 |
NULL |
|
34 | ||
35 |
#' @describeIn h_response_subgroups helper to prepare a data frame of binary responses by arm. |
|
36 |
#' |
|
37 |
#' @return |
|
38 |
#' * `h_proportion_df()` returns a `data.frame` with columns `arm`, `n`, `n_rsp`, and `prop`. |
|
39 |
#' |
|
40 |
#' @examples |
|
41 |
#' h_proportion_df( |
|
42 |
#' c(TRUE, FALSE, FALSE), |
|
43 |
#' arm = factor(c("A", "A", "B"), levels = c("A", "B")) |
|
44 |
#' ) |
|
45 |
#' |
|
46 |
#' @export |
|
47 |
h_proportion_df <- function(rsp, arm) { |
|
48 | 64x |
checkmate::assert_logical(rsp) |
49 | 63x |
assert_valid_factor(arm, len = length(rsp)) |
50 | 63x |
non_missing_rsp <- !is.na(rsp) |
51 | 63x |
rsp <- rsp[non_missing_rsp] |
52 | 63x |
arm <- arm[non_missing_rsp] |
53 | ||
54 | 63x |
lst_rsp <- split(rsp, arm) |
55 | 63x |
lst_results <- Map(function(x, arm) { |
56 | 126x |
if (length(x) > 0) { |
57 | 124x |
s_prop <- s_proportion(df = x) |
58 | 124x |
data.frame( |
59 | 124x |
arm = arm, |
60 | 124x |
n = length(x), |
61 | 124x |
n_rsp = unname(s_prop$n_prop[1]), |
62 | 124x |
prop = unname(s_prop$n_prop[2]), |
63 | 124x |
stringsAsFactors = FALSE |
64 |
) |
|
65 |
} else { |
|
66 | 2x |
data.frame( |
67 | 2x |
arm = arm, |
68 | 2x |
n = 0L, |
69 | 2x |
n_rsp = NA, |
70 | 2x |
prop = NA, |
71 | 2x |
stringsAsFactors = FALSE |
72 |
) |
|
73 |
} |
|
74 | 63x |
}, lst_rsp, names(lst_rsp)) |
75 | ||
76 | 63x |
df <- do.call(rbind, args = c(lst_results, make.row.names = FALSE)) |
77 | 63x |
df$arm <- factor(df$arm, levels = levels(arm)) |
78 | 63x |
df |
79 |
} |
|
80 | ||
81 |
#' @describeIn h_response_subgroups summarizes proportion of binary responses by arm and across subgroups |
|
82 |
#' in a data frame. `variables` corresponds to the names of variables found in `data`, passed as a named list and |
|
83 |
#' requires elements `rsp`, `arm` and optionally `subgroups`. `groups_lists` optionally specifies |
|
84 |
#' groupings for `subgroups` variables. |
|
85 |
#' |
|
86 |
#' @return |
|
87 |
#' * `h_proportion_subgroups_df()` returns a `data.frame` with columns `arm`, `n`, `n_rsp`, `prop`, `subgroup`, |
|
88 |
#' `var`, `var_label`, and `row_type`. |
|
89 |
#' |
|
90 |
#' @examples |
|
91 |
#' h_proportion_subgroups_df( |
|
92 |
#' variables = list(rsp = "rsp", arm = "ARM", subgroups = c("SEX", "BMRKR2")), |
|
93 |
#' data = adrs_f |
|
94 |
#' ) |
|
95 |
#' |
|
96 |
#' # Define groupings for BMRKR2 levels. |
|
97 |
#' h_proportion_subgroups_df( |
|
98 |
#' variables = list(rsp = "rsp", arm = "ARM", subgroups = c("SEX", "BMRKR2")), |
|
99 |
#' data = adrs_f, |
|
100 |
#' groups_lists = list( |
|
101 |
#' BMRKR2 = list( |
|
102 |
#' "low" = "LOW", |
|
103 |
#' "low/medium" = c("LOW", "MEDIUM"), |
|
104 |
#' "low/medium/high" = c("LOW", "MEDIUM", "HIGH") |
|
105 |
#' ) |
|
106 |
#' ) |
|
107 |
#' ) |
|
108 |
#' |
|
109 |
#' @export |
|
110 |
h_proportion_subgroups_df <- function(variables, |
|
111 |
data, |
|
112 |
groups_lists = list(), |
|
113 |
label_all = "All Patients") { |
|
114 | 14x |
checkmate::assert_character(variables$rsp) |
115 | 14x |
checkmate::assert_character(variables$arm) |
116 | 14x |
checkmate::assert_character(variables$subgroups, null.ok = TRUE) |
117 | 14x |
assert_df_with_factors(data, list(val = variables$arm), min.levels = 2, max.levels = 2) |
118 | 14x |
assert_df_with_variables(data, variables) |
119 | 14x |
checkmate::assert_string(label_all) |
120 | ||
121 |
# Add All Patients. |
|
122 | 14x |
result_all <- h_proportion_df(data[[variables$rsp]], data[[variables$arm]]) |
123 | 14x |
result_all$subgroup <- label_all |
124 | 14x |
result_all$var <- "ALL" |
125 | 14x |
result_all$var_label <- label_all |
126 | 14x |
result_all$row_type <- "content" |
127 | ||
128 |
# Add Subgroups. |
|
129 | 14x |
if (is.null(variables$subgroups)) { |
130 | 3x |
result_all |
131 |
} else { |
|
132 | 11x |
l_data <- h_split_by_subgroups(data, variables$subgroups, groups_lists = groups_lists) |
133 | ||
134 | 11x |
l_result <- lapply(l_data, function(grp) { |
135 | 46x |
result <- h_proportion_df(grp$df[[variables$rsp]], grp$df[[variables$arm]]) |
136 | 46x |
result_labels <- grp$df_labels[rep(1, times = nrow(result)), ] |
137 | 46x |
cbind(result, result_labels) |
138 |
}) |
|
139 | 11x |
result_subgroups <- do.call(rbind, args = c(l_result, make.row.names = FALSE)) |
140 | 11x |
result_subgroups$row_type <- "analysis" |
141 | ||
142 | 11x |
rbind( |
143 | 11x |
result_all, |
144 | 11x |
result_subgroups |
145 |
) |
|
146 |
} |
|
147 |
} |
|
148 | ||
149 |
#' @describeIn h_response_subgroups helper to prepare a data frame with estimates of |
|
150 |
#' the odds ratio between a treatment and a control arm. |
|
151 |
#' |
|
152 |
#' @inheritParams response_subgroups |
|
153 |
#' @param strata_data (`factor`, `data.frame` or `NULL`)\cr required if stratified analysis is performed. |
|
154 |
#' |
|
155 |
#' @return |
|
156 |
#' * `h_odds_ratio_df()` returns a `data.frame` with columns `arm`, `n_tot`, `or`, `lcl`, `ucl`, `conf_level`, and |
|
157 |
#' optionally `pval` and `pval_label`. |
|
158 |
#' |
|
159 |
#' @examples |
|
160 |
#' # Unstratatified analysis. |
|
161 |
#' h_odds_ratio_df( |
|
162 |
#' c(TRUE, FALSE, FALSE, TRUE), |
|
163 |
#' arm = factor(c("A", "A", "B", "B"), levels = c("A", "B")) |
|
164 |
#' ) |
|
165 |
#' |
|
166 |
#' # Include p-value. |
|
167 |
#' h_odds_ratio_df(adrs_f$rsp, adrs_f$ARM, method = "chisq") |
|
168 |
#' |
|
169 |
#' # Stratatified analysis. |
|
170 |
#' h_odds_ratio_df( |
|
171 |
#' rsp = adrs_f$rsp, |
|
172 |
#' arm = adrs_f$ARM, |
|
173 |
#' strata_data = adrs_f[, c("STRATA1", "STRATA2")], |
|
174 |
#' method = "cmh" |
|
175 |
#' ) |
|
176 |
#' |
|
177 |
#' @export |
|
178 |
h_odds_ratio_df <- function(rsp, arm, strata_data = NULL, conf_level = 0.95, method = NULL) { |
|
179 | 69x |
assert_valid_factor(arm, n.levels = 2, len = length(rsp)) |
180 | ||
181 | 69x |
df_rsp <- data.frame( |
182 | 69x |
rsp = rsp, |
183 | 69x |
arm = arm |
184 |
) |
|
185 | ||
186 | 69x |
if (!is.null(strata_data)) { |
187 | 11x |
strata_var <- interaction(strata_data, drop = TRUE) |
188 | 11x |
strata_name <- "strata" |
189 | ||
190 | 11x |
assert_valid_factor(strata_var, len = nrow(df_rsp)) |
191 | ||
192 | 11x |
df_rsp[[strata_name]] <- strata_var |
193 |
} else { |
|
194 | 58x |
strata_name <- NULL |
195 |
} |
|
196 | ||
197 | 69x |
l_df <- split(df_rsp, arm) |
198 | ||
199 | 69x |
if (nrow(l_df[[1]]) > 0 && nrow(l_df[[2]]) > 0) { |
200 |
# Odds ratio and CI. |
|
201 | 67x |
result_odds_ratio <- s_odds_ratio( |
202 | 67x |
df = l_df[[2]], |
203 | 67x |
.var = "rsp", |
204 | 67x |
.ref_group = l_df[[1]], |
205 | 67x |
.in_ref_col = FALSE, |
206 | 67x |
.df_row = df_rsp, |
207 | 67x |
variables = list(arm = "arm", strata = strata_name), |
208 | 67x |
conf_level = conf_level |
209 |
) |
|
210 | ||
211 | 67x |
df <- data.frame( |
212 |
# Dummy column needed downstream to create a nested header. |
|
213 | 67x |
arm = " ", |
214 | 67x |
n_tot = unname(result_odds_ratio$n_tot["n_tot"]), |
215 | 67x |
or = unname(result_odds_ratio$or_ci["est"]), |
216 | 67x |
lcl = unname(result_odds_ratio$or_ci["lcl"]), |
217 | 67x |
ucl = unname(result_odds_ratio$or_ci["ucl"]), |
218 | 67x |
conf_level = conf_level, |
219 | 67x |
stringsAsFactors = FALSE |
220 |
) |
|
221 | ||
222 | 67x |
if (!is.null(method)) { |
223 |
# Test for difference. |
|
224 | 34x |
result_test <- s_test_proportion_diff( |
225 | 34x |
df = l_df[[2]], |
226 | 34x |
.var = "rsp", |
227 | 34x |
.ref_group = l_df[[1]], |
228 | 34x |
.in_ref_col = FALSE, |
229 | 34x |
variables = list(strata = strata_name), |
230 | 34x |
method = method |
231 |
) |
|
232 | ||
233 | 34x |
df$pval <- as.numeric(result_test$pval) |
234 | 34x |
df$pval_label <- obj_label(result_test$pval) |
235 |
} |
|
236 | ||
237 |
# In those cases cannot go through the model so will obtain n_tot from data. |
|
238 |
} else if ( |
|
239 | 2x |
(nrow(l_df[[1]]) == 0 && nrow(l_df[[2]]) > 0) || |
240 | 2x |
(nrow(l_df[[1]]) > 0 && nrow(l_df[[2]]) == 0) |
241 |
) { |
|
242 | 2x |
df <- data.frame( |
243 |
# Dummy column needed downstream to create a nested header. |
|
244 | 2x |
arm = " ", |
245 | 2x |
n_tot = sum(stats::complete.cases(df_rsp)), |
246 | 2x |
or = NA, |
247 | 2x |
lcl = NA, |
248 | 2x |
ucl = NA, |
249 | 2x |
conf_level = conf_level, |
250 | 2x |
stringsAsFactors = FALSE |
251 |
) |
|
252 | 2x |
if (!is.null(method)) { |
253 | 2x |
df$pval <- NA |
254 | 2x |
df$pval_label <- NA |
255 |
} |
|
256 |
} else { |
|
257 | ! |
df <- data.frame( |
258 |
# Dummy column needed downstream to create a nested header. |
|
259 | ! |
arm = " ", |
260 | ! |
n_tot = 0L, |
261 | ! |
or = NA, |
262 | ! |
lcl = NA, |
263 | ! |
ucl = NA, |
264 | ! |
conf_level = conf_level, |
265 | ! |
stringsAsFactors = FALSE |
266 |
) |
|
267 | ||
268 | ! |
if (!is.null(method)) { |
269 | ! |
df$pval <- NA |
270 | ! |
df$pval_label <- NA |
271 |
} |
|
272 |
} |
|
273 | ||
274 | 69x |
df |
275 |
} |
|
276 | ||
277 |
#' @describeIn h_response_subgroups summarizes estimates of the odds ratio between a treatment and a control |
|
278 |
#' arm across subgroups in a data frame. `variables` corresponds to the names of variables found in |
|
279 |
#' `data`, passed as a named list and requires elements `rsp`, `arm` and optionally `subgroups` |
|
280 |
#' and `strat`. `groups_lists` optionally specifies groupings for `subgroups` variables. |
|
281 |
#' |
|
282 |
#' @return |
|
283 |
#' * `h_odds_ratio_subgroups_df()` returns a `data.frame` with columns `arm`, `n_tot`, `or`, `lcl`, `ucl`, |
|
284 |
#' `conf_level`, `subgroup`, `var`, `var_label`, and `row_type`. |
|
285 |
#' |
|
286 |
#' @examples |
|
287 |
#' # Unstratified analysis. |
|
288 |
#' h_odds_ratio_subgroups_df( |
|
289 |
#' variables = list(rsp = "rsp", arm = "ARM", subgroups = c("SEX", "BMRKR2")), |
|
290 |
#' data = adrs_f |
|
291 |
#' ) |
|
292 |
#' |
|
293 |
#' # Stratified analysis. |
|
294 |
#' h_odds_ratio_subgroups_df( |
|
295 |
#' variables = list( |
|
296 |
#' rsp = "rsp", |
|
297 |
#' arm = "ARM", |
|
298 |
#' subgroups = c("SEX", "BMRKR2"), |
|
299 |
#' strat = c("STRATA1", "STRATA2") |
|
300 |
#' ), |
|
301 |
#' data = adrs_f |
|
302 |
#' ) |
|
303 |
#' |
|
304 |
#' # Define groupings of BMRKR2 levels. |
|
305 |
#' h_odds_ratio_subgroups_df( |
|
306 |
#' variables = list( |
|
307 |
#' rsp = "rsp", |
|
308 |
#' arm = "ARM", |
|
309 |
#' subgroups = c("SEX", "BMRKR2") |
|
310 |
#' ), |
|
311 |
#' data = adrs_f, |
|
312 |
#' groups_lists = list( |
|
313 |
#' BMRKR2 = list( |
|
314 |
#' "low" = "LOW", |
|
315 |
#' "low/medium" = c("LOW", "MEDIUM"), |
|
316 |
#' "low/medium/high" = c("LOW", "MEDIUM", "HIGH") |
|
317 |
#' ) |
|
318 |
#' ) |
|
319 |
#' ) |
|
320 |
#' |
|
321 |
#' @export |
|
322 |
h_odds_ratio_subgroups_df <- function(variables, |
|
323 |
data, |
|
324 |
groups_lists = list(), |
|
325 |
conf_level = 0.95, |
|
326 |
method = NULL, |
|
327 |
label_all = "All Patients") { |
|
328 | 15x |
checkmate::assert_character(variables$rsp) |
329 | 15x |
checkmate::assert_character(variables$arm) |
330 | 15x |
checkmate::assert_character(variables$subgroups, null.ok = TRUE) |
331 | 15x |
checkmate::assert_character(variables$strat, null.ok = TRUE) |
332 | 15x |
assert_df_with_factors(data, list(val = variables$arm), min.levels = 2, max.levels = 2) |
333 | 15x |
assert_df_with_variables(data, variables) |
334 | 15x |
checkmate::assert_string(label_all) |
335 | ||
336 | 15x |
strata_data <- if (is.null(variables$strat)) { |
337 | 13x |
NULL |
338 |
} else { |
|
339 | 2x |
data[, variables$strat, drop = FALSE] |
340 |
} |
|
341 | ||
342 |
# Add All Patients. |
|
343 | 15x |
result_all <- h_odds_ratio_df( |
344 | 15x |
rsp = data[[variables$rsp]], |
345 | 15x |
arm = data[[variables$arm]], |
346 | 15x |
strata_data = strata_data, |
347 | 15x |
conf_level = conf_level, |
348 | 15x |
method = method |
349 |
) |
|
350 | 15x |
result_all$subgroup <- label_all |
351 | 15x |
result_all$var <- "ALL" |
352 | 15x |
result_all$var_label <- label_all |
353 | 15x |
result_all$row_type <- "content" |
354 | ||
355 | 15x |
if (is.null(variables$subgroups)) { |
356 | 3x |
result_all |
357 |
} else { |
|
358 | 12x |
l_data <- h_split_by_subgroups(data, variables$subgroups, groups_lists = groups_lists) |
359 | ||
360 | 12x |
l_result <- lapply(l_data, function(grp) { |
361 | 50x |
grp_strata_data <- if (is.null(variables$strat)) { |
362 | 42x |
NULL |
363 |
} else { |
|
364 | 8x |
grp$df[, variables$strat, drop = FALSE] |
365 |
} |
|
366 | ||
367 | 50x |
result <- h_odds_ratio_df( |
368 | 50x |
rsp = grp$df[[variables$rsp]], |
369 | 50x |
arm = grp$df[[variables$arm]], |
370 | 50x |
strata_data = grp_strata_data, |
371 | 50x |
conf_level = conf_level, |
372 | 50x |
method = method |
373 |
) |
|
374 | 50x |
result_labels <- grp$df_labels[rep(1, times = nrow(result)), ] |
375 | 50x |
cbind(result, result_labels) |
376 |
}) |
|
377 | ||
378 | 12x |
result_subgroups <- do.call(rbind, args = c(l_result, make.row.names = FALSE)) |
379 | 12x |
result_subgroups$row_type <- "analysis" |
380 | ||
381 | 12x |
rbind( |
382 | 12x |
result_all, |
383 | 12x |
result_subgroups |
384 |
) |
|
385 |
} |
|
386 |
} |
1 |
#' Re-implemented [range()] Default S3 method for numerical objects |
|
2 |
#' |
|
3 |
#' This function returns `c(NA, NA)` instead of `c(-Inf, Inf)` for zero-length data |
|
4 |
#' without any warnings. |
|
5 |
#' |
|
6 |
#' @param x (`numeric`)\cr a sequence of numbers for which the range is computed. |
|
7 |
#' @param na.rm (`logical`)\cr indicating if `NA` should be omitted. |
|
8 |
#' @param finite (`logical`)\cr indicating if non-finite elements should be removed. |
|
9 |
#' |
|
10 |
#' @return A 2-element vector of class `numeric`. |
|
11 |
#' |
|
12 |
#' @keywords internal |
|
13 |
range_noinf <- function(x, na.rm = FALSE, finite = FALSE) { # nolint |
|
14 | ||
15 | 953x |
checkmate::assert_numeric(x) |
16 | ||
17 | 953x |
if (finite) { |
18 | 24x |
x <- x[is.finite(x)] # removes NAs too |
19 | 929x |
} else if (na.rm) { |
20 | 558x |
x <- x[!is.na(x)] |
21 |
} |
|
22 | ||
23 | 953x |
if (length(x) == 0) { |
24 | 52x |
rval <- c(NA, NA) |
25 | 52x |
mode(rval) <- typeof(x) |
26 |
} else { |
|
27 | 901x |
rval <- c(min(x, na.rm = FALSE), max(x, na.rm = FALSE)) |
28 |
} |
|
29 | ||
30 | 953x |
return(rval) |
31 |
} |
|
32 | ||
33 |
#' Utility function to create label for confidence interval |
|
34 |
#' |
|
35 |
#' @description `r lifecycle::badge("stable")` |
|
36 |
#' |
|
37 |
#' @inheritParams argument_convention |
|
38 |
#' |
|
39 |
#' @return A `string`. |
|
40 |
#' |
|
41 |
#' @export |
|
42 |
f_conf_level <- function(conf_level) { |
|
43 | 1514x |
assert_proportion_value(conf_level) |
44 | 1512x |
paste0(conf_level * 100, "% CI") |
45 |
} |
|
46 | ||
47 |
#' Utility function to create label for p-value |
|
48 |
#' |
|
49 |
#' @description `r lifecycle::badge("stable")` |
|
50 |
#' |
|
51 |
#' @param test_mean (`number`)\cr mean value to test under the null hypothesis. |
|
52 |
#' |
|
53 |
#' @return A `string`. |
|
54 |
#' |
|
55 |
#' @export |
|
56 |
f_pval <- function(test_mean) { |
|
57 | 363x |
checkmate::assert_numeric(test_mean, len = 1) |
58 | 361x |
paste0("p-value (H0: mean = ", test_mean, ")") |
59 |
} |
|
60 | ||
61 |
#' Utility function to return a named list of covariate names. |
|
62 |
#' |
|
63 |
#' @param covariates (`character`)\cr a vector that can contain single variable names (such as |
|
64 |
#' `"X1"`), and/or interaction terms indicated by `"X1 * X2"`. |
|
65 |
#' |
|
66 |
#' @return A named `list` of `character` vector. |
|
67 |
#' |
|
68 |
#' @keywords internal |
|
69 |
get_covariates <- function(covariates) { |
|
70 | 14x |
checkmate::assert_character(covariates) |
71 | 12x |
cov_vars <- unique(trimws(unlist(strsplit(covariates, "\\*")))) |
72 | 12x |
stats::setNames(as.list(cov_vars), cov_vars) |
73 |
} |
|
74 | ||
75 |
#' Replicate Entries of a Vector if Required |
|
76 |
#' |
|
77 |
#' @description `r lifecycle::badge("stable")` |
|
78 |
#' |
|
79 |
#' Replicate entries of a vector if required. |
|
80 |
#' |
|
81 |
#' @inheritParams argument_convention |
|
82 |
#' @param n (`count`)\cr how many entries we need. |
|
83 |
#' |
|
84 |
#' @return `x` if it has the required length already or is `NULL`, |
|
85 |
#' otherwise if it is scalar the replicated version of it with `n` entries. |
|
86 |
#' |
|
87 |
#' @note This function will fail if `x` is not of length `n` and/or is not a scalar. |
|
88 |
#' |
|
89 |
#' @export |
|
90 |
to_n <- function(x, n) { |
|
91 | 1x |
if (is.null(x)) { |
92 | ! |
NULL |
93 | 1x |
} else if (length(x) == 1) { |
94 | ! |
rep(x, n) |
95 | 1x |
} else if (length(x) == n) { |
96 | 1x |
x |
97 |
} else { |
|
98 | ! |
stop("dimension mismatch") |
99 |
} |
|
100 |
} |
|
101 | ||
102 |
#' Check Element Dimension |
|
103 |
#' |
|
104 |
#' Checks if the elements in `...` have the same dimension. |
|
105 |
#' |
|
106 |
#' @param ... (`data.frame`s or `vector`s)\cr any data frames/vectors. |
|
107 |
#' @param omit_null (`logical`)\cr whether `NULL` elements in `...` should be omitted from the check. |
|
108 |
#' |
|
109 |
#' @return A `logical` value. |
|
110 |
#' |
|
111 |
#' @keywords internal |
|
112 |
check_same_n <- function(..., omit_null = TRUE) { |
|
113 | 2x |
dots <- list(...) |
114 | ||
115 | 2x |
n_list <- Map( |
116 | 2x |
function(x, name) { |
117 | 5x |
if (is.null(x)) { |
118 | ! |
if (omit_null) { |
119 | 2x |
NA_integer_ |
120 |
} else { |
|
121 | ! |
stop("arg", name, "is not supposed to be NULL") |
122 |
} |
|
123 | 5x |
} else if (is.data.frame(x)) { |
124 | ! |
nrow(x) |
125 | 5x |
} else if (is.atomic(x)) { |
126 | 5x |
length(x) |
127 |
} else { |
|
128 | ! |
stop("data structure for ", name, "is currently not supported") |
129 |
} |
|
130 |
}, |
|
131 | 2x |
dots, names(dots) |
132 |
) |
|
133 | ||
134 | 2x |
n <- stats::na.omit(unlist(n_list)) |
135 | ||
136 | 2x |
if (length(unique(n)) > 1) { |
137 | ! |
sel <- which(n != n[1]) |
138 | ! |
stop("dimension mismatch:", paste(names(n)[sel], collapse = ", "), " do not have N=", n[1]) |
139 |
} |
|
140 | ||
141 | 2x |
TRUE |
142 |
} |
|
143 | ||
144 |
#' Make Names Without Dots |
|
145 |
#' |
|
146 |
#' @param nams (`character`)\cr vector of original names. |
|
147 |
#' |
|
148 |
#' @return A `character` `vector` of proper names, which does not use dots in contrast to [make.names()]. |
|
149 |
#' |
|
150 |
#' @keywords internal |
|
151 |
make_names <- function(nams) { |
|
152 | 6x |
orig <- make.names(nams) |
153 | 6x |
gsub(".", "", x = orig, fixed = TRUE) |
154 |
} |
|
155 | ||
156 |
#' Conversion of Months to Days |
|
157 |
#' |
|
158 |
#' @description `r lifecycle::badge("stable")` |
|
159 |
#' |
|
160 |
#' Conversion of Months to Days. This is an approximative calculation because it |
|
161 |
#' considers each month as having an average of 30.4375 days. |
|
162 |
#' |
|
163 |
#' @param x (`numeric`)\cr time in months. |
|
164 |
#' |
|
165 |
#' @return A `numeric` vector with the time in days. |
|
166 |
#' |
|
167 |
#' @examples |
|
168 |
#' x <- c(13.25, 8.15, 1, 2.834) |
|
169 |
#' month2day(x) |
|
170 |
#' |
|
171 |
#' @export |
|
172 |
month2day <- function(x) { |
|
173 | 1x |
checkmate::assert_numeric(x) |
174 | 1x |
x * 30.4375 |
175 |
} |
|
176 | ||
177 |
#' Conversion of Days to Months |
|
178 |
#' |
|
179 |
#' @param x (`numeric`)\cr time in days. |
|
180 |
#' |
|
181 |
#' @return A `numeric` vector with the time in months. |
|
182 |
#' |
|
183 |
#' @examples |
|
184 |
#' x <- c(403, 248, 30, 86) |
|
185 |
#' day2month(x) |
|
186 |
#' |
|
187 |
#' @export |
|
188 |
day2month <- function(x) { |
|
189 | 19x |
checkmate::assert_numeric(x) |
190 | 19x |
x / 30.4375 |
191 |
} |
|
192 | ||
193 |
#' Return an empty numeric if all elements are `NA`. |
|
194 |
#' |
|
195 |
#' @param x (`numeric`)\cr vector. |
|
196 |
#' |
|
197 |
#' @return An empty `numeric` if all elements of `x` are `NA`, otherwise `x`. |
|
198 |
#' |
|
199 |
#' @examples |
|
200 |
#' x <- c(NA, NA, NA) |
|
201 |
#' # Internal function - empty_vector_if_na |
|
202 |
#' @keywords internal |
|
203 |
empty_vector_if_na <- function(x) { |
|
204 | 683x |
if (all(is.na(x))) { |
205 | 220x |
numeric() |
206 |
} else { |
|
207 | 463x |
x |
208 |
} |
|
209 |
} |
|
210 | ||
211 |
#' Combine Two Vectors Element Wise |
|
212 |
#' |
|
213 |
#' @param x (`vector`)\cr first vector to combine. |
|
214 |
#' @param y (`vector`)\cr second vector to combine. |
|
215 |
#' |
|
216 |
#' @return A `list` where each element combines corresponding elements of `x` and `y`. |
|
217 |
#' |
|
218 |
#' @examples |
|
219 |
#' combine_vectors(1:3, 4:6) |
|
220 |
#' |
|
221 |
#' @export |
|
222 |
combine_vectors <- function(x, y) { |
|
223 | 67x |
checkmate::assert_vector(x) |
224 | 67x |
checkmate::assert_vector(y, len = length(x)) |
225 | ||
226 | 67x |
result <- lapply(as.data.frame(rbind(x, y)), `c`) |
227 | 67x |
names(result) <- NULL |
228 | 67x |
result |
229 |
} |
|
230 | ||
231 |
#' Extract Elements by Name |
|
232 |
#' |
|
233 |
#' This utility function extracts elements from a vector `x` by `names`. |
|
234 |
#' Differences to the standard `[` function are: |
|
235 |
#' |
|
236 |
#' - If `x` is `NULL`, then still always `NULL` is returned (same as in base function). |
|
237 |
#' - If `x` is not `NULL`, then the intersection of its names is made with `names` and those |
|
238 |
#' elements are returned. That is, `names` which don't appear in `x` are not returned as `NA`s. |
|
239 |
#' |
|
240 |
#' @param x (named `vector`)\cr where to extract named elements from. |
|
241 |
#' @param names (`character`)\cr vector of names to extract. |
|
242 |
#' |
|
243 |
#' @return `NULL` if `x` is `NULL`, otherwise the extracted elements from `x`. |
|
244 |
#' |
|
245 |
#' @keywords internal |
|
246 |
extract_by_name <- function(x, names) { |
|
247 | 3x |
if (is.null(x)) { |
248 | 1x |
return(NULL) |
249 |
} |
|
250 | 2x |
checkmate::assert_named(x) |
251 | 2x |
checkmate::assert_character(names) |
252 | 2x |
which_extract <- intersect(names(x), names) |
253 | 2x |
if (length(which_extract) > 0) { |
254 | 1x |
x[which_extract] |
255 |
} else { |
|
256 | 1x |
NULL |
257 |
} |
|
258 |
} |
|
259 | ||
260 |
#' Labels for Adverse Event Baskets |
|
261 |
#' |
|
262 |
#' @description `r lifecycle::badge("stable")` |
|
263 |
#' |
|
264 |
#' @param aesi (`character`)\cr with standardized `MedDRA` query name (e.g. `SMQzzNAM`) or customized query |
|
265 |
#' name (e.g. `CQzzNAM`). |
|
266 |
#' @param scope (`character`)\cr with scope of query (e.g. `SMQzzSC`). |
|
267 |
#' |
|
268 |
#' @return A `string` with the standard label for the `AE` basket. |
|
269 |
#' |
|
270 |
#' @examples |
|
271 |
#' adae <- tern_ex_adae |
|
272 |
#' |
|
273 |
#' # Standardized query label includes scope. |
|
274 |
#' aesi_label(adae$SMQ01NAM, scope = adae$SMQ01SC) |
|
275 |
#' |
|
276 |
#' # Customized query label. |
|
277 |
#' aesi_label(adae$CQ01NAM) |
|
278 |
#' |
|
279 |
#' @export |
|
280 |
aesi_label <- function(aesi, scope = NULL) { |
|
281 | 3x |
checkmate::assert_character(aesi) |
282 | 3x |
checkmate::assert_character(scope, null.ok = TRUE) |
283 | 3x |
aesi_label <- obj_label(aesi) |
284 | 3x |
aesi <- sas_na(aesi) |
285 | 3x |
aesi <- unique(aesi)[!is.na(unique(aesi))] |
286 | ||
287 | 3x |
lbl <- if (length(aesi) == 1 && !is.null(scope)) { |
288 | 1x |
scope <- sas_na(scope) |
289 | 1x |
scope <- unique(scope)[!is.na(unique(scope))] |
290 | 1x |
checkmate::assert_string(scope) |
291 | 1x |
paste0(aesi, " (", scope, ")") |
292 | 3x |
} else if (length(aesi) == 1 && is.null(scope)) { |
293 | 1x |
aesi |
294 |
} else { |
|
295 | 1x |
aesi_label |
296 |
} |
|
297 | ||
298 | 3x |
lbl |
299 |
} |
|
300 | ||
301 |
#' Indicate Study Arm Variable in Formula |
|
302 |
#' |
|
303 |
#' We use `study_arm` to indicate the study arm variable in `tern` formulas. |
|
304 |
#' |
|
305 |
#' @param x arm information |
|
306 |
#' |
|
307 |
#' @return `x` |
|
308 |
#' |
|
309 |
#' @keywords internal |
|
310 |
study_arm <- function(x) { |
|
311 | ! |
structure(x, varname = deparse(substitute(x))) |
312 |
} |
|
313 | ||
314 |
#' Smooth Function with Optional Grouping |
|
315 |
#' |
|
316 |
#' @description `r lifecycle::badge("stable")` |
|
317 |
#' |
|
318 |
#' This produces `loess` smoothed estimates of `y` with Student confidence intervals. |
|
319 |
#' |
|
320 |
#' @param df (`data.frame`)\cr data set containing all analysis variables. |
|
321 |
#' @param x (`character`)\cr value with x column name. |
|
322 |
#' @param y (`character`)\cr value with y column name. |
|
323 |
#' @param groups (`character`)\cr vector with optional grouping variables names. |
|
324 |
#' @param level (`numeric`)\cr level of confidence interval to use (0.95 by default). |
|
325 |
#' |
|
326 |
#' @return A `data.frame` with original `x`, smoothed `y`, `ylow`, and `yhigh`, and |
|
327 |
#' optional `groups` variables formatted as `factor` type. |
|
328 |
#' |
|
329 |
#' @export |
|
330 |
get_smooths <- function(df, x, y, groups = NULL, level = 0.95) { |
|
331 | 5x |
checkmate::assert_data_frame(df) |
332 | 5x |
df_cols <- colnames(df) |
333 | 5x |
checkmate::assert_string(x) |
334 | 5x |
checkmate::assert_subset(x, df_cols) |
335 | 5x |
checkmate::assert_numeric(df[[x]]) |
336 | 5x |
checkmate::assert_string(y) |
337 | 5x |
checkmate::assert_subset(y, df_cols) |
338 | 5x |
checkmate::assert_numeric(df[[y]]) |
339 | ||
340 | 5x |
if (!is.null(groups)) { |
341 | 4x |
checkmate::assert_character(groups) |
342 | 4x |
checkmate::assert_subset(groups, df_cols) |
343 |
} |
|
344 | ||
345 | 5x |
smooths <- function(x, y) { |
346 | 18x |
stats::predict(stats::loess(y ~ x), se = TRUE) |
347 |
} |
|
348 | ||
349 | 5x |
if (!is.null(groups)) { |
350 | 4x |
cc <- stats::complete.cases(df[c(x, y, groups)]) |
351 | 4x |
df_c <- df[cc, c(x, y, groups)] |
352 | 4x |
df_c_ordered <- df_c[do.call("order", as.list(df_c[, groups, drop = FALSE])), , drop = FALSE] |
353 | 4x |
df_c_g <- data.frame(Map(as.factor, df_c_ordered[groups])) |
354 | ||
355 | 4x |
df_smooth_raw <- |
356 | 4x |
by(df_c_ordered, df_c_g, function(d) { |
357 | 17x |
plx <- smooths(d[[x]], d[[y]]) |
358 | 17x |
data.frame( |
359 | 17x |
x = d[[x]], |
360 | 17x |
y = plx$fit, |
361 | 17x |
ylow = plx$fit - stats::qt(level, plx$df) * plx$se, |
362 | 17x |
yhigh = plx$fit + stats::qt(level, plx$df) * plx$se |
363 |
) |
|
364 |
}) |
|
365 | ||
366 | 4x |
df_smooth <- do.call(rbind, df_smooth_raw) |
367 | 4x |
df_smooth[groups] <- df_c_g |
368 | ||
369 | 4x |
df_smooth |
370 |
} else { |
|
371 | 1x |
cc <- stats::complete.cases(df[c(x, y)]) |
372 | 1x |
df_c <- df[cc, ] |
373 | 1x |
plx <- smooths(df_c[[x]], df_c[[y]]) |
374 | ||
375 | 1x |
df_smooth <- data.frame( |
376 | 1x |
x = df_c[[x]], |
377 | 1x |
y = plx$fit, |
378 | 1x |
ylow = plx$fit - stats::qt(level, plx$df) * plx$se, |
379 | 1x |
yhigh = plx$fit + stats::qt(level, plx$df) * plx$se |
380 |
) |
|
381 | ||
382 | 1x |
df_smooth |
383 |
} |
|
384 |
} |
|
385 | ||
386 |
#' Number of Available (Non-Missing Entries) in a Vector |
|
387 |
#' |
|
388 |
#' Small utility function for better readability. |
|
389 |
#' |
|
390 |
#' @param x (`any`)\cr vector in which to count non-missing values. |
|
391 |
#' |
|
392 |
#' @return Number of non-missing values. |
|
393 |
#' |
|
394 |
#' @keywords internal |
|
395 |
n_available <- function(x) { |
|
396 | 258x |
sum(!is.na(x)) |
397 |
} |
|
398 | ||
399 |
#' Reapply Variable Labels |
|
400 |
#' |
|
401 |
#' This is a helper function that is used in tests. |
|
402 |
#' |
|
403 |
#' @param x (`vector`)\cr vector of elements that needs new labels. |
|
404 |
#' @param varlabels (`character`)\cr vector of labels for `x`. |
|
405 |
#' @param ... further parameters to be added to the list. |
|
406 |
#' |
|
407 |
#' @return `x` with variable labels reapplied. |
|
408 |
#' |
|
409 |
#' @export |
|
410 |
reapply_varlabels <- function(x, varlabels, ...) { |
|
411 | 10x |
named_labels <- c(as.list(varlabels), list(...)) |
412 | 10x |
formatters::var_labels(x)[names(named_labels)] <- as.character(named_labels) |
413 | 10x |
x |
414 |
} |
|
415 | ||
416 |
# Wrapper function of survival::clogit so that when model fitting failed, a more useful message would show |
|
417 |
clogit_with_tryCatch <- function(formula, data, ...) { # nolint |
|
418 | 30x |
tryCatch( |
419 | 30x |
survival::clogit(formula = formula, data = data, ...), |
420 | 30x |
error = function(e) stop("model not built successfully with survival::clogit") |
421 |
) |
|
422 |
} |
1 |
#' Tabulate Biomarker Effects on Binary Response by Subgroup |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Tabulate the estimated effects of multiple continuous biomarker variables |
|
6 |
#' on a binary response endpoint across population subgroups. |
|
7 |
#' |
|
8 |
#' @inheritParams argument_convention |
|
9 |
#' @param df (`data.frame`)\cr containing all analysis variables, as returned by |
|
10 |
#' [extract_rsp_biomarkers()]. |
|
11 |
#' @param vars (`character`)\cr the names of statistics to be reported among: |
|
12 |
#' * `n_tot`: Total number of patients per group. |
|
13 |
#' * `n_rsp`: Total number of responses per group. |
|
14 |
#' * `prop`: Total response proportion per group. |
|
15 |
#' * `or`: Odds ratio. |
|
16 |
#' * `ci`: Confidence interval of odds ratio. |
|
17 |
#' * `pval`: p-value of the effect. |
|
18 |
#' Note, the statistics `n_tot`, `or` and `ci` are required. |
|
19 |
#' |
|
20 |
#' @return An `rtables` table summarizing biomarker effects on binary response by subgroup. |
|
21 |
#' |
|
22 |
#' @details These functions create a layout starting from a data frame which contains |
|
23 |
#' the required statistics. The tables are then typically used as input for forest plots. |
|
24 |
#' |
|
25 |
#' @note In contrast to [tabulate_rsp_subgroups()] this tabulation function does |
|
26 |
#' not start from an input layout `lyt`. This is because internally the table is |
|
27 |
#' created by combining multiple subtables. |
|
28 |
#' |
|
29 |
#' @seealso [h_tab_rsp_one_biomarker()] which is used internally, [extract_rsp_biomarkers()]. |
|
30 |
#' |
|
31 |
#' @examples |
|
32 |
#' library(dplyr) |
|
33 |
#' library(forcats) |
|
34 |
#' |
|
35 |
#' adrs <- tern_ex_adrs |
|
36 |
#' adrs_labels <- formatters::var_labels(adrs) |
|
37 |
#' |
|
38 |
#' adrs_f <- adrs %>% |
|
39 |
#' filter(PARAMCD == "BESRSPI") %>% |
|
40 |
#' mutate(rsp = AVALC == "CR") |
|
41 |
#' formatters::var_labels(adrs_f) <- c(adrs_labels, "Response") |
|
42 |
#' |
|
43 |
#' df <- extract_rsp_biomarkers( |
|
44 |
#' variables = list( |
|
45 |
#' rsp = "rsp", |
|
46 |
#' biomarkers = c("BMRKR1", "AGE"), |
|
47 |
#' covariates = "SEX", |
|
48 |
#' subgroups = "BMRKR2" |
|
49 |
#' ), |
|
50 |
#' data = adrs_f |
|
51 |
#' ) |
|
52 |
#' |
|
53 |
#' \donttest{ |
|
54 |
#' ## Table with default columns. |
|
55 |
#' tabulate_rsp_biomarkers(df) |
|
56 |
#' |
|
57 |
#' ## Table with a manually chosen set of columns: leave out "pval", reorder. |
|
58 |
#' tab <- tabulate_rsp_biomarkers( |
|
59 |
#' df = df, |
|
60 |
#' vars = c("n_rsp", "ci", "n_tot", "prop", "or") |
|
61 |
#' ) |
|
62 |
#' |
|
63 |
#' ## Finally produce the forest plot. |
|
64 |
#' g_forest(tab, xlim = c(0.7, 1.4)) |
|
65 |
#' } |
|
66 |
#' |
|
67 |
#' @export |
|
68 |
#' @name response_biomarkers_subgroups |
|
69 |
tabulate_rsp_biomarkers <- function(df, |
|
70 |
vars = c("n_tot", "n_rsp", "prop", "or", "ci", "pval"), |
|
71 |
na_str = default_na_str(), |
|
72 |
.indent_mods = 0L) { |
|
73 | 4x |
checkmate::assert_data_frame(df) |
74 | 4x |
checkmate::assert_character(df$biomarker) |
75 | 4x |
checkmate::assert_character(df$biomarker_label) |
76 | 4x |
checkmate::assert_subset(vars, get_stats("tabulate_rsp_biomarkers")) |
77 | ||
78 | 4x |
df_subs <- split(df, f = df$biomarker) |
79 | 4x |
tabs <- lapply(df_subs, FUN = function(df_sub) { |
80 | 7x |
tab_sub <- h_tab_rsp_one_biomarker( |
81 | 7x |
df = df_sub, |
82 | 7x |
vars = vars, |
83 | 7x |
na_str = na_str, |
84 | 7x |
.indent_mods = .indent_mods |
85 |
) |
|
86 |
# Insert label row as first row in table. |
|
87 | 7x |
label_at_path(tab_sub, path = row_paths(tab_sub)[[1]][1]) <- df_sub$biomarker_label[1] |
88 | 7x |
tab_sub |
89 |
}) |
|
90 | 4x |
result <- do.call(rbind, tabs) |
91 | ||
92 | 4x |
n_id <- grep("n_tot", vars) |
93 | 4x |
or_id <- match("or", vars) |
94 | 4x |
ci_id <- match("ci", vars) |
95 | 4x |
structure( |
96 | 4x |
result, |
97 | 4x |
forest_header = paste0(c("Lower", "Higher"), "\nBetter"), |
98 | 4x |
col_x = or_id, |
99 | 4x |
col_ci = ci_id, |
100 | 4x |
col_symbol_size = n_id |
101 |
) |
|
102 |
} |
|
103 | ||
104 |
#' Prepares Response Data Estimates for Multiple Biomarkers in a Single Data Frame |
|
105 |
#' |
|
106 |
#' @description `r lifecycle::badge("stable")` |
|
107 |
#' |
|
108 |
#' Prepares estimates for number of responses, patients and overall response rate, |
|
109 |
#' as well as odds ratio estimates, confidence intervals and p-values, |
|
110 |
#' for multiple biomarkers across population subgroups in a single data frame. |
|
111 |
#' `variables` corresponds to the names of variables found in `data`, passed as a |
|
112 |
#' named list and requires elements `rsp` and `biomarkers` (vector of continuous |
|
113 |
#' biomarker variables) and optionally `covariates`, `subgroups` and `strat`. |
|
114 |
#' `groups_lists` optionally specifies groupings for `subgroups` variables. |
|
115 |
#' |
|
116 |
#' @inheritParams argument_convention |
|
117 |
#' @inheritParams response_subgroups |
|
118 |
#' @param control (named `list`)\cr controls for the response definition and the |
|
119 |
#' confidence level produced by [control_logistic()]. |
|
120 |
#' |
|
121 |
#' @return A `data.frame` with columns `biomarker`, `biomarker_label`, `n_tot`, `n_rsp`, |
|
122 |
#' `prop`, `or`, `lcl`, `ucl`, `conf_level`, `pval`, `pval_label`, `subgroup`, `var`, |
|
123 |
#' `var_label`, and `row_type`. |
|
124 |
#' |
|
125 |
#' @note You can also specify a continuous variable in `rsp` and then use the |
|
126 |
#' `response_definition` control to convert that internally to a logical |
|
127 |
#' variable reflecting binary response. |
|
128 |
#' |
|
129 |
#' @seealso [h_logistic_mult_cont_df()] which is used internally. |
|
130 |
#' |
|
131 |
#' @examples |
|
132 |
#' library(dplyr) |
|
133 |
#' library(forcats) |
|
134 |
#' |
|
135 |
#' adrs <- tern_ex_adrs |
|
136 |
#' adrs_labels <- formatters::var_labels(adrs) |
|
137 |
#' |
|
138 |
#' adrs_f <- adrs %>% |
|
139 |
#' filter(PARAMCD == "BESRSPI") %>% |
|
140 |
#' mutate(rsp = AVALC == "CR") |
|
141 |
#' |
|
142 |
#' # Typical analysis of two continuous biomarkers `BMRKR1` and `AGE`, |
|
143 |
#' # in logistic regression models with one covariate `RACE`. The subgroups |
|
144 |
#' # are defined by the levels of `BMRKR2`. |
|
145 |
#' df <- extract_rsp_biomarkers( |
|
146 |
#' variables = list( |
|
147 |
#' rsp = "rsp", |
|
148 |
#' biomarkers = c("BMRKR1", "AGE"), |
|
149 |
#' covariates = "SEX", |
|
150 |
#' subgroups = "BMRKR2" |
|
151 |
#' ), |
|
152 |
#' data = adrs_f |
|
153 |
#' ) |
|
154 |
#' df |
|
155 |
#' |
|
156 |
#' # Here we group the levels of `BMRKR2` manually, and we add a stratification |
|
157 |
#' # variable `STRATA1`. We also here use a continuous variable `EOSDY` |
|
158 |
#' # which is then binarized internally (response is defined as this variable |
|
159 |
#' # being larger than 500). |
|
160 |
#' df_grouped <- extract_rsp_biomarkers( |
|
161 |
#' variables = list( |
|
162 |
#' rsp = "EOSDY", |
|
163 |
#' biomarkers = c("BMRKR1", "AGE"), |
|
164 |
#' covariates = "SEX", |
|
165 |
#' subgroups = "BMRKR2", |
|
166 |
#' strat = "STRATA1" |
|
167 |
#' ), |
|
168 |
#' data = adrs_f, |
|
169 |
#' groups_lists = list( |
|
170 |
#' BMRKR2 = list( |
|
171 |
#' "low" = "LOW", |
|
172 |
#' "low/medium" = c("LOW", "MEDIUM"), |
|
173 |
#' "low/medium/high" = c("LOW", "MEDIUM", "HIGH") |
|
174 |
#' ) |
|
175 |
#' ), |
|
176 |
#' control = control_logistic( |
|
177 |
#' response_definition = "I(response > 500)" |
|
178 |
#' ) |
|
179 |
#' ) |
|
180 |
#' df_grouped |
|
181 |
#' |
|
182 |
#' @export |
|
183 |
extract_rsp_biomarkers <- function(variables, |
|
184 |
data, |
|
185 |
groups_lists = list(), |
|
186 |
control = control_logistic(), |
|
187 |
label_all = "All Patients") { |
|
188 | 5x |
assert_list_of_variables(variables) |
189 | 5x |
checkmate::assert_string(variables$rsp) |
190 | 5x |
checkmate::assert_character(variables$subgroups, null.ok = TRUE) |
191 | 5x |
checkmate::assert_string(label_all) |
192 | ||
193 |
# Start with all patients. |
|
194 | 5x |
result_all <- h_logistic_mult_cont_df( |
195 | 5x |
variables = variables, |
196 | 5x |
data = data, |
197 | 5x |
control = control |
198 |
) |
|
199 | 5x |
result_all$subgroup <- label_all |
200 | 5x |
result_all$var <- "ALL" |
201 | 5x |
result_all$var_label <- label_all |
202 | 5x |
result_all$row_type <- "content" |
203 | 5x |
if (is.null(variables$subgroups)) { |
204 |
# Only return result for all patients. |
|
205 | 1x |
result_all |
206 |
} else { |
|
207 |
# Add subgroups results. |
|
208 | 4x |
l_data <- h_split_by_subgroups( |
209 | 4x |
data, |
210 | 4x |
variables$subgroups, |
211 | 4x |
groups_lists = groups_lists |
212 |
) |
|
213 | 4x |
l_result <- lapply(l_data, function(grp) { |
214 | 20x |
result <- h_logistic_mult_cont_df( |
215 | 20x |
variables = variables, |
216 | 20x |
data = grp$df, |
217 | 20x |
control = control |
218 |
) |
|
219 | 20x |
result_labels <- grp$df_labels[rep(1, times = nrow(result)), ] |
220 | 20x |
cbind(result, result_labels) |
221 |
}) |
|
222 | 4x |
result_subgroups <- do.call(rbind, args = c(l_result, make.row.names = FALSE)) |
223 | 4x |
result_subgroups$row_type <- "analysis" |
224 | 4x |
rbind( |
225 | 4x |
result_all, |
226 | 4x |
result_subgroups |
227 |
) |
|
228 |
} |
|
229 |
} |
1 |
#' Helper Functions for Multivariate Logistic Regression |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Helper functions used in calculations for logistic regression. |
|
6 |
#' |
|
7 |
#' @inheritParams argument_convention |
|
8 |
#' @param fit_glm (`glm`)\cr logistic regression model fitted by [stats::glm()] with "binomial" family. |
|
9 |
#' Limited functionality is also available for conditional logistic regression models fitted by |
|
10 |
#' [survival::clogit()], currently this is used only by [extract_rsp_biomarkers()]. |
|
11 |
#' @param x (`string` or `character`)\cr a variable or interaction term in `fit_glm` (depending on the |
|
12 |
#' helper function). |
|
13 |
#' |
|
14 |
#' @examples |
|
15 |
#' library(dplyr) |
|
16 |
#' library(broom) |
|
17 |
#' |
|
18 |
#' adrs_f <- tern_ex_adrs %>% |
|
19 |
#' filter(PARAMCD == "BESRSPI") %>% |
|
20 |
#' filter(RACE %in% c("ASIAN", "WHITE", "BLACK OR AFRICAN AMERICAN")) %>% |
|
21 |
#' mutate( |
|
22 |
#' Response = case_when(AVALC %in% c("PR", "CR") ~ 1, TRUE ~ 0), |
|
23 |
#' RACE = factor(RACE), |
|
24 |
#' SEX = factor(SEX) |
|
25 |
#' ) |
|
26 |
#' formatters::var_labels(adrs_f) <- c(formatters::var_labels(tern_ex_adrs), Response = "Response") |
|
27 |
#' mod1 <- fit_logistic( |
|
28 |
#' data = adrs_f, |
|
29 |
#' variables = list( |
|
30 |
#' response = "Response", |
|
31 |
#' arm = "ARMCD", |
|
32 |
#' covariates = c("AGE", "RACE") |
|
33 |
#' ) |
|
34 |
#' ) |
|
35 |
#' mod2 <- fit_logistic( |
|
36 |
#' data = adrs_f, |
|
37 |
#' variables = list( |
|
38 |
#' response = "Response", |
|
39 |
#' arm = "ARMCD", |
|
40 |
#' covariates = c("AGE", "RACE"), |
|
41 |
#' interaction = "AGE" |
|
42 |
#' ) |
|
43 |
#' ) |
|
44 |
#' |
|
45 |
#' @name h_logistic_regression |
|
46 |
NULL |
|
47 | ||
48 |
#' @describeIn h_logistic_regression Helper function to extract interaction variable names from a fitted |
|
49 |
#' model assuming only one interaction term. |
|
50 |
#' |
|
51 |
#' @return Vector of names of interaction variables. |
|
52 |
#' |
|
53 |
#' @export |
|
54 |
h_get_interaction_vars <- function(fit_glm) { |
|
55 | 27x |
checkmate::assert_class(fit_glm, "glm") |
56 | 27x |
terms_name <- attr(stats::terms(fit_glm), "term.labels") |
57 | 27x |
terms_order <- attr(stats::terms(fit_glm), "order") |
58 | 27x |
interaction_term <- terms_name[terms_order == 2] |
59 | 27x |
checkmate::assert_string(interaction_term) |
60 | 27x |
strsplit(interaction_term, split = ":")[[1]] |
61 |
} |
|
62 | ||
63 |
#' @describeIn h_logistic_regression Helper function to get the right coefficient name from the |
|
64 |
#' interaction variable names and the given levels. The main value here is that the order |
|
65 |
#' of first and second variable is checked in the `interaction_vars` input. |
|
66 |
#' |
|
67 |
#' @param interaction_vars (`character` of length 2)\cr interaction variable names. |
|
68 |
#' @param first_var_with_level (`character` of length 2)\cr the first variable name with |
|
69 |
#' the interaction level. |
|
70 |
#' @param second_var_with_level (`character` of length 2)\cr the second variable name with |
|
71 |
#' the interaction level. |
|
72 |
#' |
|
73 |
#' @return Name of coefficient. |
|
74 |
#' |
|
75 |
#' @export |
|
76 |
h_interaction_coef_name <- function(interaction_vars, |
|
77 |
first_var_with_level, |
|
78 |
second_var_with_level) { |
|
79 | 45x |
checkmate::assert_character(interaction_vars, len = 2, any.missing = FALSE) |
80 | 45x |
checkmate::assert_character(first_var_with_level, len = 2, any.missing = FALSE) |
81 | 45x |
checkmate::assert_character(second_var_with_level, len = 2, any.missing = FALSE) |
82 | 45x |
checkmate::assert_subset(c(first_var_with_level[1], second_var_with_level[1]), interaction_vars) |
83 | ||
84 | 45x |
first_name <- paste(first_var_with_level, collapse = "") |
85 | 45x |
second_name <- paste(second_var_with_level, collapse = "") |
86 | 45x |
if (first_var_with_level[1] == interaction_vars[1]) { |
87 | 34x |
paste(first_name, second_name, sep = ":") |
88 | 11x |
} else if (second_var_with_level[1] == interaction_vars[1]) { |
89 | 11x |
paste(second_name, first_name, sep = ":") |
90 |
} |
|
91 |
} |
|
92 | ||
93 |
#' @describeIn h_logistic_regression Helper function to calculate the odds ratio estimates |
|
94 |
#' for the case when both the odds ratio and the interaction variable are categorical. |
|
95 |
#' |
|
96 |
#' @param odds_ratio_var (`string`)\cr the odds ratio variable. |
|
97 |
#' @param interaction_var (`string`)\cr the interaction variable. |
|
98 |
#' |
|
99 |
#' @return Odds ratio. |
|
100 |
#' |
|
101 |
#' @export |
|
102 |
h_or_cat_interaction <- function(odds_ratio_var, |
|
103 |
interaction_var, |
|
104 |
fit_glm, |
|
105 |
conf_level = 0.95) { |
|
106 | 7x |
interaction_vars <- h_get_interaction_vars(fit_glm) |
107 | 7x |
checkmate::assert_string(odds_ratio_var) |
108 | 7x |
checkmate::assert_string(interaction_var) |
109 | 7x |
checkmate::assert_subset(c(odds_ratio_var, interaction_var), interaction_vars) |
110 | 7x |
checkmate::assert_vector(interaction_vars, len = 2) |
111 | ||
112 | 7x |
xs_level <- fit_glm$xlevels |
113 | 7x |
xs_coef <- stats::coef(fit_glm) |
114 | 7x |
xs_vcov <- stats::vcov(fit_glm) |
115 | 7x |
y <- list() |
116 | 7x |
for (var_level in xs_level[[odds_ratio_var]][-1]) { |
117 | 12x |
x <- list() |
118 | 12x |
for (ref_level in xs_level[[interaction_var]]) { |
119 | 32x |
coef_names <- paste0(odds_ratio_var, var_level) |
120 | 32x |
if (ref_level != xs_level[[interaction_var]][1]) { |
121 | 20x |
interaction_coef_name <- h_interaction_coef_name( |
122 | 20x |
interaction_vars, |
123 | 20x |
c(odds_ratio_var, var_level), |
124 | 20x |
c(interaction_var, ref_level) |
125 |
) |
|
126 | 20x |
coef_names <- c( |
127 | 20x |
coef_names, |
128 | 20x |
interaction_coef_name |
129 |
) |
|
130 |
} |
|
131 | 32x |
if (length(coef_names) > 1) { |
132 | 20x |
ones <- t(c(1, 1)) |
133 | 20x |
est <- as.numeric(ones %*% xs_coef[coef_names]) |
134 | 20x |
se <- sqrt(as.numeric(ones %*% xs_vcov[coef_names, coef_names] %*% t(ones))) |
135 |
} else { |
|
136 | 12x |
est <- xs_coef[coef_names] |
137 | 12x |
se <- sqrt(as.numeric(xs_vcov[coef_names, coef_names])) |
138 |
} |
|
139 | 32x |
or <- exp(est) |
140 | 32x |
ci <- exp(est + c(lcl = -1, ucl = 1) * stats::qnorm((1 + conf_level) / 2) * se) |
141 | 32x |
x[[ref_level]] <- list(or = or, ci = ci) |
142 |
} |
|
143 | 12x |
y[[var_level]] <- x |
144 |
} |
|
145 | 7x |
y |
146 |
} |
|
147 | ||
148 |
#' @describeIn h_logistic_regression Helper function to calculate the odds ratio estimates |
|
149 |
#' for the case when either the odds ratio or the interaction variable is continuous. |
|
150 |
#' |
|
151 |
#' @param at (`NULL` or `numeric`)\cr optional values for the interaction variable. Otherwise |
|
152 |
#' the median is used. |
|
153 |
#' |
|
154 |
#' @return Odds ratio. |
|
155 |
#' |
|
156 |
#' @note We don't provide a function for the case when both variables are continuous because |
|
157 |
#' this does not arise in this table, as the treatment arm variable will always be involved |
|
158 |
#' and categorical. |
|
159 |
#' |
|
160 |
#' @export |
|
161 |
h_or_cont_interaction <- function(odds_ratio_var, |
|
162 |
interaction_var, |
|
163 |
fit_glm, |
|
164 |
at = NULL, |
|
165 |
conf_level = 0.95) { |
|
166 | 9x |
interaction_vars <- h_get_interaction_vars(fit_glm) |
167 | 9x |
checkmate::assert_string(odds_ratio_var) |
168 | 9x |
checkmate::assert_string(interaction_var) |
169 | 9x |
checkmate::assert_subset(c(odds_ratio_var, interaction_var), interaction_vars) |
170 | 9x |
checkmate::assert_vector(interaction_vars, len = 2) |
171 | 9x |
checkmate::assert_numeric(at, min.len = 1, null.ok = TRUE, any.missing = FALSE) |
172 | 9x |
xs_level <- fit_glm$xlevels |
173 | 9x |
xs_coef <- stats::coef(fit_glm) |
174 | 9x |
xs_vcov <- stats::vcov(fit_glm) |
175 | 9x |
xs_class <- attr(fit_glm$terms, "dataClasses") |
176 | 9x |
model_data <- fit_glm$model |
177 | 9x |
if (!is.null(at)) { |
178 | 2x |
checkmate::assert_set_equal(xs_class[interaction_var], "numeric") |
179 |
} |
|
180 | 9x |
y <- list() |
181 | 9x |
if (xs_class[interaction_var] == "numeric") { |
182 | 6x |
if (is.null(at)) { |
183 | 4x |
at <- ceiling(stats::median(model_data[[interaction_var]])) |
184 |
} |
|
185 | ||
186 | 6x |
for (var_level in xs_level[[odds_ratio_var]][-1]) { |
187 | 12x |
x <- list() |
188 | 12x |
for (increment in at) { |
189 | 18x |
coef_names <- paste0(odds_ratio_var, var_level) |
190 | 18x |
if (increment != 0) { |
191 | 18x |
interaction_coef_name <- h_interaction_coef_name( |
192 | 18x |
interaction_vars, |
193 | 18x |
c(odds_ratio_var, var_level), |
194 | 18x |
c(interaction_var, "") |
195 |
) |
|
196 | 18x |
coef_names <- c( |
197 | 18x |
coef_names, |
198 | 18x |
interaction_coef_name |
199 |
) |
|
200 |
} |
|
201 | 18x |
if (length(coef_names) > 1) { |
202 | 18x |
xvec <- t(c(1, increment)) |
203 | 18x |
est <- as.numeric(xvec %*% xs_coef[coef_names]) |
204 | 18x |
se <- sqrt(as.numeric(xvec %*% xs_vcov[coef_names, coef_names] %*% t(xvec))) |
205 |
} else { |
|
206 | ! |
est <- xs_coef[coef_names] |
207 | ! |
se <- sqrt(as.numeric(xs_vcov[coef_names, coef_names])) |
208 |
} |
|
209 | 18x |
or <- exp(est) |
210 | 18x |
ci <- exp(est + c(lcl = -1, ucl = 1) * stats::qnorm((1 + conf_level) / 2) * se) |
211 | 18x |
x[[as.character(increment)]] <- list(or = or, ci = ci) |
212 |
} |
|
213 | 12x |
y[[var_level]] <- x |
214 |
} |
|
215 |
} else { |
|
216 | 3x |
checkmate::assert_set_equal(xs_class[odds_ratio_var], "numeric") |
217 | 3x |
checkmate::assert_set_equal(xs_class[interaction_var], "factor") |
218 | 3x |
for (var_level in xs_level[[interaction_var]]) { |
219 | 9x |
coef_names <- odds_ratio_var |
220 | 9x |
if (var_level != xs_level[[interaction_var]][1]) { |
221 | 6x |
interaction_coef_name <- h_interaction_coef_name( |
222 | 6x |
interaction_vars, |
223 | 6x |
c(odds_ratio_var, ""), |
224 | 6x |
c(interaction_var, var_level) |
225 |
) |
|
226 | 6x |
coef_names <- c( |
227 | 6x |
coef_names, |
228 | 6x |
interaction_coef_name |
229 |
) |
|
230 |
} |
|
231 | 9x |
if (length(coef_names) > 1) { |
232 | 6x |
xvec <- t(c(1, 1)) |
233 | 6x |
est <- as.numeric(xvec %*% xs_coef[coef_names]) |
234 | 6x |
se <- sqrt(as.numeric(xvec %*% xs_vcov[coef_names, coef_names] %*% t(xvec))) |
235 |
} else { |
|
236 | 3x |
est <- xs_coef[coef_names] |
237 | 3x |
se <- sqrt(as.numeric(xs_vcov[coef_names, coef_names])) |
238 |
} |
|
239 | 9x |
or <- exp(est) |
240 | 9x |
ci <- exp(est + c(lcl = -1, ucl = 1) * stats::qnorm((1 + conf_level) / 2) * se) |
241 | 9x |
y[[var_level]] <- list(or = or, ci = ci) |
242 |
} |
|
243 |
} |
|
244 | 9x |
y |
245 |
} |
|
246 | ||
247 |
#' @describeIn h_logistic_regression Helper function to calculate the odds ratio estimates |
|
248 |
#' in case of an interaction. This is a wrapper for [h_or_cont_interaction()] and |
|
249 |
#' [h_or_cat_interaction()]. |
|
250 |
#' |
|
251 |
#' @return Odds ratio. |
|
252 |
#' |
|
253 |
#' @export |
|
254 |
h_or_interaction <- function(odds_ratio_var, |
|
255 |
interaction_var, |
|
256 |
fit_glm, |
|
257 |
at = NULL, |
|
258 |
conf_level = 0.95) { |
|
259 | 13x |
xs_class <- attr(fit_glm$terms, "dataClasses") |
260 | 13x |
if (any(xs_class[c(odds_ratio_var, interaction_var)] == "numeric")) { |
261 | 7x |
h_or_cont_interaction( |
262 | 7x |
odds_ratio_var, |
263 | 7x |
interaction_var, |
264 | 7x |
fit_glm, |
265 | 7x |
at = at, |
266 | 7x |
conf_level = conf_level |
267 |
) |
|
268 | 6x |
} else if (all(xs_class[c(odds_ratio_var, interaction_var)] == "factor")) { |
269 | 6x |
h_or_cat_interaction( |
270 | 6x |
odds_ratio_var, |
271 | 6x |
interaction_var, |
272 | 6x |
fit_glm, |
273 | 6x |
conf_level = conf_level |
274 |
) |
|
275 |
} else { |
|
276 | ! |
stop("wrong interaction variable class, the interaction variable is not a numeric nor a factor") |
277 |
} |
|
278 |
} |
|
279 | ||
280 |
#' @describeIn h_logistic_regression Helper function to construct term labels from simple terms and the table |
|
281 |
#' of numbers of patients. |
|
282 |
#' |
|
283 |
#' @param terms (`character`)\cr simple terms. |
|
284 |
#' @param table (`table`)\cr table containing numbers for terms. |
|
285 |
#' |
|
286 |
#' @return Term labels containing numbers of patients. |
|
287 |
#' |
|
288 |
#' @export |
|
289 |
h_simple_term_labels <- function(terms, |
|
290 |
table) { |
|
291 | 45x |
checkmate::assert_true(is.table(table)) |
292 | 45x |
checkmate::assert_multi_class(terms, classes = c("factor", "character")) |
293 | 45x |
terms <- as.character(terms) |
294 | 45x |
term_n <- table[terms] |
295 | 45x |
paste0(terms, ", n = ", term_n) |
296 |
} |
|
297 | ||
298 |
#' @describeIn h_logistic_regression Helper function to construct term labels from interaction terms and the table |
|
299 |
#' of numbers of patients. |
|
300 |
#' |
|
301 |
#' @param terms1 (`character`)\cr terms for first dimension (rows). |
|
302 |
#' @param terms2 (`character`)\cr terms for second dimension (rows). |
|
303 |
#' @param any (`flag`)\cr whether any of `term1` and `term2` can be fulfilled to count the |
|
304 |
#' number of patients. In that case they can only be scalar (strings). |
|
305 |
#' |
|
306 |
#' @return Term labels containing numbers of patients. |
|
307 |
#' |
|
308 |
#' @export |
|
309 |
h_interaction_term_labels <- function(terms1, |
|
310 |
terms2, |
|
311 |
table, |
|
312 |
any = FALSE) { |
|
313 | 8x |
checkmate::assert_true(is.table(table)) |
314 | 8x |
checkmate::assert_flag(any) |
315 | 8x |
checkmate::assert_multi_class(terms1, classes = c("factor", "character")) |
316 | 8x |
checkmate::assert_multi_class(terms2, classes = c("factor", "character")) |
317 | 8x |
terms1 <- as.character(terms1) |
318 | 8x |
terms2 <- as.character(terms2) |
319 | 8x |
if (any) { |
320 | 4x |
checkmate::assert_scalar(terms1) |
321 | 4x |
checkmate::assert_scalar(terms2) |
322 | 4x |
paste0( |
323 | 4x |
terms1, " or ", terms2, ", n = ", |
324 |
# Note that we double count in the initial sum the cell [terms1, terms2], therefore subtract. |
|
325 | 4x |
sum(c(table[terms1, ], table[, terms2])) - table[terms1, terms2] |
326 |
) |
|
327 |
} else { |
|
328 | 4x |
term_n <- table[cbind(terms1, terms2)] |
329 | 4x |
paste0(terms1, " * ", terms2, ", n = ", term_n) |
330 |
} |
|
331 |
} |
|
332 | ||
333 |
#' @describeIn h_logistic_regression Helper function to tabulate the main effect |
|
334 |
#' results of a (conditional) logistic regression model. |
|
335 |
#' |
|
336 |
#' @return Tabulated main effect results from a logistic regression model. |
|
337 |
#' |
|
338 |
#' @examples |
|
339 |
#' h_glm_simple_term_extract("AGE", mod1) |
|
340 |
#' h_glm_simple_term_extract("ARMCD", mod1) |
|
341 |
#' |
|
342 |
#' @export |
|
343 |
h_glm_simple_term_extract <- function(x, fit_glm) { |
|
344 | 73x |
checkmate::assert_multi_class(fit_glm, c("glm", "clogit")) |
345 | 73x |
checkmate::assert_string(x) |
346 | ||
347 | 73x |
xs_class <- attr(fit_glm$terms, "dataClasses") |
348 | 73x |
xs_level <- fit_glm$xlevels |
349 | 73x |
xs_coef <- summary(fit_glm)$coefficients |
350 | 73x |
stats <- if (inherits(fit_glm, "glm")) { |
351 | 61x |
c("estimate" = "Estimate", "std_error" = "Std. Error", "pvalue" = "Pr(>|z|)") |
352 |
} else { |
|
353 | 12x |
c("estimate" = "coef", "std_error" = "se(coef)", "pvalue" = "Pr(>|z|)") |
354 |
} |
|
355 |
# Make sure x is not an interaction term. |
|
356 | 73x |
checkmate::assert_subset(x, names(xs_class)) |
357 | 73x |
x_sel <- if (xs_class[x] == "numeric") x else paste0(x, xs_level[[x]][-1]) |
358 | 73x |
x_stats <- as.data.frame(xs_coef[x_sel, stats, drop = FALSE], stringsAsFactors = FALSE) |
359 | 73x |
colnames(x_stats) <- names(stats) |
360 | 73x |
x_stats$estimate <- as.list(x_stats$estimate) |
361 | 73x |
x_stats$std_error <- as.list(x_stats$std_error) |
362 | 73x |
x_stats$pvalue <- as.list(x_stats$pvalue) |
363 | 73x |
x_stats$df <- as.list(1) |
364 | 73x |
if (xs_class[x] == "numeric") { |
365 | 58x |
x_stats$term <- x |
366 | 58x |
x_stats$term_label <- if (inherits(fit_glm, "glm")) { |
367 | 46x |
formatters::var_labels(fit_glm$data[x], fill = TRUE) |
368 |
} else { |
|
369 |
# We just fill in here with the `term` itself as we don't have the data available. |
|
370 | 12x |
x |
371 |
} |
|
372 | 58x |
x_stats$is_variable_summary <- FALSE |
373 | 58x |
x_stats$is_term_summary <- TRUE |
374 |
} else { |
|
375 | 15x |
checkmate::assert_class(fit_glm, "glm") |
376 |
# The reason is that we don't have the original data set in the `clogit` object |
|
377 |
# and therefore cannot determine the `x_numbers` here. |
|
378 | 15x |
x_numbers <- table(fit_glm$data[[x]]) |
379 | 15x |
x_stats$term <- xs_level[[x]][-1] |
380 | 15x |
x_stats$term_label <- h_simple_term_labels(x_stats$term, x_numbers) |
381 | 15x |
x_stats$is_variable_summary <- FALSE |
382 | 15x |
x_stats$is_term_summary <- TRUE |
383 | 15x |
main_effects <- car::Anova(fit_glm, type = 3, test.statistic = "Wald") |
384 | 15x |
x_main <- data.frame( |
385 | 15x |
pvalue = main_effects[x, "Pr(>Chisq)", drop = TRUE], |
386 | 15x |
term = xs_level[[x]][1], |
387 | 15x |
term_label = paste("Reference", h_simple_term_labels(xs_level[[x]][1], x_numbers)), |
388 | 15x |
df = main_effects[x, "Df", drop = TRUE], |
389 | 15x |
stringsAsFactors = FALSE |
390 |
) |
|
391 | 15x |
x_main$pvalue <- as.list(x_main$pvalue) |
392 | 15x |
x_main$df <- as.list(x_main$df) |
393 | 15x |
x_main$estimate <- list(numeric(0)) |
394 | 15x |
x_main$std_error <- list(numeric(0)) |
395 | 15x |
if (length(xs_level[[x]][-1]) == 1) { |
396 | 6x |
x_main$pvalue <- list(numeric(0)) |
397 | 6x |
x_main$df <- list(numeric(0)) |
398 |
} |
|
399 | 15x |
x_main$is_variable_summary <- TRUE |
400 | 15x |
x_main$is_term_summary <- FALSE |
401 | 15x |
x_stats <- rbind(x_main, x_stats) |
402 |
} |
|
403 | 73x |
x_stats$variable <- x |
404 | 73x |
x_stats$variable_label <- if (inherits(fit_glm, "glm")) { |
405 | 61x |
formatters::var_labels(fit_glm$data[x], fill = TRUE) |
406 |
} else { |
|
407 | 12x |
x |
408 |
} |
|
409 | 73x |
x_stats$interaction <- "" |
410 | 73x |
x_stats$interaction_label <- "" |
411 | 73x |
x_stats$reference <- "" |
412 | 73x |
x_stats$reference_label <- "" |
413 | 73x |
rownames(x_stats) <- NULL |
414 | 73x |
x_stats[c( |
415 | 73x |
"variable", |
416 | 73x |
"variable_label", |
417 | 73x |
"term", |
418 | 73x |
"term_label", |
419 | 73x |
"interaction", |
420 | 73x |
"interaction_label", |
421 | 73x |
"reference", |
422 | 73x |
"reference_label", |
423 | 73x |
"estimate", |
424 | 73x |
"std_error", |
425 | 73x |
"df", |
426 | 73x |
"pvalue", |
427 | 73x |
"is_variable_summary", |
428 | 73x |
"is_term_summary" |
429 |
)] |
|
430 |
} |
|
431 | ||
432 |
#' @describeIn h_logistic_regression Helper function to tabulate the interaction term |
|
433 |
#' results of a logistic regression model. |
|
434 |
#' |
|
435 |
#' @return Tabulated interaction term results from a logistic regression model. |
|
436 |
#' |
|
437 |
#' @examples |
|
438 |
#' h_glm_interaction_extract("ARMCD:AGE", mod2) |
|
439 |
#' |
|
440 |
#' @export |
|
441 |
h_glm_interaction_extract <- function(x, fit_glm) { |
|
442 | 6x |
vars <- h_get_interaction_vars(fit_glm) |
443 | 6x |
xs_class <- attr(fit_glm$terms, "dataClasses") |
444 | ||
445 | 6x |
checkmate::assert_string(x) |
446 | ||
447 |
# Only take two-way interaction |
|
448 | 6x |
checkmate::assert_vector(vars, len = 2) |
449 | ||
450 |
# Only consider simple case: first variable in interaction is arm, a categorical variable |
|
451 | 6x |
checkmate::assert_disjunct(xs_class[vars[1]], "numeric") |
452 | ||
453 | 6x |
xs_level <- fit_glm$xlevels |
454 | 6x |
xs_coef <- summary(fit_glm)$coefficients |
455 | 6x |
main_effects <- car::Anova(fit_glm, type = 3, test.statistic = "Wald") |
456 | 6x |
stats <- c("estimate" = "Estimate", "std_error" = "Std. Error", "pvalue" = "Pr(>|z|)") |
457 | 6x |
v1_comp <- xs_level[[vars[1]]][-1] |
458 | 6x |
if (xs_class[vars[2]] == "numeric") { |
459 | 3x |
x_stats <- as.data.frame( |
460 | 3x |
xs_coef[paste0(vars[1], v1_comp, ":", vars[2]), stats, drop = FALSE], |
461 | 3x |
stringsAsFactors = FALSE |
462 |
) |
|
463 | 3x |
colnames(x_stats) <- names(stats) |
464 | 3x |
x_stats$term <- v1_comp |
465 | 3x |
x_numbers <- table(fit_glm$data[[vars[1]]]) |
466 | 3x |
x_stats$term_label <- h_simple_term_labels(v1_comp, x_numbers) |
467 | 3x |
v1_ref <- xs_level[[vars[1]]][1] |
468 | 3x |
term_main <- v1_ref |
469 | 3x |
ref_label <- h_simple_term_labels(v1_ref, x_numbers) |
470 | 3x |
} else if (xs_class[vars[2]] != "numeric") { |
471 | 3x |
v2_comp <- xs_level[[vars[2]]][-1] |
472 | 3x |
v1_v2_grid <- expand.grid(v1 = v1_comp, v2 = v2_comp) |
473 | 3x |
x_sel <- paste( |
474 | 3x |
paste0(vars[1], v1_v2_grid$v1), |
475 | 3x |
paste0(vars[2], v1_v2_grid$v2), |
476 | 3x |
sep = ":" |
477 |
) |
|
478 | 3x |
x_stats <- as.data.frame(xs_coef[x_sel, stats, drop = FALSE], stringsAsFactors = FALSE) |
479 | 3x |
colnames(x_stats) <- names(stats) |
480 | 3x |
x_stats$term <- paste(v1_v2_grid$v1, "*", v1_v2_grid$v2) |
481 | 3x |
x_numbers <- table(fit_glm$data[[vars[1]]], fit_glm$data[[vars[2]]]) |
482 | 3x |
x_stats$term_label <- h_interaction_term_labels(v1_v2_grid$v1, v1_v2_grid$v2, x_numbers) |
483 | 3x |
v1_ref <- xs_level[[vars[1]]][1] |
484 | 3x |
v2_ref <- xs_level[[vars[2]]][1] |
485 | 3x |
term_main <- paste(vars[1], vars[2], sep = " * ") |
486 | 3x |
ref_label <- h_interaction_term_labels(v1_ref, v2_ref, x_numbers, any = TRUE) |
487 |
} |
|
488 | 6x |
x_stats$df <- as.list(1) |
489 | 6x |
x_stats$pvalue <- as.list(x_stats$pvalue) |
490 | 6x |
x_stats$is_variable_summary <- FALSE |
491 | 6x |
x_stats$is_term_summary <- TRUE |
492 | 6x |
x_main <- data.frame( |
493 | 6x |
pvalue = main_effects[x, "Pr(>Chisq)", drop = TRUE], |
494 | 6x |
term = term_main, |
495 | 6x |
term_label = paste("Reference", ref_label), |
496 | 6x |
df = main_effects[x, "Df", drop = TRUE], |
497 | 6x |
stringsAsFactors = FALSE |
498 |
) |
|
499 | 6x |
x_main$pvalue <- as.list(x_main$pvalue) |
500 | 6x |
x_main$df <- as.list(x_main$df) |
501 | 6x |
x_main$estimate <- list(numeric(0)) |
502 | 6x |
x_main$std_error <- list(numeric(0)) |
503 | 6x |
x_main$is_variable_summary <- TRUE |
504 | 6x |
x_main$is_term_summary <- FALSE |
505 | ||
506 | 6x |
x_stats <- rbind(x_main, x_stats) |
507 | 6x |
x_stats$variable <- x |
508 | 6x |
x_stats$variable_label <- paste( |
509 | 6x |
"Interaction of", |
510 | 6x |
formatters::var_labels(fit_glm$data[vars[1]], fill = TRUE), |
511 |
"*", |
|
512 | 6x |
formatters::var_labels(fit_glm$data[vars[2]], fill = TRUE) |
513 |
) |
|
514 | 6x |
x_stats$interaction <- "" |
515 | 6x |
x_stats$interaction_label <- "" |
516 | 6x |
x_stats$reference <- "" |
517 | 6x |
x_stats$reference_label <- "" |
518 | 6x |
rownames(x_stats) <- NULL |
519 | 6x |
x_stats[c( |
520 | 6x |
"variable", |
521 | 6x |
"variable_label", |
522 | 6x |
"term", |
523 | 6x |
"term_label", |
524 | 6x |
"interaction", |
525 | 6x |
"interaction_label", |
526 | 6x |
"reference", |
527 | 6x |
"reference_label", |
528 | 6x |
"estimate", |
529 | 6x |
"std_error", |
530 | 6x |
"df", |
531 | 6x |
"pvalue", |
532 | 6x |
"is_variable_summary", |
533 | 6x |
"is_term_summary" |
534 |
)] |
|
535 |
} |
|
536 | ||
537 |
#' @describeIn h_logistic_regression Helper function to tabulate the interaction |
|
538 |
#' results of a logistic regression model. This basically is a wrapper for |
|
539 |
#' [h_or_interaction()] and [h_glm_simple_term_extract()] which puts the results |
|
540 |
#' in the right data frame format. |
|
541 |
#' |
|
542 |
#' @return A `data.frame` of tabulated interaction term results from a logistic regression model. |
|
543 |
#' |
|
544 |
#' @examples |
|
545 |
#' h_glm_inter_term_extract("AGE", "ARMCD", mod2) |
|
546 |
#' |
|
547 |
#' @export |
|
548 |
h_glm_inter_term_extract <- function(odds_ratio_var, |
|
549 |
interaction_var, |
|
550 |
fit_glm, |
|
551 |
...) { |
|
552 |
# First obtain the main effects. |
|
553 | 11x |
main_stats <- h_glm_simple_term_extract(odds_ratio_var, fit_glm) |
554 | 11x |
main_stats$is_reference_summary <- FALSE |
555 | 11x |
main_stats$odds_ratio <- NA |
556 | 11x |
main_stats$lcl <- NA |
557 | 11x |
main_stats$ucl <- NA |
558 | ||
559 |
# Then we get the odds ratio estimates and put into df form. |
|
560 | 11x |
or_numbers <- h_or_interaction(odds_ratio_var, interaction_var, fit_glm, ...) |
561 | 11x |
is_num_or_var <- attr(fit_glm$terms, "dataClasses")[odds_ratio_var] == "numeric" |
562 | ||
563 | 11x |
if (is_num_or_var) { |
564 |
# Numeric OR variable case. |
|
565 | 3x |
references <- names(or_numbers) |
566 | 3x |
n_ref <- length(references) |
567 | ||
568 | 3x |
extract_from_list <- function(l, name, pos = 1) { |
569 | 9x |
unname(unlist( |
570 | 9x |
lapply(or_numbers, function(x) { |
571 | 27x |
x[[name]][pos] |
572 |
}) |
|
573 |
)) |
|
574 |
} |
|
575 | 3x |
or_stats <- data.frame( |
576 | 3x |
variable = odds_ratio_var, |
577 | 3x |
variable_label = unname(formatters::var_labels(fit_glm$data[odds_ratio_var], fill = TRUE)), |
578 | 3x |
term = odds_ratio_var, |
579 | 3x |
term_label = unname(formatters::var_labels(fit_glm$data[odds_ratio_var], fill = TRUE)), |
580 | 3x |
interaction = interaction_var, |
581 | 3x |
interaction_label = unname(formatters::var_labels(fit_glm$data[interaction_var], fill = TRUE)), |
582 | 3x |
reference = references, |
583 | 3x |
reference_label = references, |
584 | 3x |
estimate = NA, |
585 | 3x |
std_error = NA, |
586 | 3x |
odds_ratio = extract_from_list(or_numbers, "or"), |
587 | 3x |
lcl = extract_from_list(or_numbers, "ci", pos = "lcl"), |
588 | 3x |
ucl = extract_from_list(or_numbers, "ci", pos = "ucl"), |
589 | 3x |
df = NA, |
590 | 3x |
pvalue = NA, |
591 | 3x |
is_variable_summary = FALSE, |
592 | 3x |
is_term_summary = FALSE, |
593 | 3x |
is_reference_summary = TRUE |
594 |
) |
|
595 |
} else { |
|
596 |
# Categorical OR variable case. |
|
597 | 8x |
references <- names(or_numbers[[1]]) |
598 | 8x |
n_ref <- length(references) |
599 | ||
600 | 8x |
extract_from_list <- function(l, name, pos = 1) { |
601 | 24x |
unname(unlist( |
602 | 24x |
lapply(or_numbers, function(x) { |
603 | 42x |
lapply(x, function(y) y[[name]][pos]) |
604 |
}) |
|
605 |
)) |
|
606 |
} |
|
607 | 8x |
or_stats <- data.frame( |
608 | 8x |
variable = odds_ratio_var, |
609 | 8x |
variable_label = unname(formatters::var_labels(fit_glm$data[odds_ratio_var], fill = TRUE)), |
610 | 8x |
term = rep(names(or_numbers), each = n_ref), |
611 | 8x |
term_label = h_simple_term_labels(rep(names(or_numbers), each = n_ref), table(fit_glm$data[[odds_ratio_var]])), |
612 | 8x |
interaction = interaction_var, |
613 | 8x |
interaction_label = unname(formatters::var_labels(fit_glm$data[interaction_var], fill = TRUE)), |
614 | 8x |
reference = unlist(lapply(or_numbers, names)), |
615 | 8x |
reference_label = unlist(lapply(or_numbers, names)), |
616 | 8x |
estimate = NA, |
617 | 8x |
std_error = NA, |
618 | 8x |
odds_ratio = extract_from_list(or_numbers, "or"), |
619 | 8x |
lcl = extract_from_list(or_numbers, "ci", pos = "lcl"), |
620 | 8x |
ucl = extract_from_list(or_numbers, "ci", pos = "ucl"), |
621 | 8x |
df = NA, |
622 | 8x |
pvalue = NA, |
623 | 8x |
is_variable_summary = FALSE, |
624 | 8x |
is_term_summary = FALSE, |
625 | 8x |
is_reference_summary = TRUE |
626 |
) |
|
627 |
} |
|
628 | ||
629 | 11x |
df <- rbind( |
630 | 11x |
main_stats[, names(or_stats)], |
631 | 11x |
or_stats |
632 |
) |
|
633 | 11x |
df[order(-df$is_variable_summary, df$term, -df$is_term_summary, df$reference), ] |
634 |
} |
|
635 | ||
636 |
#' @describeIn h_logistic_regression Helper function to tabulate the results including |
|
637 |
#' odds ratios and confidence intervals of simple terms. |
|
638 |
#' |
|
639 |
#' @return Tabulated statistics for the given variable(s) from the logistic regression model. |
|
640 |
#' |
|
641 |
#' @examples |
|
642 |
#' h_logistic_simple_terms("AGE", mod1) |
|
643 |
#' |
|
644 |
#' @export |
|
645 |
h_logistic_simple_terms <- function(x, fit_glm, conf_level = 0.95) { |
|
646 | 52x |
checkmate::assert_multi_class(fit_glm, c("glm", "clogit")) |
647 | 52x |
if (inherits(fit_glm, "glm")) { |
648 | 41x |
checkmate::assert_set_equal(fit_glm$family$family, "binomial") |
649 |
} |
|
650 | 52x |
terms_name <- attr(stats::terms(fit_glm), "term.labels") |
651 | 52x |
xs_class <- attr(fit_glm$terms, "dataClasses") |
652 | 52x |
interaction <- terms_name[which(!terms_name %in% names(xs_class))] |
653 | 52x |
checkmate::assert_subset(x, terms_name) |
654 | 52x |
if (length(interaction) != 0) { |
655 |
# Make sure any item in x is not part of interaction term |
|
656 | 1x |
checkmate::assert_disjunct(x, unlist(strsplit(interaction, ":"))) |
657 |
} |
|
658 | 52x |
x_stats <- lapply(x, h_glm_simple_term_extract, fit_glm) |
659 | 52x |
x_stats <- do.call(rbind, x_stats) |
660 | 52x |
q_norm <- stats::qnorm((1 + conf_level) / 2) |
661 | 52x |
x_stats$odds_ratio <- lapply(x_stats$estimate, exp) |
662 | 52x |
x_stats$lcl <- Map(function(or, se) exp(log(or) - q_norm * se), x_stats$odds_ratio, x_stats$std_error) |
663 | 52x |
x_stats$ucl <- Map(function(or, se) exp(log(or) + q_norm * se), x_stats$odds_ratio, x_stats$std_error) |
664 | 52x |
x_stats$ci <- Map(function(lcl, ucl) c(lcl, ucl), lcl = x_stats$lcl, ucl = x_stats$ucl) |
665 | 52x |
x_stats |
666 |
} |
|
667 | ||
668 |
#' @describeIn h_logistic_regression Helper function to tabulate the results including |
|
669 |
#' odds ratios and confidence intervals of interaction terms. |
|
670 |
#' |
|
671 |
#' @return Tabulated statistics for the given variable(s) from the logistic regression model. |
|
672 |
#' |
|
673 |
#' @examples |
|
674 |
#' h_logistic_inter_terms(c("RACE", "AGE", "ARMCD", "AGE:ARMCD"), mod2) |
|
675 |
#' |
|
676 |
#' @export |
|
677 |
h_logistic_inter_terms <- function(x, |
|
678 |
fit_glm, |
|
679 |
conf_level = 0.95, |
|
680 |
at = NULL) { |
|
681 |
# Find out the interaction variables and interaction term. |
|
682 | 4x |
inter_vars <- h_get_interaction_vars(fit_glm) |
683 | 4x |
checkmate::assert_vector(inter_vars, len = 2) |
684 | ||
685 | ||
686 | 4x |
inter_term_index <- intersect(grep(inter_vars[1], x), grep(inter_vars[2], x)) |
687 | 4x |
inter_term <- x[inter_term_index] |
688 | ||
689 |
# For the non-interaction vars we need the standard stuff. |
|
690 | 4x |
normal_terms <- setdiff(x, union(inter_vars, inter_term)) |
691 | ||
692 | 4x |
x_stats <- lapply(normal_terms, h_glm_simple_term_extract, fit_glm) |
693 | 4x |
x_stats <- do.call(rbind, x_stats) |
694 | 4x |
q_norm <- stats::qnorm((1 + conf_level) / 2) |
695 | 4x |
x_stats$odds_ratio <- lapply(x_stats$estimate, exp) |
696 | 4x |
x_stats$lcl <- Map(function(or, se) exp(log(or) - q_norm * se), x_stats$odds_ratio, x_stats$std_error) |
697 | 4x |
x_stats$ucl <- Map(function(or, se) exp(log(or) + q_norm * se), x_stats$odds_ratio, x_stats$std_error) |
698 | 4x |
normal_stats <- x_stats |
699 | 4x |
normal_stats$is_reference_summary <- FALSE |
700 | ||
701 |
# Now the interaction term itself. |
|
702 | 4x |
inter_term_stats <- h_glm_interaction_extract(inter_term, fit_glm) |
703 | 4x |
inter_term_stats$odds_ratio <- NA |
704 | 4x |
inter_term_stats$lcl <- NA |
705 | 4x |
inter_term_stats$ucl <- NA |
706 | 4x |
inter_term_stats$is_reference_summary <- FALSE |
707 | ||
708 | 4x |
is_intervar1_numeric <- attr(fit_glm$terms, "dataClasses")[inter_vars[1]] == "numeric" |
709 | ||
710 |
# Interaction stuff. |
|
711 | 4x |
inter_stats_one <- h_glm_inter_term_extract( |
712 | 4x |
inter_vars[1], |
713 | 4x |
inter_vars[2], |
714 | 4x |
fit_glm, |
715 | 4x |
conf_level = conf_level, |
716 | 4x |
at = `if`(is_intervar1_numeric, NULL, at) |
717 |
) |
|
718 | 4x |
inter_stats_two <- h_glm_inter_term_extract( |
719 | 4x |
inter_vars[2], |
720 | 4x |
inter_vars[1], |
721 | 4x |
fit_glm, |
722 | 4x |
conf_level = conf_level, |
723 | 4x |
at = `if`(is_intervar1_numeric, at, NULL) |
724 |
) |
|
725 | ||
726 |
# Now just combine everything in one data frame. |
|
727 | 4x |
col_names <- c( |
728 | 4x |
"variable", |
729 | 4x |
"variable_label", |
730 | 4x |
"term", |
731 | 4x |
"term_label", |
732 | 4x |
"interaction", |
733 | 4x |
"interaction_label", |
734 | 4x |
"reference", |
735 | 4x |
"reference_label", |
736 | 4x |
"estimate", |
737 | 4x |
"std_error", |
738 | 4x |
"df", |
739 | 4x |
"pvalue", |
740 | 4x |
"odds_ratio", |
741 | 4x |
"lcl", |
742 | 4x |
"ucl", |
743 | 4x |
"is_variable_summary", |
744 | 4x |
"is_term_summary", |
745 | 4x |
"is_reference_summary" |
746 |
) |
|
747 | 4x |
df <- rbind( |
748 | 4x |
inter_stats_one[, col_names], |
749 | 4x |
inter_stats_two[, col_names], |
750 | 4x |
inter_term_stats[, col_names] |
751 |
) |
|
752 | 4x |
if (length(normal_terms) > 0) { |
753 | 4x |
df <- rbind( |
754 | 4x |
normal_stats[, col_names], |
755 | 4x |
df |
756 |
) |
|
757 |
} |
|
758 | 4x |
df$ci <- combine_vectors(df$lcl, df$ucl) |
759 | 4x |
df |
760 |
} |
1 |
#' Univariate Formula Special Term |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' The special term `univariate` indicate that the model should be fitted individually for |
|
6 |
#' every variable included in univariate. |
|
7 |
#' |
|
8 |
#' @param x A vector of variable name separated by commas. |
|
9 |
#' |
|
10 |
#' @return When used within a model formula, produces univariate models for each variable provided. |
|
11 |
#' |
|
12 |
#' @details |
|
13 |
#' If provided alongside with pairwise specification, the model |
|
14 |
#' `y ~ ARM + univariate(SEX, AGE, RACE)` lead to the study and comparison of the models |
|
15 |
#' + `y ~ ARM` |
|
16 |
#' + `y ~ ARM + SEX` |
|
17 |
#' + `y ~ ARM + AGE` |
|
18 |
#' + `y ~ ARM + RACE` |
|
19 |
#' |
|
20 |
#' @export |
|
21 |
univariate <- function(x) { |
|
22 | 1x |
structure(x, varname = deparse(substitute(x))) |
23 |
} |
|
24 | ||
25 |
# Get the right-hand-term of a formula |
|
26 |
rht <- function(x) { |
|
27 | 4x |
checkmate::assert_formula(x) |
28 | 4x |
y <- as.character(rev(x)[[1]]) |
29 | 4x |
return(y) |
30 |
} |
|
31 | ||
32 |
#' Hazard Ratio Estimation in Interactions |
|
33 |
#' |
|
34 |
#' This function estimates the hazard ratios between arms when an interaction variable is given with |
|
35 |
#' specific values. |
|
36 |
#' |
|
37 |
#' @param variable,given Names of two variable in interaction. We seek the estimation of the levels of `variable` |
|
38 |
#' given the levels of `given`. |
|
39 |
#' @param lvl_var,lvl_given corresponding levels has given by `levels`. |
|
40 |
#' @param mmat A name numeric filled with 0 used as template to obtain the design matrix. |
|
41 |
#' @param coef Numeric of estimated coefficients. |
|
42 |
#' @param vcov Variance-covariance matrix of underlying model. |
|
43 |
#' @param conf_level Single numeric for the confidence level of estimate intervals. |
|
44 |
#' |
|
45 |
#' @details Given the cox regression investigating the effect of Arm (A, B, C; reference A) |
|
46 |
#' and Sex (F, M; reference Female). The model is abbreviated: y ~ Arm + Sex + Arm x Sex. |
|
47 |
#' The cox regression estimates the coefficients along with a variance-covariance matrix for: |
|
48 |
#' |
|
49 |
#' - b1 (arm b), b2 (arm c) |
|
50 |
#' - b3 (sex m) |
|
51 |
#' - b4 (arm b: sex m), b5 (arm c: sex m) |
|
52 |
#' |
|
53 |
#' Given that I want an estimation of the Hazard Ratio for arm C/sex M, the estimation |
|
54 |
#' will be given in reference to arm A/Sex M by exp(b2 + b3 + b5)/ exp(b3) = exp(b2 + b5), |
|
55 |
#' therefore the interaction coefficient is given by b2 + b5 while the standard error is obtained |
|
56 |
#' as $1.96 * sqrt(Var b2 + Var b5 + 2 * covariance (b2,b5))$ for a confidence level of 0.95. |
|
57 |
#' |
|
58 |
#' @return A list of matrix (one per level of variable) with rows corresponding to the combinations of |
|
59 |
#' `variable` and `given`, with columns: |
|
60 |
#' * `coef_hat`: Estimation of the coefficient. |
|
61 |
#' * `coef_se`: Standard error of the estimation. |
|
62 |
#' * `hr`: Hazard ratio. |
|
63 |
#' * `lcl, ucl`: Lower/upper confidence limit of the hazard ratio. |
|
64 |
#' |
|
65 |
#' @seealso [s_cox_multivariate()]. |
|
66 |
#' |
|
67 |
#' @examples |
|
68 |
#' library(dplyr) |
|
69 |
#' library(survival) |
|
70 |
#' |
|
71 |
#' ADSL <- tern_ex_adsl %>% |
|
72 |
#' filter(SEX %in% c("F", "M")) |
|
73 |
#' |
|
74 |
#' adtte <- tern_ex_adtte %>% filter(PARAMCD == "PFS") |
|
75 |
#' adtte$ARMCD <- droplevels(adtte$ARMCD) |
|
76 |
#' adtte$SEX <- droplevels(adtte$SEX) |
|
77 |
#' |
|
78 |
#' mod <- coxph( |
|
79 |
#' formula = Surv(time = AVAL, event = 1 - CNSR) ~ (SEX + ARMCD)^2, |
|
80 |
#' data = adtte |
|
81 |
#' ) |
|
82 |
#' |
|
83 |
#' mmat <- stats::model.matrix(mod)[1, ] |
|
84 |
#' mmat[!mmat == 0] <- 0 |
|
85 |
#' |
|
86 |
#' @keywords internal |
|
87 |
estimate_coef <- function(variable, given, |
|
88 |
lvl_var, lvl_given, |
|
89 |
coef, |
|
90 |
mmat, |
|
91 |
vcov, |
|
92 |
conf_level = 0.95) { |
|
93 | 8x |
var_lvl <- paste0(variable, lvl_var[-1]) # [-1]: reference level |
94 | 8x |
giv_lvl <- paste0(given, lvl_given) |
95 | ||
96 | 8x |
design_mat <- expand.grid(variable = var_lvl, given = giv_lvl) |
97 | 8x |
design_mat <- design_mat[order(design_mat$variable, design_mat$given), ] |
98 | 8x |
design_mat <- within( |
99 | 8x |
data = design_mat, |
100 | 8x |
expr = { |
101 | 8x |
inter <- paste0(variable, ":", given) |
102 | 8x |
rev_inter <- paste0(given, ":", variable) |
103 |
} |
|
104 |
) |
|
105 | ||
106 | 8x |
split_by_variable <- design_mat$variable |
107 | 8x |
interaction_names <- paste(design_mat$variable, design_mat$given, sep = "/") |
108 | ||
109 | 8x |
design_mat <- apply( |
110 | 8x |
X = design_mat, MARGIN = 1, FUN = function(x) { |
111 | 27x |
mmat[names(mmat) %in% x[-which(names(x) == "given")]] <- 1 |
112 | 27x |
return(mmat) |
113 |
} |
|
114 |
) |
|
115 | 8x |
colnames(design_mat) <- interaction_names |
116 | ||
117 | 8x |
betas <- as.matrix(coef) |
118 | ||
119 | 8x |
coef_hat <- t(design_mat) %*% betas |
120 | 8x |
dimnames(coef_hat)[2] <- "coef" |
121 | ||
122 | 8x |
coef_se <- apply(design_mat, 2, function(x) { |
123 | 27x |
vcov_el <- as.logical(x) |
124 | 27x |
y <- vcov[vcov_el, vcov_el] |
125 | 27x |
y <- sum(y) |
126 | 27x |
y <- sqrt(y) |
127 | 27x |
return(y) |
128 |
}) |
|
129 | ||
130 | 8x |
q_norm <- stats::qnorm((1 + conf_level) / 2) |
131 | 8x |
y <- cbind(coef_hat, `se(coef)` = coef_se) |
132 | ||
133 | 8x |
y <- apply(y, 1, function(x) { |
134 | 27x |
x["hr"] <- exp(x["coef"]) |
135 | 27x |
x["lcl"] <- exp(x["coef"] - q_norm * x["se(coef)"]) |
136 | 27x |
x["ucl"] <- exp(x["coef"] + q_norm * x["se(coef)"]) |
137 | ||
138 | 27x |
return(x) |
139 |
}) |
|
140 | ||
141 | 8x |
y <- t(y) |
142 | 8x |
y <- by(y, split_by_variable, identity) |
143 | 8x |
y <- lapply(y, as.matrix) |
144 | ||
145 | 8x |
attr(y, "details") <- paste0( |
146 | 8x |
"Estimations of ", variable, |
147 | 8x |
" hazard ratio given the level of ", given, " compared to ", |
148 | 8x |
variable, " level ", lvl_var[1], "." |
149 |
) |
|
150 | 8x |
return(y) |
151 |
} |
|
152 | ||
153 |
#' `tryCatch` around `car::Anova` |
|
154 |
#' |
|
155 |
#' Captures warnings when executing [car::Anova]. |
|
156 |
#' |
|
157 |
#' @inheritParams car::Anova |
|
158 |
#' |
|
159 |
#' @return A list with item `aov` for the result of the model and `error_text` for the captured warnings. |
|
160 |
#' |
|
161 |
#' @examples |
|
162 |
#' # `car::Anova` on cox regression model including strata and expected |
|
163 |
#' # a likelihood ratio test triggers a warning as only `Wald` method is |
|
164 |
#' # accepted. |
|
165 |
#' |
|
166 |
#' library(survival) |
|
167 |
#' |
|
168 |
#' mod <- coxph( |
|
169 |
#' formula = Surv(time = futime, event = fustat) ~ factor(rx) + strata(ecog.ps), |
|
170 |
#' data = ovarian |
|
171 |
#' ) |
|
172 |
#' |
|
173 |
#' @keywords internal |
|
174 |
try_car_anova <- function(mod, |
|
175 |
test.statistic) { # nolint |
|
176 | 2x |
y <- tryCatch( |
177 | 2x |
withCallingHandlers( |
178 | 2x |
expr = { |
179 | 2x |
warn_text <- c() |
180 | 2x |
list( |
181 | 2x |
aov = car::Anova( |
182 | 2x |
mod, |
183 | 2x |
test.statistic = test.statistic, |
184 | 2x |
type = "III" |
185 |
), |
|
186 | 2x |
warn_text = warn_text |
187 |
) |
|
188 |
}, |
|
189 | 2x |
warning = function(w) { |
190 |
# If a warning is detected it is handled as "w". |
|
191 | ! |
warn_text <<- trimws(paste0("Warning in `try_car_anova`: ", w)) |
192 | ||
193 |
# A warning is sometimes expected, then, we want to restart |
|
194 |
# the execution while ignoring the warning. |
|
195 | ! |
invokeRestart("muffleWarning") |
196 |
} |
|
197 |
), |
|
198 | 2x |
finally = { |
199 |
} |
|
200 |
) |
|
201 | ||
202 | 2x |
return(y) |
203 |
} |
|
204 | ||
205 |
#' Fit the Cox Regression Model and `Anova` |
|
206 |
#' |
|
207 |
#' The functions allows to derive from the [survival::coxph()] results the effect p.values using [car::Anova()]. |
|
208 |
#' This last package introduces more flexibility to get the effect p.values. |
|
209 |
#' |
|
210 |
#' @inheritParams t_coxreg |
|
211 |
#' |
|
212 |
#' @return A list with items `mod` (results of [survival::coxph()]), `msum` (result of `summary`) and |
|
213 |
#' `aov` (result of [car::Anova()]). |
|
214 |
#' |
|
215 |
#' @noRd |
|
216 |
fit_n_aov <- function(formula, |
|
217 |
data = data, |
|
218 |
conf_level = conf_level, |
|
219 |
pval_method = c("wald", "likelihood"), |
|
220 |
...) { |
|
221 | 1x |
pval_method <- match.arg(pval_method) |
222 | ||
223 | 1x |
environment(formula) <- environment() |
224 | 1x |
suppressWarnings({ |
225 |
# We expect some warnings due to coxph which fails strict programming. |
|
226 | 1x |
mod <- survival::coxph(formula, data = data, ...) |
227 | 1x |
msum <- summary(mod, conf.int = conf_level) |
228 |
}) |
|
229 | ||
230 | 1x |
aov <- try_car_anova( |
231 | 1x |
mod, |
232 | 1x |
test.statistic = switch(pval_method, |
233 | 1x |
"wald" = "Wald", |
234 | 1x |
"likelihood" = "LR" |
235 |
) |
|
236 |
) |
|
237 | ||
238 | 1x |
warn_attr <- aov$warn_text |
239 | ! |
if (!is.null(aov$warn_text)) message(warn_attr) |
240 | ||
241 | 1x |
aov <- aov$aov |
242 | 1x |
y <- list(mod = mod, msum = msum, aov = aov) |
243 | 1x |
attr(y, "message") <- warn_attr |
244 | ||
245 | 1x |
return(y) |
246 |
} |
|
247 | ||
248 |
# argument_checks |
|
249 |
check_formula <- function(formula) { |
|
250 | 1x |
if (!(inherits(formula, "formula"))) { |
251 | 1x |
stop("Check `formula`. A formula should resemble `Surv(time = AVAL, event = 1 - CNSR) ~ study_arm(ARMCD)`.") |
252 |
} |
|
253 | ||
254 | ! |
invisible() |
255 |
} |
|
256 | ||
257 |
check_covariate_formulas <- function(covariates) { |
|
258 | 1x |
if (!all(vapply(X = covariates, FUN = inherits, what = "formula", FUN.VALUE = TRUE)) || is.null(covariates)) { |
259 | 1x |
stop("Check `covariates`, it should be a list of right-hand-term formulas, e.g. list(Age = ~AGE).") |
260 |
} |
|
261 | ||
262 | ! |
invisible() |
263 |
} |
|
264 | ||
265 |
name_covariate_names <- function(covariates) { |
|
266 | 1x |
miss_names <- names(covariates) == "" |
267 | 1x |
no_names <- is.null(names(covariates)) |
268 | ! |
if (any(miss_names)) names(covariates)[miss_names] <- vapply(covariates[miss_names], FUN = rht, FUN.VALUE = "name") |
269 | ! |
if (no_names) names(covariates) <- vapply(covariates, FUN = rht, FUN.VALUE = "name") |
270 | 1x |
return(covariates) |
271 |
} |
|
272 | ||
273 |
check_increments <- function(increments, covariates) { |
|
274 | 1x |
if (!is.null(increments)) { |
275 | 1x |
covariates <- vapply(covariates, FUN = rht, FUN.VALUE = "name") |
276 | 1x |
lapply( |
277 | 1x |
X = names(increments), FUN = function(x) { |
278 | 3x |
if (!x %in% covariates) { |
279 | 1x |
warning( |
280 | 1x |
paste( |
281 | 1x |
"Check `increments`, the `increment` for ", x, |
282 | 1x |
"doesn't match any names in investigated covariate(s)." |
283 |
) |
|
284 |
) |
|
285 |
} |
|
286 |
} |
|
287 |
) |
|
288 |
} |
|
289 | ||
290 | 1x |
invisible() |
291 |
} |
|
292 | ||
293 |
#' Multivariate Cox Model - Summarized Results |
|
294 |
#' |
|
295 |
#' Analyses based on multivariate Cox model are usually not performed for the Controlled Substance Reporting or |
|
296 |
#' regulatory documents but serve exploratory purposes only (e.g., for publication). In practice, the model usually |
|
297 |
#' includes only the main effects (without interaction terms). It produces the hazard ratio estimates for each of the |
|
298 |
#' covariates included in the model. |
|
299 |
#' The analysis follows the same principles (e.g., stratified vs. unstratified analysis and tie handling) as the |
|
300 |
#' usual Cox model analysis. Since there is usually no pre-specified hypothesis testing for such analysis, |
|
301 |
#' the p.values need to be interpreted with caution. (**Statistical Analysis of Clinical Trials Data with R**, |
|
302 |
#' `NEST's bookdown`) |
|
303 |
#' |
|
304 |
#' @param formula (`formula`)\cr A formula corresponding to the investigated [survival::Surv()] survival model |
|
305 |
#' including covariates. |
|
306 |
#' @param data (`data.frame`)\cr A data frame which includes the variable in formula and covariates. |
|
307 |
#' @param conf_level (`proportion`)\cr The confidence level for the hazard ratio interval estimations. Default is 0.95. |
|
308 |
#' @param pval_method (`character`)\cr The method used for the estimation of p-values, should be one of |
|
309 |
#' `"wald"` (default) or `"likelihood"`. |
|
310 |
#' @param ... Optional parameters passed to [survival::coxph()]. Can include `ties`, a character string specifying the |
|
311 |
#' method for tie handling, one of `exact` (default), `efron`, `breslow`. |
|
312 |
#' |
|
313 |
#' @return A `list` with elements `mod`, `msum`, `aov`, and `coef_inter`. |
|
314 |
#' |
|
315 |
#' @details The output is limited to single effect terms. Work in ongoing for estimation of interaction terms |
|
316 |
#' but is out of scope as defined by the Global Data Standards Repository |
|
317 |
#' (**`GDS_Standard_TLG_Specs_Tables_2.doc`**). |
|
318 |
#' |
|
319 |
#' @seealso [estimate_coef()]. |
|
320 |
#' |
|
321 |
#' @examples |
|
322 |
#' library(dplyr) |
|
323 |
#' |
|
324 |
#' adtte <- tern_ex_adtte |
|
325 |
#' adtte_f <- subset(adtte, PARAMCD == "OS") # _f: filtered |
|
326 |
#' adtte_f <- filter( |
|
327 |
#' adtte_f, |
|
328 |
#' PARAMCD == "OS" & |
|
329 |
#' SEX %in% c("F", "M") & |
|
330 |
#' RACE %in% c("ASIAN", "BLACK OR AFRICAN AMERICAN", "WHITE") |
|
331 |
#' ) |
|
332 |
#' adtte_f$SEX <- droplevels(adtte_f$SEX) |
|
333 |
#' adtte_f$RACE <- droplevels(adtte_f$RACE) |
|
334 |
#' |
|
335 |
#' @keywords internal |
|
336 |
s_cox_multivariate <- function(formula, data, |
|
337 |
conf_level = 0.95, |
|
338 |
pval_method = c("wald", "likelihood"), |
|
339 |
...) { |
|
340 | 1x |
tf <- stats::terms(formula, specials = c("strata")) |
341 | 1x |
covariates <- rownames(attr(tf, "factors"))[-c(1, unlist(attr(tf, "specials")))] |
342 | 1x |
lapply( |
343 | 1x |
X = covariates, |
344 | 1x |
FUN = function(x) { |
345 | 3x |
if (is.character(data[[x]])) { |
346 | 1x |
data[[x]] <<- as.factor(data[[x]]) |
347 |
} |
|
348 | 3x |
invisible() |
349 |
} |
|
350 |
) |
|
351 | 1x |
pval_method <- match.arg(pval_method) |
352 | ||
353 |
# Results directly exported from environment(fit_n_aov) to environment(s_function_draft) |
|
354 | 1x |
y <- fit_n_aov( |
355 | 1x |
formula = formula, |
356 | 1x |
data = data, |
357 | 1x |
conf_level = conf_level, |
358 | 1x |
pval_method = pval_method, |
359 |
... |
|
360 |
) |
|
361 | 1x |
mod <- y$mod |
362 | 1x |
aov <- y$aov |
363 | 1x |
msum <- y$msum |
364 | 1x |
list2env(as.list(y), environment()) |
365 | ||
366 | 1x |
all_term_labs <- attr(mod$terms, "term.labels") |
367 | 1x |
term_labs <- all_term_labs[which(attr(mod$terms, "order") == 1)] |
368 | 1x |
names(term_labs) <- term_labs |
369 | ||
370 | 1x |
coef_inter <- NULL |
371 | 1x |
if (any(attr(mod$terms, "order") > 1)) { |
372 | 1x |
for_inter <- all_term_labs[attr(mod$terms, "order") > 1] |
373 | 1x |
names(for_inter) <- for_inter |
374 | 1x |
mmat <- stats::model.matrix(mod)[1, ] |
375 | 1x |
mmat[!mmat == 0] <- 0 |
376 | 1x |
mcoef <- stats::coef(mod) |
377 | 1x |
mvcov <- stats::vcov(mod) |
378 | ||
379 | 1x |
estimate_coef_local <- function(variable, given) { |
380 | 6x |
estimate_coef( |
381 | 6x |
variable, given, |
382 | 6x |
coef = mcoef, mmat = mmat, vcov = mvcov, conf_level = conf_level, |
383 | 6x |
lvl_var = levels(data[[variable]]), lvl_given = levels(data[[given]]) |
384 |
) |
|
385 |
} |
|
386 | ||
387 | 1x |
coef_inter <- lapply( |
388 | 1x |
for_inter, function(x) { |
389 | 3x |
y <- attr(mod$terms, "factor")[, x] |
390 | 3x |
y <- names(y[y > 0]) |
391 | 3x |
Map(estimate_coef_local, variable = y, given = rev(y)) |
392 |
} |
|
393 |
) |
|
394 |
} |
|
395 | ||
396 | 1x |
list(mod = mod, msum = msum, aov = aov, coef_inter = coef_inter) |
397 |
} |
1 |
#' Tabulate Survival Duration by Subgroup |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Tabulate statistics such as median survival time and hazard ratio for population subgroups. |
|
6 |
#' |
|
7 |
#' @inheritParams argument_convention |
|
8 |
#' @inheritParams survival_coxph_pairwise |
|
9 |
#' @param df (`list`)\cr of data frames containing all analysis variables. List should be |
|
10 |
#' created using [extract_survival_subgroups()]. |
|
11 |
#' @param vars (`character`)\cr the name of statistics to be reported among: |
|
12 |
#' * `n_tot_events`: Total number of events per group. |
|
13 |
#' * `n_events`: Number of events per group. |
|
14 |
#' * `n_tot`: Total number of observations per group. |
|
15 |
#' * `n`: Number of observations per group. |
|
16 |
#' * `median`: Median survival time. |
|
17 |
#' * `hr`: Hazard ratio. |
|
18 |
#' * `ci`: Confidence interval of hazard ratio. |
|
19 |
#' * `pval`: p-value of the effect. |
|
20 |
#' Note, one of the statistics `n_tot` and `n_tot_events`, as well as both `hr` and `ci` |
|
21 |
#' are required. |
|
22 |
#' @param time_unit (`string`)\cr label with unit of median survival time. Default `NULL` skips displaying unit. |
|
23 |
#' |
|
24 |
#' @details These functions create a layout starting from a data frame which contains |
|
25 |
#' the required statistics. Tables typically used as part of forest plot. |
|
26 |
#' |
|
27 |
#' @seealso [extract_survival_subgroups()] |
|
28 |
#' |
|
29 |
#' @examples |
|
30 |
#' library(dplyr) |
|
31 |
#' library(forcats) |
|
32 |
#' |
|
33 |
#' adtte <- tern_ex_adtte |
|
34 |
#' |
|
35 |
#' # Save variable labels before data processing steps. |
|
36 |
#' adtte_labels <- formatters::var_labels(adtte) |
|
37 |
#' |
|
38 |
#' adtte_f <- adtte %>% |
|
39 |
#' filter( |
|
40 |
#' PARAMCD == "OS", |
|
41 |
#' ARM %in% c("B: Placebo", "A: Drug X"), |
|
42 |
#' SEX %in% c("M", "F") |
|
43 |
#' ) %>% |
|
44 |
#' mutate( |
|
45 |
#' # Reorder levels of ARM to display reference arm before treatment arm. |
|
46 |
#' ARM = droplevels(fct_relevel(ARM, "B: Placebo")), |
|
47 |
#' SEX = droplevels(SEX), |
|
48 |
#' AVALU = as.character(AVALU), |
|
49 |
#' is_event = CNSR == 0 |
|
50 |
#' ) |
|
51 |
#' labels <- c( |
|
52 |
#' "ARM" = adtte_labels[["ARM"]], |
|
53 |
#' "SEX" = adtte_labels[["SEX"]], |
|
54 |
#' "AVALU" = adtte_labels[["AVALU"]], |
|
55 |
#' "is_event" = "Event Flag" |
|
56 |
#' ) |
|
57 |
#' formatters::var_labels(adtte_f)[names(labels)] <- labels |
|
58 |
#' |
|
59 |
#' df <- extract_survival_subgroups( |
|
60 |
#' variables = list( |
|
61 |
#' tte = "AVAL", |
|
62 |
#' is_event = "is_event", |
|
63 |
#' arm = "ARM", subgroups = c("SEX", "BMRKR2") |
|
64 |
#' ), |
|
65 |
#' data = adtte_f |
|
66 |
#' ) |
|
67 |
#' df |
|
68 |
#' |
|
69 |
#' df_grouped <- extract_survival_subgroups( |
|
70 |
#' variables = list( |
|
71 |
#' tte = "AVAL", |
|
72 |
#' is_event = "is_event", |
|
73 |
#' arm = "ARM", subgroups = c("SEX", "BMRKR2") |
|
74 |
#' ), |
|
75 |
#' data = adtte_f, |
|
76 |
#' groups_lists = list( |
|
77 |
#' BMRKR2 = list( |
|
78 |
#' "low" = "LOW", |
|
79 |
#' "low/medium" = c("LOW", "MEDIUM"), |
|
80 |
#' "low/medium/high" = c("LOW", "MEDIUM", "HIGH") |
|
81 |
#' ) |
|
82 |
#' ) |
|
83 |
#' ) |
|
84 |
#' df_grouped |
|
85 |
#' |
|
86 |
#' @name survival_duration_subgroups |
|
87 |
#' @order 1 |
|
88 |
NULL |
|
89 | ||
90 |
#' Prepares Survival Data for Population Subgroups in Data Frames |
|
91 |
#' |
|
92 |
#' @description `r lifecycle::badge("stable")` |
|
93 |
#' |
|
94 |
#' Prepares estimates of median survival times and treatment hazard ratios for population subgroups in |
|
95 |
#' data frames. Simple wrapper for [h_survtime_subgroups_df()] and [h_coxph_subgroups_df()]. Result is a `list` |
|
96 |
#' of two `data.frame`s: `survtime` and `hr`. `variables` corresponds to the names of variables found in `data`, |
|
97 |
#' passed as a named `list` and requires elements `tte`, `is_event`, `arm` and optionally `subgroups` and `strat`. |
|
98 |
#' `groups_lists` optionally specifies groupings for `subgroups` variables. |
|
99 |
#' |
|
100 |
#' @inheritParams argument_convention |
|
101 |
#' @inheritParams survival_duration_subgroups |
|
102 |
#' @inheritParams survival_coxph_pairwise |
|
103 |
#' |
|
104 |
#' @return A named `list` of two elements: |
|
105 |
#' * `survtime`: A `data.frame` containing columns `arm`, `n`, `n_events`, `median`, `subgroup`, `var`, |
|
106 |
#' `var_label`, and `row_type`. |
|
107 |
#' * `hr`: A `data.frame` containing columns `arm`, `n_tot`, `n_tot_events`, `hr`, `lcl`, `ucl`, `conf_level`, |
|
108 |
#' `pval`, `pval_label`, `subgroup`, `var`, `var_label`, and `row_type`. |
|
109 |
#' |
|
110 |
#' @seealso [survival_duration_subgroups] |
|
111 |
#' |
|
112 |
#' @export |
|
113 |
extract_survival_subgroups <- function(variables, |
|
114 |
data, |
|
115 |
groups_lists = list(), |
|
116 |
control = control_coxph(), |
|
117 |
label_all = "All Patients") { |
|
118 | 9x |
df_survtime <- h_survtime_subgroups_df( |
119 | 9x |
variables, |
120 | 9x |
data, |
121 | 9x |
groups_lists = groups_lists, |
122 | 9x |
label_all = label_all |
123 |
) |
|
124 | 9x |
df_hr <- h_coxph_subgroups_df( |
125 | 9x |
variables, |
126 | 9x |
data, |
127 | 9x |
groups_lists = groups_lists, |
128 | 9x |
control = control, |
129 | 9x |
label_all = label_all |
130 |
) |
|
131 | ||
132 | 9x |
list(survtime = df_survtime, hr = df_hr) |
133 |
} |
|
134 | ||
135 |
#' @describeIn survival_duration_subgroups Formatted analysis function which is used as |
|
136 |
#' `afun` in `tabulate_survival_subgroups()`. |
|
137 |
#' |
|
138 |
#' @return |
|
139 |
#' * `a_survival_subgroups()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
140 |
#' |
|
141 |
#' @keywords internal |
|
142 |
a_survival_subgroups <- function(.formats = list( # nolint start |
|
143 |
n = "xx", |
|
144 |
n_events = "xx", |
|
145 |
n_tot_events = "xx", |
|
146 |
median = "xx.x", |
|
147 |
n_tot = "xx", |
|
148 |
hr = list(format_extreme_values(2L)), |
|
149 |
ci = list(format_extreme_values_ci(2L)), |
|
150 |
pval = "x.xxxx | (<0.0001)" |
|
151 |
), |
|
152 |
na_str = default_na_str()) { # nolint end |
|
153 | 15x |
checkmate::assert_list(.formats) |
154 | 15x |
checkmate::assert_subset( |
155 | 15x |
names(.formats), |
156 | 15x |
c("n", "n_events", "median", "n_tot", "n_tot_events", "hr", "ci", "pval") |
157 |
) |
|
158 | ||
159 | 15x |
afun_lst <- Map( |
160 | 15x |
function(stat, fmt, na_str) { |
161 | 114x |
if (stat == "ci") { |
162 | 14x |
function(df, labelstr = "", ...) { |
163 | 29x |
in_rows( |
164 | 29x |
.list = combine_vectors(df$lcl, df$ucl), |
165 | 29x |
.labels = as.character(df$subgroup), |
166 | 29x |
.formats = fmt, |
167 | 29x |
.format_na_strs = na_str |
168 |
) |
|
169 |
} |
|
170 |
} else { |
|
171 | 100x |
function(df, labelstr = "", ...) { |
172 | 159x |
in_rows( |
173 | 159x |
.list = as.list(df[[stat]]), |
174 | 159x |
.labels = as.character(df$subgroup), |
175 | 159x |
.formats = fmt, |
176 | 159x |
.format_na_strs = na_str |
177 |
) |
|
178 |
} |
|
179 |
} |
|
180 |
}, |
|
181 | 15x |
stat = names(.formats), |
182 | 15x |
fmt = .formats, |
183 | 15x |
na_str = na_str |
184 |
) |
|
185 | ||
186 | 15x |
afun_lst |
187 |
} |
|
188 | ||
189 |
#' @describeIn survival_duration_subgroups Table-creating function which creates a table |
|
190 |
#' summarizing survival by subgroup. This function is a wrapper for [rtables::analyze_colvars()] |
|
191 |
#' and [rtables::summarize_row_groups()]. |
|
192 |
#' |
|
193 |
#' @return An `rtables` table summarizing survival by subgroup. |
|
194 |
#' |
|
195 |
#' @examples |
|
196 |
#' ## Table with default columns. |
|
197 |
#' basic_table() %>% |
|
198 |
#' tabulate_survival_subgroups(df, time_unit = adtte_f$AVALU[1]) |
|
199 |
#' |
|
200 |
#' ## Table with a manually chosen set of columns: adding "pval". |
|
201 |
#' basic_table() %>% |
|
202 |
#' tabulate_survival_subgroups( |
|
203 |
#' df = df, |
|
204 |
#' vars = c("n_tot_events", "n_events", "median", "hr", "ci", "pval"), |
|
205 |
#' time_unit = adtte_f$AVALU[1] |
|
206 |
#' ) |
|
207 |
#' |
|
208 |
#' @export |
|
209 |
#' @order 2 |
|
210 |
tabulate_survival_subgroups <- function(lyt, |
|
211 |
df, |
|
212 |
vars = c("n_tot_events", "n_events", "median", "hr", "ci"), |
|
213 |
groups_lists = list(), |
|
214 |
label_all = "All Patients", |
|
215 |
time_unit = NULL, |
|
216 |
na_str = default_na_str()) { |
|
217 | 6x |
conf_level <- df$hr$conf_level[1] |
218 | 6x |
method <- df$hr$pval_label[1] |
219 | ||
220 | 6x |
extra_args <- list(groups_lists = groups_lists, conf_level = conf_level, method = method, label_all = label_all) |
221 | ||
222 | 6x |
afun_lst <- a_survival_subgroups(na_str = na_str) |
223 | 6x |
colvars <- d_survival_subgroups_colvars( |
224 | 6x |
vars, |
225 | 6x |
conf_level = conf_level, |
226 | 6x |
method = method, |
227 | 6x |
time_unit = time_unit |
228 |
) |
|
229 | ||
230 | 6x |
colvars_survtime <- list( |
231 | 6x |
vars = colvars$vars[names(colvars$labels) %in% c("n", "n_events", "median")], |
232 | 6x |
labels = colvars$labels[names(colvars$labels) %in% c("n", "n_events", "median")] |
233 |
) |
|
234 | 6x |
colvars_hr <- list( |
235 | 6x |
vars = colvars$vars[names(colvars$labels) %in% c("n_tot", "n_tot_events", "hr", "ci", "pval")], |
236 | 6x |
labels = colvars$labels[names(colvars$labels) %in% c("n_tot", "n_tot_events", "hr", "ci", "pval")] |
237 |
) |
|
238 | ||
239 |
# Columns from table_survtime are optional. |
|
240 | 6x |
if (length(colvars_survtime$vars) > 0) { |
241 | 5x |
lyt_survtime <- split_cols_by(lyt = lyt, var = "arm") |
242 | 5x |
lyt_survtime <- split_rows_by( |
243 | 5x |
lyt = lyt_survtime, |
244 | 5x |
var = "row_type", |
245 | 5x |
split_fun = keep_split_levels("content"), |
246 | 5x |
nested = FALSE |
247 |
) |
|
248 | 5x |
lyt_survtime <- summarize_row_groups( |
249 | 5x |
lyt = lyt_survtime, |
250 | 5x |
var = "var_label", |
251 | 5x |
cfun = afun_lst[names(colvars_survtime$labels)], |
252 | 5x |
na_str = na_str, |
253 | 5x |
extra_args = extra_args |
254 |
) |
|
255 | 5x |
lyt_survtime <- split_cols_by_multivar( |
256 | 5x |
lyt = lyt_survtime, |
257 | 5x |
vars = colvars_survtime$vars, |
258 | 5x |
varlabels = colvars_survtime$labels |
259 |
) |
|
260 | ||
261 | 5x |
if ("analysis" %in% df$survtime$row_type) { |
262 | 4x |
lyt_survtime <- split_rows_by( |
263 | 4x |
lyt = lyt_survtime, |
264 | 4x |
var = "row_type", |
265 | 4x |
split_fun = keep_split_levels("analysis"), |
266 | 4x |
nested = FALSE, |
267 | 4x |
child_labels = "hidden" |
268 |
) |
|
269 | 4x |
lyt_survtime <- split_rows_by(lyt = lyt_survtime, var = "var_label", nested = TRUE) |
270 | 4x |
lyt_survtime <- analyze_colvars( |
271 | 4x |
lyt = lyt_survtime, |
272 | 4x |
afun = afun_lst[names(colvars_survtime$labels)], |
273 | 4x |
na_str = na_str, |
274 | 4x |
inclNAs = TRUE, |
275 | 4x |
extra_args = extra_args |
276 |
) |
|
277 |
} |
|
278 | ||
279 | 5x |
table_survtime <- build_table(lyt_survtime, df = df$survtime) |
280 |
} else { |
|
281 | 1x |
table_survtime <- NULL |
282 |
} |
|
283 | ||
284 |
# Columns "n_tot_events" or "n_tot", and "hr", "ci" in table_hr are required. |
|
285 | 6x |
lyt_hr <- split_cols_by(lyt = lyt, var = "arm") |
286 | 6x |
lyt_hr <- split_rows_by( |
287 | 6x |
lyt = lyt_hr, |
288 | 6x |
var = "row_type", |
289 | 6x |
split_fun = keep_split_levels("content"), |
290 | 6x |
nested = FALSE |
291 |
) |
|
292 | 6x |
lyt_hr <- summarize_row_groups( |
293 | 6x |
lyt = lyt_hr, |
294 | 6x |
var = "var_label", |
295 | 6x |
cfun = afun_lst[names(colvars_hr$labels)], |
296 | 6x |
na_str = na_str, |
297 | 6x |
extra_args = extra_args |
298 |
) |
|
299 | 6x |
lyt_hr <- split_cols_by_multivar( |
300 | 6x |
lyt = lyt_hr, |
301 | 6x |
vars = colvars_hr$vars, |
302 | 6x |
varlabels = colvars_hr$labels |
303 |
) %>% |
|
304 | 6x |
append_topleft("Baseline Risk Factors") |
305 | ||
306 | 6x |
if ("analysis" %in% df$survtime$row_type) { |
307 | 5x |
lyt_hr <- split_rows_by( |
308 | 5x |
lyt = lyt_hr, |
309 | 5x |
var = "row_type", |
310 | 5x |
split_fun = keep_split_levels("analysis"), |
311 | 5x |
nested = FALSE, |
312 | 5x |
child_labels = "hidden" |
313 |
) |
|
314 | 5x |
lyt_hr <- split_rows_by(lyt = lyt_hr, var = "var_label", nested = TRUE) |
315 | 5x |
lyt_hr <- analyze_colvars( |
316 | 5x |
lyt = lyt_hr, |
317 | 5x |
afun = afun_lst[names(colvars_hr$labels)], |
318 | 5x |
na_str = na_str, |
319 | 5x |
inclNAs = TRUE, |
320 | 5x |
extra_args = extra_args |
321 |
) |
|
322 |
} |
|
323 | 6x |
table_hr <- build_table(lyt_hr, df = df$hr) |
324 | ||
325 |
# There can be one or two vars starting with "n_tot". |
|
326 | 6x |
n_tot_ids <- grep("^n_tot", colvars_hr$vars) |
327 | 6x |
if (is.null(table_survtime)) { |
328 | 1x |
result <- table_hr |
329 | 1x |
hr_id <- match("hr", colvars_hr$vars) |
330 | 1x |
ci_id <- match("lcl", colvars_hr$vars) |
331 |
} else { |
|
332 |
# Reorder the table. |
|
333 | 5x |
result <- cbind_rtables(table_hr[, n_tot_ids], table_survtime, table_hr[, -n_tot_ids]) |
334 |
# And then calculate column indices accordingly. |
|
335 | 5x |
hr_id <- length(n_tot_ids) + ncol(table_survtime) + match("hr", colvars_hr$vars[-n_tot_ids]) |
336 | 5x |
ci_id <- length(n_tot_ids) + ncol(table_survtime) + match("lcl", colvars_hr$vars[-n_tot_ids]) |
337 | 5x |
n_tot_ids <- seq_along(n_tot_ids) |
338 |
} |
|
339 | ||
340 | 6x |
structure( |
341 | 6x |
result, |
342 | 6x |
forest_header = paste0(rev(levels(df$survtime$arm)), "\nBetter"), |
343 | 6x |
col_x = hr_id, |
344 | 6x |
col_ci = ci_id, |
345 |
# Take the first one for scaling the symbol sizes in graph. |
|
346 | 6x |
col_symbol_size = n_tot_ids[1] |
347 |
) |
|
348 |
} |
|
349 | ||
350 |
#' Labels for Column Variables in Survival Duration by Subgroup Table |
|
351 |
#' |
|
352 |
#' @description `r lifecycle::badge("stable")` |
|
353 |
#' |
|
354 |
#' Internal function to check variables included in [tabulate_survival_subgroups()] and create column labels. |
|
355 |
#' |
|
356 |
#' @inheritParams tabulate_survival_subgroups |
|
357 |
#' @inheritParams argument_convention |
|
358 |
#' @param method (`character`)\cr p-value method for testing hazard ratio = 1. |
|
359 |
#' |
|
360 |
#' @return A `list` of variables and their labels to tabulate. |
|
361 |
#' |
|
362 |
#' @note At least one of `n_tot` and `n_tot_events` must be provided in `vars`. |
|
363 |
#' |
|
364 |
#' @export |
|
365 |
d_survival_subgroups_colvars <- function(vars, |
|
366 |
conf_level, |
|
367 |
method, |
|
368 |
time_unit = NULL) { |
|
369 | 15x |
checkmate::assert_character(vars) |
370 | 15x |
checkmate::assert_string(time_unit, null.ok = TRUE) |
371 | 15x |
checkmate::assert_subset(c("hr", "ci"), vars) |
372 | 15x |
checkmate::assert_true(any(c("n_tot", "n_tot_events") %in% vars)) |
373 | 15x |
checkmate::assert_subset( |
374 | 15x |
vars, |
375 | 15x |
c("n", "n_events", "median", "n_tot", "n_tot_events", "hr", "ci", "pval") |
376 |
) |
|
377 | ||
378 | 15x |
propcase_time_label <- if (!is.null(time_unit)) { |
379 | 14x |
paste0("Median (", time_unit, ")") |
380 |
} else { |
|
381 | 1x |
"Median" |
382 |
} |
|
383 | ||
384 | 15x |
varlabels <- c( |
385 | 15x |
n = "n", |
386 | 15x |
n_events = "Events", |
387 | 15x |
median = propcase_time_label, |
388 | 15x |
n_tot = "Total n", |
389 | 15x |
n_tot_events = "Total Events", |
390 | 15x |
hr = "Hazard Ratio", |
391 | 15x |
ci = paste0(100 * conf_level, "% Wald CI"), |
392 | 15x |
pval = method |
393 |
) |
|
394 | ||
395 | 15x |
colvars <- vars |
396 | ||
397 |
# The `lcl` variable is just a placeholder available in the analysis data, |
|
398 |
# it is not acutally used in the tabulation. |
|
399 |
# Variables used in the tabulation are lcl and ucl, see `a_survival_subgroups` for details. |
|
400 | 15x |
colvars[colvars == "ci"] <- "lcl" |
401 | ||
402 | 15x |
list( |
403 | 15x |
vars = colvars, |
404 | 15x |
labels = varlabels[vars] |
405 |
) |
|
406 |
} |
1 |
#' Summarize Variables in Columns |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' This analyze function uses the S3 generic function [s_summary()] to summarize different variables |
|
6 |
#' that are arranged in columns. Additional standard formatting arguments are available. It is a |
|
7 |
#' minimal wrapper for [rtables::analyze_colvars()]. The latter function is meant to add different |
|
8 |
#' analysis methods for each column variables as different rows. To have the analysis methods as |
|
9 |
#' column labels, please refer to [analyze_vars_in_cols()]. |
|
10 |
#' |
|
11 |
#' @inheritParams argument_convention |
|
12 |
#' @param ... arguments passed to `s_summary()`. |
|
13 |
#' @param .indent_mods (named `vector` of `integer`)\cr indent modifiers for the labels. Each element of the vector |
|
14 |
#' should be a name-value pair with name corresponding to a statistic specified in `.stats` and value the indentation |
|
15 |
#' for that statistic's row label. |
|
16 |
#' |
|
17 |
#' @return |
|
18 |
#' A layout object suitable for passing to further layouting functions, or to [rtables::build_table()]. |
|
19 |
#' Adding this function to an `rtable` layout will summarize the given variables, arrange the output |
|
20 |
#' in columns, and add it to the table layout. |
|
21 |
#' |
|
22 |
#' @seealso [rtables::split_cols_by_multivar()] and [`analyze_colvars_functions`]. |
|
23 |
#' |
|
24 |
#' @examples |
|
25 |
#' dta_test <- data.frame( |
|
26 |
#' USUBJID = rep(1:6, each = 3), |
|
27 |
#' PARAMCD = rep("lab", 6 * 3), |
|
28 |
#' AVISIT = rep(paste0("V", 1:3), 6), |
|
29 |
#' ARM = rep(LETTERS[1:3], rep(6, 3)), |
|
30 |
#' AVAL = c(9:1, rep(NA, 9)), |
|
31 |
#' CHG = c(1:9, rep(NA, 9)) |
|
32 |
#' ) |
|
33 |
#' |
|
34 |
#' ## Default output within a `rtables` pipeline. |
|
35 |
#' basic_table() %>% |
|
36 |
#' split_cols_by("ARM") %>% |
|
37 |
#' split_rows_by("AVISIT") %>% |
|
38 |
#' split_cols_by_multivar(vars = c("AVAL", "CHG")) %>% |
|
39 |
#' summarize_colvars() %>% |
|
40 |
#' build_table(dta_test) |
|
41 |
#' |
|
42 |
#' ## Selection of statistics, formats and labels also work. |
|
43 |
#' basic_table() %>% |
|
44 |
#' split_cols_by("ARM") %>% |
|
45 |
#' split_rows_by("AVISIT") %>% |
|
46 |
#' split_cols_by_multivar(vars = c("AVAL", "CHG")) %>% |
|
47 |
#' summarize_colvars( |
|
48 |
#' .stats = c("n", "mean_sd"), |
|
49 |
#' .formats = c("mean_sd" = "xx.x, xx.x"), |
|
50 |
#' .labels = c(n = "n", mean_sd = "Mean, SD") |
|
51 |
#' ) %>% |
|
52 |
#' build_table(dta_test) |
|
53 |
#' |
|
54 |
#' ## Use arguments interpreted by `s_summary`. |
|
55 |
#' basic_table() %>% |
|
56 |
#' split_cols_by("ARM") %>% |
|
57 |
#' split_rows_by("AVISIT") %>% |
|
58 |
#' split_cols_by_multivar(vars = c("AVAL", "CHG")) %>% |
|
59 |
#' summarize_colvars(na.rm = FALSE) %>% |
|
60 |
#' build_table(dta_test) |
|
61 |
#' |
|
62 |
#' @export |
|
63 |
summarize_colvars <- function(lyt, |
|
64 |
..., |
|
65 |
na_level = lifecycle::deprecated(), |
|
66 |
na_str = default_na_str(), |
|
67 |
.stats = c("n", "mean_sd", "median", "range", "count_fraction"), |
|
68 |
.formats = NULL, |
|
69 |
.labels = NULL, |
|
70 |
.indent_mods = NULL) { |
|
71 | 3x |
if (lifecycle::is_present(na_level)) { |
72 | ! |
lifecycle::deprecate_warn("0.9.1", "summarize_colvars(na_level)", "summarize_colvars(na_str)") |
73 | ! |
na_str <- na_level |
74 |
} |
|
75 | ||
76 | 3x |
extra_args <- list(.stats = .stats, na_str = na_str, ...) |
77 | 1x |
if (!is.null(.formats)) extra_args[[".formats"]] <- .formats |
78 | 1x |
if (!is.null(.labels)) extra_args[[".labels"]] <- .labels |
79 | 1x |
if (!is.null(.indent_mods)) extra_args[[".indent_mods"]] <- .indent_mods |
80 | ||
81 | 3x |
analyze_colvars( |
82 | 3x |
lyt, |
83 | 3x |
afun = a_summary, |
84 | 3x |
na_str = na_str, |
85 | 3x |
extra_args = extra_args |
86 |
) |
|
87 |
} |
1 |
#' Tabulate Binary Response by Subgroup |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Tabulate statistics such as response rate and odds ratio for population subgroups. |
|
6 |
#' |
|
7 |
#' @inheritParams extract_rsp_subgroups |
|
8 |
#' @inheritParams argument_convention |
|
9 |
#' |
|
10 |
#' @details These functions create a layout starting from a data frame which contains |
|
11 |
#' the required statistics. Tables typically used as part of forest plot. |
|
12 |
#' |
|
13 |
#' @seealso [extract_rsp_subgroups()] |
|
14 |
#' |
|
15 |
#' @examples |
|
16 |
#' library(dplyr) |
|
17 |
#' library(forcats) |
|
18 |
#' |
|
19 |
#' adrs <- tern_ex_adrs |
|
20 |
#' adrs_labels <- formatters::var_labels(adrs) |
|
21 |
#' |
|
22 |
#' adrs_f <- adrs %>% |
|
23 |
#' filter(PARAMCD == "BESRSPI") %>% |
|
24 |
#' filter(ARM %in% c("A: Drug X", "B: Placebo")) %>% |
|
25 |
#' droplevels() %>% |
|
26 |
#' mutate( |
|
27 |
#' # Reorder levels of factor to make the placebo group the reference arm. |
|
28 |
#' ARM = fct_relevel(ARM, "B: Placebo"), |
|
29 |
#' rsp = AVALC == "CR" |
|
30 |
#' ) |
|
31 |
#' formatters::var_labels(adrs_f) <- c(adrs_labels, "Response") |
|
32 |
#' |
|
33 |
#' # Unstratified analysis. |
|
34 |
#' df <- extract_rsp_subgroups( |
|
35 |
#' variables = list(rsp = "rsp", arm = "ARM", subgroups = c("SEX", "BMRKR2")), |
|
36 |
#' data = adrs_f |
|
37 |
#' ) |
|
38 |
#' df |
|
39 |
#' |
|
40 |
#' # Stratified analysis. |
|
41 |
#' df_strat <- extract_rsp_subgroups( |
|
42 |
#' variables = list(rsp = "rsp", arm = "ARM", subgroups = c("SEX", "BMRKR2"), strat = "STRATA1"), |
|
43 |
#' data = adrs_f |
|
44 |
#' ) |
|
45 |
#' df_strat |
|
46 |
#' |
|
47 |
#' # Grouping of the BMRKR2 levels. |
|
48 |
#' df_grouped <- extract_rsp_subgroups( |
|
49 |
#' variables = list(rsp = "rsp", arm = "ARM", subgroups = c("SEX", "BMRKR2")), |
|
50 |
#' data = adrs_f, |
|
51 |
#' groups_lists = list( |
|
52 |
#' BMRKR2 = list( |
|
53 |
#' "low" = "LOW", |
|
54 |
#' "low/medium" = c("LOW", "MEDIUM"), |
|
55 |
#' "low/medium/high" = c("LOW", "MEDIUM", "HIGH") |
|
56 |
#' ) |
|
57 |
#' ) |
|
58 |
#' ) |
|
59 |
#' df_grouped |
|
60 |
#' |
|
61 |
#' @name response_subgroups |
|
62 |
#' @order 1 |
|
63 |
NULL |
|
64 | ||
65 |
#' Prepares Response Data for Population Subgroups in Data Frames |
|
66 |
#' |
|
67 |
#' @description `r lifecycle::badge("stable")` |
|
68 |
#' |
|
69 |
#' Prepares response rates and odds ratios for population subgroups in data frames. Simple wrapper |
|
70 |
#' for [h_odds_ratio_subgroups_df()] and [h_proportion_subgroups_df()]. Result is a list of two |
|
71 |
#' `data.frames`: `prop` and `or`. `variables` corresponds to the names of variables found in `data`, |
|
72 |
#' passed as a named `list` and requires elements `rsp`, `arm` and optionally `subgroups` and `strat`. |
|
73 |
#' `groups_lists` optionally specifies groupings for `subgroups` variables. |
|
74 |
#' |
|
75 |
#' @inheritParams argument_convention |
|
76 |
#' @inheritParams response_subgroups |
|
77 |
#' @param label_all (`string`)\cr label for the total population analysis. |
|
78 |
#' |
|
79 |
#' @return A named list of two elements: |
|
80 |
#' * `prop`: A `data.frame` containing columns `arm`, `n`, `n_rsp`, `prop`, `subgroup`, `var`, |
|
81 |
#' `var_label`, and `row_type`. |
|
82 |
#' * `or`: A `data.frame` containing columns `arm`, `n_tot`, `or`, `lcl`, `ucl`, `conf_level`, |
|
83 |
#' `subgroup`, `var`, `var_label`, and `row_type`. |
|
84 |
#' |
|
85 |
#' @seealso [response_subgroups] |
|
86 |
#' |
|
87 |
#' @export |
|
88 |
extract_rsp_subgroups <- function(variables, |
|
89 |
data, |
|
90 |
groups_lists = list(), |
|
91 |
conf_level = 0.95, |
|
92 |
method = NULL, |
|
93 |
label_all = "All Patients") { |
|
94 | 11x |
df_prop <- h_proportion_subgroups_df( |
95 | 11x |
variables, |
96 | 11x |
data, |
97 | 11x |
groups_lists = groups_lists, |
98 | 11x |
label_all = label_all |
99 |
) |
|
100 | 11x |
df_or <- h_odds_ratio_subgroups_df( |
101 | 11x |
variables, |
102 | 11x |
data, |
103 | 11x |
groups_lists = groups_lists, |
104 | 11x |
conf_level = conf_level, |
105 | 11x |
method = method, |
106 | 11x |
label_all = label_all |
107 |
) |
|
108 | ||
109 | 11x |
list(prop = df_prop, or = df_or) |
110 |
} |
|
111 | ||
112 |
#' @describeIn response_subgroups Formatted analysis function which is used as `afun` in `tabulate_rsp_subgroups()`. |
|
113 |
#' |
|
114 |
#' @return |
|
115 |
#' * `a_response_subgroups()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
116 |
#' |
|
117 |
#' @keywords internal |
|
118 |
a_response_subgroups <- function(.formats = list( |
|
119 |
n = "xx", # nolint start |
|
120 |
n_rsp = "xx", |
|
121 |
prop = "xx.x%", |
|
122 |
n_tot = "xx", |
|
123 |
or = list(format_extreme_values(2L)), |
|
124 |
ci = list(format_extreme_values_ci(2L)), |
|
125 |
pval = "x.xxxx | (<0.0001)" # nolint end |
|
126 |
), |
|
127 |
na_str = default_na_str()) { |
|
128 | 16x |
checkmate::assert_list(.formats) |
129 | 16x |
checkmate::assert_subset( |
130 | 16x |
names(.formats), |
131 | 16x |
c("n", "n_rsp", "prop", "n_tot", "or", "ci", "pval") |
132 |
) |
|
133 | ||
134 | 16x |
afun_lst <- Map( |
135 | 16x |
function(stat, fmt, na_str) { |
136 | 107x |
if (stat == "ci") { |
137 | 15x |
function(df, labelstr = "", ...) { |
138 | 33x |
in_rows( |
139 | 33x |
.list = combine_vectors(df$lcl, df$ucl), |
140 | 33x |
.labels = as.character(df$subgroup), |
141 | 33x |
.formats = fmt, |
142 | 33x |
.format_na_strs = na_str |
143 |
) |
|
144 |
} |
|
145 |
} else { |
|
146 | 92x |
function(df, labelstr = "", ...) { |
147 | 193x |
in_rows( |
148 | 193x |
.list = as.list(df[[stat]]), |
149 | 193x |
.labels = as.character(df$subgroup), |
150 | 193x |
.formats = fmt, |
151 | 193x |
.format_na_strs = na_str |
152 |
) |
|
153 |
} |
|
154 |
} |
|
155 |
}, |
|
156 | 16x |
stat = names(.formats), |
157 | 16x |
fmt = .formats, |
158 | 16x |
na_str = na_str |
159 |
) |
|
160 | ||
161 | 16x |
afun_lst |
162 |
} |
|
163 | ||
164 |
#' @describeIn response_subgroups Table-creating function which creates a table |
|
165 |
#' summarizing binary response by subgroup. This function is a wrapper for [rtables::analyze_colvars()] |
|
166 |
#' and [rtables::summarize_row_groups()]. |
|
167 |
#' |
|
168 |
#' @param df (`list`)\cr of data frames containing all analysis variables. List should be |
|
169 |
#' created using [extract_rsp_subgroups()]. |
|
170 |
#' @param vars (`character`)\cr the names of statistics to be reported among: |
|
171 |
#' * `n`: Total number of observations per group. |
|
172 |
#' * `n_rsp`: Number of responders per group. |
|
173 |
#' * `prop`: Proportion of responders. |
|
174 |
#' * `n_tot`: Total number of observations. |
|
175 |
#' * `or`: Odds ratio. |
|
176 |
#' * `ci` : Confidence interval of odds ratio. |
|
177 |
#' * `pval`: p-value of the effect. |
|
178 |
#' Note, the statistics `n_tot`, `or` and `ci` are required. |
|
179 |
#' |
|
180 |
#' @return An `rtables` table summarizing binary response by subgroup. |
|
181 |
#' |
|
182 |
#' @examples |
|
183 |
#' ## Table with default columns. |
|
184 |
#' basic_table() %>% |
|
185 |
#' tabulate_rsp_subgroups(df) |
|
186 |
#' |
|
187 |
#' ## Table with selected columns. |
|
188 |
#' basic_table() %>% |
|
189 |
#' tabulate_rsp_subgroups( |
|
190 |
#' df = df, |
|
191 |
#' vars = c("n_tot", "n", "n_rsp", "prop", "or", "ci") |
|
192 |
#' ) |
|
193 |
#' |
|
194 |
#' @export |
|
195 |
#' @order 2 |
|
196 |
tabulate_rsp_subgroups <- function(lyt, |
|
197 |
df, |
|
198 |
vars = c("n_tot", "n", "prop", "or", "ci"), |
|
199 |
groups_lists = list(), |
|
200 |
label_all = "All Patients", |
|
201 |
na_str = default_na_str()) { |
|
202 | 7x |
conf_level <- df$or$conf_level[1] |
203 | 7x |
method <- if ("pval_label" %in% names(df$or)) { |
204 | 5x |
df$or$pval_label[1] |
205 |
} else { |
|
206 | 2x |
NULL |
207 |
} |
|
208 | ||
209 | 7x |
extra_args <- list(groups_lists = groups_lists, conf_level = conf_level, method = method, label_all = label_all) |
210 | ||
211 | 7x |
afun_lst <- a_response_subgroups(na_str = na_str) |
212 | 7x |
colvars <- d_rsp_subgroups_colvars(vars, conf_level = conf_level, method = method) |
213 | ||
214 | 7x |
colvars_prop <- list( |
215 | 7x |
vars = colvars$vars[names(colvars$labels) %in% c("n", "prop", "n_rsp")], |
216 | 7x |
labels = colvars$labels[names(colvars$labels) %in% c("n", "prop", "n_rsp")] |
217 |
) |
|
218 | 7x |
colvars_or <- list( |
219 | 7x |
vars = colvars$vars[names(colvars$labels) %in% c("n_tot", "or", "ci", "pval")], |
220 | 7x |
labels = colvars$labels[names(colvars$labels) %in% c("n_tot", "or", "ci", "pval")] |
221 |
) |
|
222 | ||
223 |
# Columns from table_prop are optional. |
|
224 | 7x |
if (length(colvars_prop$vars) > 0) { |
225 | 7x |
lyt_prop <- split_cols_by(lyt = lyt, var = "arm") |
226 | 7x |
lyt_prop <- split_cols_by_multivar( |
227 | 7x |
lyt = lyt_prop, |
228 | 7x |
vars = colvars_prop$vars, |
229 | 7x |
varlabels = colvars_prop$labels |
230 |
) |
|
231 | ||
232 |
# "All Patients" row |
|
233 | 7x |
lyt_prop <- split_rows_by( |
234 | 7x |
lyt = lyt_prop, |
235 | 7x |
var = "row_type", |
236 | 7x |
split_fun = keep_split_levels("content"), |
237 | 7x |
nested = FALSE, |
238 | 7x |
child_labels = "hidden" |
239 |
) |
|
240 | 7x |
lyt_prop <- analyze_colvars( |
241 | 7x |
lyt = lyt_prop, |
242 | 7x |
afun = afun_lst[names(colvars_prop$labels)], |
243 | 7x |
na_str = na_str, |
244 | 7x |
extra_args = extra_args |
245 |
) |
|
246 | ||
247 | 7x |
if ("analysis" %in% df$prop$row_type) { |
248 | 6x |
lyt_prop <- split_rows_by( |
249 | 6x |
lyt = lyt_prop, |
250 | 6x |
var = "row_type", |
251 | 6x |
split_fun = keep_split_levels("analysis"), |
252 | 6x |
nested = FALSE, |
253 | 6x |
child_labels = "hidden" |
254 |
) |
|
255 | 6x |
lyt_prop <- split_rows_by(lyt = lyt_prop, var = "var_label", nested = TRUE) |
256 | 6x |
lyt_prop <- analyze_colvars( |
257 | 6x |
lyt = lyt_prop, |
258 | 6x |
afun = afun_lst[names(colvars_prop$labels)], |
259 | 6x |
na_str = na_str, |
260 | 6x |
inclNAs = TRUE, |
261 | 6x |
extra_args = extra_args |
262 |
) |
|
263 |
} |
|
264 | ||
265 | 7x |
table_prop <- build_table(lyt_prop, df = df$prop) |
266 |
} else { |
|
267 | ! |
table_prop <- NULL |
268 |
} |
|
269 | ||
270 |
# Columns "n_tot", "or", "ci" in table_or are required. |
|
271 | 7x |
lyt_or <- split_cols_by(lyt = lyt, var = "arm") |
272 | 7x |
lyt_or <- split_cols_by_multivar( |
273 | 7x |
lyt = lyt_or, |
274 | 7x |
vars = colvars_or$vars, |
275 | 7x |
varlabels = colvars_or$labels |
276 |
) |
|
277 | ||
278 |
# "All Patients" row |
|
279 | 7x |
lyt_or <- split_rows_by( |
280 | 7x |
lyt = lyt_or, |
281 | 7x |
var = "row_type", |
282 | 7x |
split_fun = keep_split_levels("content"), |
283 | 7x |
nested = FALSE, |
284 | 7x |
child_labels = "hidden" |
285 |
) |
|
286 | 7x |
lyt_or <- analyze_colvars( |
287 | 7x |
lyt = lyt_or, |
288 | 7x |
afun = afun_lst[names(colvars_or$labels)], |
289 | 7x |
na_str = na_str, |
290 | 7x |
extra_args = extra_args |
291 |
) %>% |
|
292 | 7x |
append_topleft("Baseline Risk Factors") |
293 | ||
294 | 7x |
if ("analysis" %in% df$or$row_type) { |
295 | 6x |
lyt_or <- split_rows_by( |
296 | 6x |
lyt = lyt_or, |
297 | 6x |
var = "row_type", |
298 | 6x |
split_fun = keep_split_levels("analysis"), |
299 | 6x |
nested = FALSE, |
300 | 6x |
child_labels = "hidden" |
301 |
) |
|
302 | 6x |
lyt_or <- split_rows_by(lyt = lyt_or, var = "var_label", nested = TRUE) |
303 | 6x |
lyt_or <- analyze_colvars( |
304 | 6x |
lyt = lyt_or, |
305 | 6x |
afun = afun_lst[names(colvars_or$labels)], |
306 | 6x |
na_str = na_str, |
307 | 6x |
inclNAs = TRUE, |
308 | 6x |
extra_args = extra_args |
309 |
) |
|
310 |
} |
|
311 | 7x |
table_or <- build_table(lyt_or, df = df$or) |
312 | ||
313 | 7x |
n_tot_id <- match("n_tot", colvars_or$vars) |
314 | 7x |
if (is.null(table_prop)) { |
315 | ! |
result <- table_or |
316 | ! |
or_id <- match("or", colvars_or$vars) |
317 | ! |
ci_id <- match("lcl", colvars_or$vars) |
318 |
} else { |
|
319 | 7x |
result <- cbind_rtables(table_or[, n_tot_id], table_prop, table_or[, -n_tot_id]) |
320 | 7x |
or_id <- 1L + ncol(table_prop) + match("or", colvars_or$vars[-n_tot_id]) |
321 | 7x |
ci_id <- 1L + ncol(table_prop) + match("lcl", colvars_or$vars[-n_tot_id]) |
322 | 7x |
n_tot_id <- 1L |
323 |
} |
|
324 | 7x |
structure( |
325 | 7x |
result, |
326 | 7x |
forest_header = paste0(levels(df$prop$arm), "\nBetter"), |
327 | 7x |
col_x = or_id, |
328 | 7x |
col_ci = ci_id, |
329 | 7x |
col_symbol_size = n_tot_id |
330 |
) |
|
331 |
} |
|
332 | ||
333 |
#' Labels for Column Variables in Binary Response by Subgroup Table |
|
334 |
#' |
|
335 |
#' @description `r lifecycle::badge("stable")` |
|
336 |
#' |
|
337 |
#' Internal function to check variables included in [tabulate_rsp_subgroups()] and create column labels. |
|
338 |
#' |
|
339 |
#' @inheritParams argument_convention |
|
340 |
#' @inheritParams tabulate_rsp_subgroups |
|
341 |
#' |
|
342 |
#' @return A `list` of variables to tabulate and their labels. |
|
343 |
#' |
|
344 |
#' @export |
|
345 |
d_rsp_subgroups_colvars <- function(vars, |
|
346 |
conf_level = NULL, |
|
347 |
method = NULL) { |
|
348 | 16x |
checkmate::assert_character(vars) |
349 | 16x |
checkmate::assert_subset(c("n_tot", "or", "ci"), vars) |
350 | 16x |
checkmate::assert_subset( |
351 | 16x |
vars, |
352 | 16x |
c("n", "n_rsp", "prop", "n_tot", "or", "ci", "pval") |
353 |
) |
|
354 | ||
355 | 16x |
varlabels <- c( |
356 | 16x |
n = "n", |
357 | 16x |
n_rsp = "Responders", |
358 | 16x |
prop = "Response (%)", |
359 | 16x |
n_tot = "Total n", |
360 | 16x |
or = "Odds Ratio" |
361 |
) |
|
362 | 16x |
colvars <- vars |
363 | ||
364 | 16x |
if ("ci" %in% colvars) { |
365 | 16x |
checkmate::assert_false(is.null(conf_level)) |
366 | ||
367 | 16x |
varlabels <- c( |
368 | 16x |
varlabels, |
369 | 16x |
ci = paste0(100 * conf_level, "% CI") |
370 |
) |
|
371 | ||
372 |
# The `lcl`` variable is just a placeholder available in the analysis data, |
|
373 |
# it is not acutally used in the tabulation. |
|
374 |
# Variables used in the tabulation are lcl and ucl, see `a_response_subgroups` for details. |
|
375 | 16x |
colvars[colvars == "ci"] <- "lcl" |
376 |
} |
|
377 | ||
378 | 16x |
if ("pval" %in% colvars) { |
379 | 13x |
varlabels <- c( |
380 | 13x |
varlabels, |
381 | 13x |
pval = method |
382 |
) |
|
383 |
} |
|
384 | ||
385 | 16x |
list( |
386 | 16x |
vars = colvars, |
387 | 16x |
labels = varlabels[vars] |
388 |
) |
|
389 |
} |
1 |
#' Control Function for Descriptive Statistics |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Sets a list of parameters for summaries of descriptive statistics. Typically used internally to specify |
|
6 |
#' details for [s_summary()]. This function family is mainly used by [analyze_vars()]. |
|
7 |
#' |
|
8 |
#' @inheritParams argument_convention |
|
9 |
#' @param quantiles (`numeric`)\cr of length two to specify the quantiles to calculate. |
|
10 |
#' @param quantile_type (`numeric`)\cr between 1 and 9 selecting quantile algorithms to be used. |
|
11 |
#' Default is set to 2 as this matches the default quantile algorithm in SAS `proc univariate` set by `QNTLDEF=5`. |
|
12 |
#' This differs from R's default. See more about `type` in [stats::quantile()]. |
|
13 |
#' @param test_mean (`numeric`)\cr to test against the mean under the null hypothesis when calculating p-value. |
|
14 |
#' |
|
15 |
#' @note Deprecation cycle started for `control_summarize_vars` as it is going to renamed into |
|
16 |
#' `control_analyze_vars`. Intention is to reflect better the core underlying `rtables` |
|
17 |
#' functions; in this case [analyze_vars()] wraps [rtables::analyze()]. |
|
18 |
#' |
|
19 |
#' @return A list of components with the same names as the arguments. |
|
20 |
#' |
|
21 |
#' @export control_analyze_vars control_summarize_vars |
|
22 |
#' @aliases control_summarize_vars |
|
23 |
control_analyze_vars <- function(conf_level = 0.95, |
|
24 |
quantiles = c(0.25, 0.75), |
|
25 |
quantile_type = 2, |
|
26 |
test_mean = 0) { |
|
27 | 296x |
checkmate::assert_vector(quantiles, len = 2) |
28 | 296x |
checkmate::assert_int(quantile_type, lower = 1, upper = 9) |
29 | 296x |
checkmate::assert_numeric(test_mean) |
30 | 296x |
lapply(quantiles, assert_proportion_value) |
31 | 295x |
assert_proportion_value(conf_level) |
32 | 294x |
list(conf_level = conf_level, quantiles = quantiles, quantile_type = quantile_type, test_mean = test_mean) |
33 |
} |
|
34 | ||
35 |
control_summarize_vars <- control_analyze_vars |
|
36 | ||
37 | ||
38 |
#' Analyze Variables |
|
39 |
#' |
|
40 |
#' @description `r lifecycle::badge("stable")` |
|
41 |
#' |
|
42 |
#' The analyze function [analyze_vars()] generates a summary of one or more variables, using the S3 generic function |
|
43 |
#' [s_summary()] to calculate a list of summary statistics. A list of all available statistics for numeric |
|
44 |
#' variables can be viewed by running `get_stats("analyze_vars_numeric")` and for non-numeric variables by running |
|
45 |
#' `get_stats("analyze_vars_counts")`. Use the `.stats` parameter to specify the statistics to include in your output |
|
46 |
#' summary table. |
|
47 |
#' |
|
48 |
#' @details |
|
49 |
#' **Automatic digit formatting:** The number of digits to display can be automatically determined from the analyzed |
|
50 |
#' variable(s) (`vars`) for certain statistics by setting the statistic format to `"auto"` in `.formats`. |
|
51 |
#' This utilizes the [format_auto()] formatting function. Note that only data for the current row & variable (for all |
|
52 |
#' columns) will be considered (`.df_row[[.var]]`, see [`rtables::additional_fun_params`]) and not the whole dataset. |
|
53 |
#' |
|
54 |
#' @note |
|
55 |
#' * Deprecation cycle started for `summarize_vars` which has been renamed to `analyze_vars`. This renaming is intended |
|
56 |
#' to better reflect its core underlying `rtables` functions - in this case [rtables::analyze()]. |
|
57 |
#' |
|
58 |
#' @inheritParams argument_convention |
|
59 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("analyze_vars_numeric")` to see |
|
60 |
#' statistics available for numeric variables, and `get_stats("analyze_vars_counts")` for statistics available |
|
61 |
#' for non-numeric variables. |
|
62 |
#' |
|
63 |
#' @name analyze_variables |
|
64 |
#' @order 1 |
|
65 |
NULL |
|
66 | ||
67 |
#' @describeIn analyze_variables S3 generic function to produces a variable summary. |
|
68 |
#' |
|
69 |
#' @return |
|
70 |
#' * `s_summary()` returns different statistics depending on the class of `x`. |
|
71 |
#' |
|
72 |
#' @export |
|
73 |
s_summary <- function(x, |
|
74 |
na.rm = TRUE, # nolint |
|
75 |
denom, |
|
76 |
.N_row, # nolint |
|
77 |
.N_col, # nolint |
|
78 |
.var, |
|
79 |
...) { |
|
80 | 731x |
checkmate::assert_flag(na.rm) |
81 | 731x |
UseMethod("s_summary", x) |
82 |
} |
|
83 | ||
84 |
#' @describeIn analyze_variables Method for `numeric` class. |
|
85 |
#' |
|
86 |
#' @param control (`list`)\cr parameters for descriptive statistics details, specified by using |
|
87 |
#' the helper function [control_analyze_vars()]. Some possible parameter options are: |
|
88 |
#' * `conf_level` (`proportion`)\cr confidence level of the interval for mean and median. |
|
89 |
#' * `quantiles` (`numeric`)\cr vector of length two to specify the quantiles. |
|
90 |
#' * `quantile_type` (`numeric`)\cr between 1 and 9 selecting quantile algorithms to be used. |
|
91 |
#' See more about `type` in [stats::quantile()]. |
|
92 |
#' * `test_mean` (`numeric`)\cr value to test against the mean under the null hypothesis when calculating p-value. |
|
93 |
#' |
|
94 |
#' @return |
|
95 |
#' * If `x` is of class `numeric`, returns a `list` with the following named `numeric` items: |
|
96 |
#' * `n`: The [length()] of `x`. |
|
97 |
#' * `sum`: The [sum()] of `x`. |
|
98 |
#' * `mean`: The [mean()] of `x`. |
|
99 |
#' * `sd`: The [stats::sd()] of `x`. |
|
100 |
#' * `se`: The standard error of `x` mean, i.e.: (`sd(x) / sqrt(length(x))`). |
|
101 |
#' * `mean_sd`: The [mean()] and [stats::sd()] of `x`. |
|
102 |
#' * `mean_se`: The [mean()] of `x` and its standard error (see above). |
|
103 |
#' * `mean_ci`: The CI for the mean of `x` (from [stat_mean_ci()]). |
|
104 |
#' * `mean_sei`: The SE interval for the mean of `x`, i.e.: ([mean()] -/+ [stats::sd()] / [sqrt()]). |
|
105 |
#' * `mean_sdi`: The SD interval for the mean of `x`, i.e.: ([mean()] -/+ [stats::sd()]). |
|
106 |
#' * `mean_pval`: The two-sided p-value of the mean of `x` (from [stat_mean_pval()]). |
|
107 |
#' * `median`: The [stats::median()] of `x`. |
|
108 |
#' * `mad`: The median absolute deviation of `x`, i.e.: ([stats::median()] of `xc`, |
|
109 |
#' where `xc` = `x` - [stats::median()]). |
|
110 |
#' * `median_ci`: The CI for the median of `x` (from [stat_median_ci()]). |
|
111 |
#' * `quantiles`: Two sample quantiles of `x` (from [stats::quantile()]). |
|
112 |
#' * `iqr`: The [stats::IQR()] of `x`. |
|
113 |
#' * `range`: The [range_noinf()] of `x`. |
|
114 |
#' * `min`: The [max()] of `x`. |
|
115 |
#' * `max`: The [min()] of `x`. |
|
116 |
#' * `median_range`: The [median()] and [range_noinf()] of `x`. |
|
117 |
#' * `cv`: The coefficient of variation of `x`, i.e.: ([stats::sd()] / [mean()] * 100). |
|
118 |
#' * `geom_mean`: The geometric mean of `x`, i.e.: (`exp(mean(log(x)))`). |
|
119 |
#' * `geom_cv`: The geometric coefficient of variation of `x`, i.e.: (`sqrt(exp(sd(log(x)) ^ 2) - 1) * 100`). |
|
120 |
#' |
|
121 |
#' @note |
|
122 |
#' * If `x` is an empty vector, `NA` is returned. This is the expected feature so as to return `rcell` content in |
|
123 |
#' `rtables` when the intersection of a column and a row delimits an empty data selection. |
|
124 |
#' * When the `mean` function is applied to an empty vector, `NA` will be returned instead of `NaN`, the latter |
|
125 |
#' being standard behavior in R. |
|
126 |
#' |
|
127 |
#' @method s_summary numeric |
|
128 |
#' |
|
129 |
#' @examples |
|
130 |
#' # `s_summary.numeric` |
|
131 |
#' |
|
132 |
#' ## Basic usage: empty numeric returns NA-filled items. |
|
133 |
#' s_summary(numeric()) |
|
134 |
#' |
|
135 |
#' ## Management of NA values. |
|
136 |
#' x <- c(NA_real_, 1) |
|
137 |
#' s_summary(x, na.rm = TRUE) |
|
138 |
#' s_summary(x, na.rm = FALSE) |
|
139 |
#' |
|
140 |
#' x <- c(NA_real_, 1, 2) |
|
141 |
#' s_summary(x, stats = NULL) |
|
142 |
#' |
|
143 |
#' ## Benefits in `rtables` contructions: |
|
144 |
#' require(rtables) |
|
145 |
#' dta_test <- data.frame( |
|
146 |
#' Group = rep(LETTERS[1:3], each = 2), |
|
147 |
#' sub_group = rep(letters[1:2], each = 3), |
|
148 |
#' x = 1:6 |
|
149 |
#' ) |
|
150 |
#' |
|
151 |
#' ## The summary obtained in with `rtables`: |
|
152 |
#' basic_table() %>% |
|
153 |
#' split_cols_by(var = "Group") %>% |
|
154 |
#' split_rows_by(var = "sub_group") %>% |
|
155 |
#' analyze(vars = "x", afun = s_summary) %>% |
|
156 |
#' build_table(df = dta_test) |
|
157 |
#' |
|
158 |
#' ## By comparison with `lapply`: |
|
159 |
#' X <- split(dta_test, f = with(dta_test, interaction(Group, sub_group))) |
|
160 |
#' lapply(X, function(x) s_summary(x$x)) |
|
161 |
#' |
|
162 |
#' @export |
|
163 |
s_summary.numeric <- function(x, |
|
164 |
na.rm = TRUE, # nolint |
|
165 |
denom, |
|
166 |
.N_row, # nolint |
|
167 |
.N_col, # nolint |
|
168 |
.var, |
|
169 |
control = control_analyze_vars(), |
|
170 |
...) { |
|
171 | 359x |
checkmate::assert_numeric(x) |
172 | ||
173 | 359x |
if (na.rm) { |
174 | 358x |
x <- x[!is.na(x)] |
175 |
} |
|
176 | ||
177 | 359x |
y <- list() |
178 | ||
179 | 359x |
y$n <- c("n" = length(x)) |
180 | ||
181 | 359x |
y$sum <- c("sum" = ifelse(length(x) == 0, NA_real_, sum(x, na.rm = FALSE))) |
182 | ||
183 | 359x |
y$mean <- c("mean" = ifelse(length(x) == 0, NA_real_, mean(x, na.rm = FALSE))) |
184 | ||
185 | 359x |
y$sd <- c("sd" = stats::sd(x, na.rm = FALSE)) |
186 | ||
187 | 359x |
y$se <- c("se" = stats::sd(x, na.rm = FALSE) / sqrt(length(stats::na.omit(x)))) |
188 | ||
189 | 359x |
y$mean_sd <- c(y$mean, "sd" = stats::sd(x, na.rm = FALSE)) |
190 | ||
191 | 359x |
y$mean_se <- c(y$mean, y$se) |
192 | ||
193 | 359x |
mean_ci <- stat_mean_ci(x, conf_level = control$conf_level, na.rm = FALSE, gg_helper = FALSE) |
194 | 359x |
y$mean_ci <- formatters::with_label(mean_ci, paste("Mean", f_conf_level(control$conf_level))) |
195 | ||
196 | 359x |
mean_sei <- y$mean[[1]] + c(-1, 1) * stats::sd(x, na.rm = FALSE) / sqrt(y$n) |
197 | 359x |
names(mean_sei) <- c("mean_sei_lwr", "mean_sei_upr") |
198 | 359x |
y$mean_sei <- formatters::with_label(mean_sei, "Mean -/+ 1xSE") |
199 | ||
200 | 359x |
mean_sdi <- y$mean[[1]] + c(-1, 1) * stats::sd(x, na.rm = FALSE) |
201 | 359x |
names(mean_sdi) <- c("mean_sdi_lwr", "mean_sdi_upr") |
202 | 359x |
y$mean_sdi <- formatters::with_label(mean_sdi, "Mean -/+ 1xSD") |
203 | ||
204 | 359x |
mean_pval <- stat_mean_pval(x, test_mean = control$test_mean, na.rm = FALSE, n_min = 2) |
205 | 359x |
y$mean_pval <- formatters::with_label(mean_pval, paste("Mean", f_pval(control$test_mean))) |
206 | ||
207 | 359x |
y$median <- c("median" = stats::median(x, na.rm = FALSE)) |
208 | ||
209 | 359x |
y$mad <- c("mad" = stats::median(x - y$median, na.rm = FALSE)) |
210 | ||
211 | 359x |
median_ci <- stat_median_ci(x, conf_level = control$conf_level, na.rm = FALSE, gg_helper = FALSE) |
212 | 359x |
y$median_ci <- formatters::with_label(median_ci, paste("Median", f_conf_level(control$conf_level))) |
213 | ||
214 | 359x |
q <- control$quantiles |
215 | 359x |
if (any(is.na(x))) { |
216 | 1x |
qnts <- rep(NA_real_, length(q)) |
217 |
} else { |
|
218 | 358x |
qnts <- stats::quantile(x, probs = q, type = control$quantile_type, na.rm = FALSE) |
219 |
} |
|
220 | 359x |
names(qnts) <- paste("quantile", q, sep = "_") |
221 | 359x |
y$quantiles <- formatters::with_label(qnts, paste0(paste(paste0(q * 100, "%"), collapse = " and "), "-ile")) |
222 | ||
223 | 359x |
y$iqr <- c("iqr" = ifelse( |
224 | 359x |
any(is.na(x)), |
225 | 359x |
NA_real_, |
226 | 359x |
stats::IQR(x, na.rm = FALSE, type = control$quantile_type) |
227 |
)) |
|
228 | ||
229 | 359x |
y$range <- stats::setNames(range_noinf(x, na.rm = FALSE), c("min", "max")) |
230 | 359x |
y$min <- y$range[1] |
231 | 359x |
y$max <- y$range[2] |
232 | ||
233 | 359x |
y$median_range <- formatters::with_label(c(y$median, y$range), "Median (Min - Max)") |
234 | ||
235 | 359x |
y$cv <- c("cv" = unname(y$sd) / unname(y$mean) * 100) |
236 | ||
237 |
# Convert negative values to NA for log calculation. |
|
238 | 359x |
x_no_negative_vals <- x |
239 | 359x |
x_no_negative_vals[x_no_negative_vals <= 0] <- NA |
240 | 359x |
y$geom_mean <- c("geom_mean" = exp(mean(log(x_no_negative_vals), na.rm = FALSE))) |
241 | 359x |
geom_mean_ci <- stat_mean_ci(x, conf_level = control$conf_level, na.rm = FALSE, gg_helper = FALSE, geom_mean = TRUE) |
242 | 359x |
y$geom_mean_ci <- formatters::with_label(geom_mean_ci, paste("Geometric Mean", f_conf_level(control$conf_level))) |
243 | ||
244 | 359x |
y$geom_cv <- c("geom_cv" = sqrt(exp(stats::sd(log(x_no_negative_vals), na.rm = FALSE) ^ 2) - 1) * 100) # styler: off |
245 | ||
246 | 359x |
y |
247 |
} |
|
248 | ||
249 |
#' @describeIn analyze_variables Method for `factor` class. |
|
250 |
#' |
|
251 |
#' @param denom (`string`)\cr choice of denominator for factor proportions. Options are: |
|
252 |
#' * `n`: number of values in this row and column intersection. |
|
253 |
#' * `N_row`: total number of values in this row across columns. |
|
254 |
#' * `N_col`: total number of values in this column across rows. |
|
255 |
#' |
|
256 |
#' @return |
|
257 |
#' * If `x` is of class `factor` or converted from `character`, returns a `list` with named `numeric` items: |
|
258 |
#' * `n`: The [length()] of `x`. |
|
259 |
#' * `count`: A list with the number of cases for each level of the factor `x`. |
|
260 |
#' * `count_fraction`: Similar to `count` but also includes the proportion of cases for each level of the |
|
261 |
#' factor `x` relative to the denominator, or `NA` if the denominator is zero. |
|
262 |
#' |
|
263 |
#' @note |
|
264 |
#' * If `x` is an empty `factor`, a list is still returned for `counts` with one element |
|
265 |
#' per factor level. If there are no levels in `x`, the function fails. |
|
266 |
#' * If factor variables contain `NA`, these `NA` values are excluded by default. To include `NA` values |
|
267 |
#' set `na.rm = FALSE` and missing values will be displayed as an `NA` level. Alternatively, an explicit |
|
268 |
#' factor level can be defined for `NA` values during pre-processing via [df_explicit_na()] - the |
|
269 |
#' default `na_level` (`"<Missing>"`) will also be excluded when `na.rm` is set to `TRUE`. |
|
270 |
#' |
|
271 |
#' @method s_summary factor |
|
272 |
#' |
|
273 |
#' @examples |
|
274 |
#' # `s_summary.factor` |
|
275 |
#' |
|
276 |
#' ## Basic usage: |
|
277 |
#' s_summary(factor(c("a", "a", "b", "c", "a"))) |
|
278 |
#' |
|
279 |
#' # Empty factor returns zero-filled items. |
|
280 |
#' s_summary(factor(levels = c("a", "b", "c"))) |
|
281 |
#' |
|
282 |
#' ## Management of NA values. |
|
283 |
#' x <- factor(c(NA, "Female")) |
|
284 |
#' x <- explicit_na(x) |
|
285 |
#' s_summary(x, na.rm = TRUE) |
|
286 |
#' s_summary(x, na.rm = FALSE) |
|
287 |
#' |
|
288 |
#' ## Different denominators. |
|
289 |
#' x <- factor(c("a", "a", "b", "c", "a")) |
|
290 |
#' s_summary(x, denom = "N_row", .N_row = 10L) |
|
291 |
#' s_summary(x, denom = "N_col", .N_col = 20L) |
|
292 |
#' |
|
293 |
#' @export |
|
294 |
s_summary.factor <- function(x, |
|
295 |
na.rm = TRUE, # nolint |
|
296 |
denom = c("n", "N_row", "N_col"), |
|
297 |
.N_row, # nolint |
|
298 |
.N_col, # nolint |
|
299 |
...) { |
|
300 | 280x |
assert_valid_factor(x) |
301 | 277x |
denom <- match.arg(denom) |
302 | ||
303 | 277x |
if (na.rm) { |
304 | 273x |
x <- x[!is.na(x)] %>% fct_discard("<Missing>") |
305 |
} else { |
|
306 | 4x |
x <- x %>% explicit_na(label = "NA") |
307 |
} |
|
308 | ||
309 | 277x |
y <- list() |
310 | ||
311 | 277x |
y$n <- length(x) |
312 | ||
313 | 277x |
y$count <- as.list(table(x, useNA = "ifany")) |
314 | 277x |
dn <- switch(denom, |
315 | 277x |
n = length(x), |
316 | 277x |
N_row = .N_row, |
317 | 277x |
N_col = .N_col |
318 |
) |
|
319 | 277x |
y$count_fraction <- lapply( |
320 | 277x |
y$count, |
321 | 277x |
function(x) { |
322 | 2101x |
c(x, ifelse(dn > 0, x / dn, 0)) |
323 |
} |
|
324 |
) |
|
325 | ||
326 | 277x |
y$n_blq <- sum(grepl("BLQ|LTR|<[1-9]|<PCLLOQ", x)) |
327 | ||
328 | 277x |
y |
329 |
} |
|
330 | ||
331 |
#' @describeIn analyze_variables Method for `character` class. This makes an automatic |
|
332 |
#' conversion to factor (with a warning) and then forwards to the method for factors. |
|
333 |
#' |
|
334 |
#' @param verbose (`logical`)\cr Defaults to `TRUE`, which prints out warnings and messages. It is mainly used |
|
335 |
#' to print out information about factor casting. |
|
336 |
#' |
|
337 |
#' @note |
|
338 |
#' * Automatic conversion of character to factor does not guarantee that the table |
|
339 |
#' can be generated correctly. In particular for sparse tables this very likely can fail. |
|
340 |
#' It is therefore better to always pre-process the dataset such that factors are manually |
|
341 |
#' created from character variables before passing the dataset to [rtables::build_table()]. |
|
342 |
#' |
|
343 |
#' @method s_summary character |
|
344 |
#' |
|
345 |
#' @examples |
|
346 |
#' # `s_summary.character` |
|
347 |
#' |
|
348 |
#' ## Basic usage: |
|
349 |
#' s_summary(c("a", "a", "b", "c", "a"), .var = "x", verbose = FALSE) |
|
350 |
#' s_summary(c("a", "a", "b", "c", "a", ""), .var = "x", na.rm = FALSE, verbose = FALSE) |
|
351 |
#' |
|
352 |
#' @export |
|
353 |
s_summary.character <- function(x, |
|
354 |
na.rm = TRUE, # nolint |
|
355 |
denom = c("n", "N_row", "N_col"), |
|
356 |
.N_row, # nolint |
|
357 |
.N_col, # nolint |
|
358 |
.var, |
|
359 |
verbose = TRUE, |
|
360 |
...) { |
|
361 | 6x |
if (na.rm) { |
362 | 5x |
y <- as_factor_keep_attributes(x, verbose = verbose) |
363 |
} else { |
|
364 | 1x |
y <- as_factor_keep_attributes(x, verbose = verbose, na_level = "NA") |
365 |
} |
|
366 | ||
367 | 6x |
s_summary( |
368 | 6x |
x = y, |
369 | 6x |
na.rm = na.rm, |
370 | 6x |
denom = denom, |
371 | 6x |
.N_row = .N_row, |
372 | 6x |
.N_col = .N_col, |
373 |
... |
|
374 |
) |
|
375 |
} |
|
376 | ||
377 |
#' @describeIn analyze_variables Method for `logical` class. |
|
378 |
#' |
|
379 |
#' @param denom (`string`)\cr choice of denominator for proportion. Options are: |
|
380 |
#' * `n`: number of values in this row and column intersection. |
|
381 |
#' * `N_row`: total number of values in this row across columns. |
|
382 |
#' * `N_col`: total number of values in this column across rows. |
|
383 |
#' |
|
384 |
#' @return |
|
385 |
#' * If `x` is of class `logical`, returns a `list` with named `numeric` items: |
|
386 |
#' * `n`: The [length()] of `x` (possibly after removing `NA`s). |
|
387 |
#' * `count`: Count of `TRUE` in `x`. |
|
388 |
#' * `count_fraction`: Count and proportion of `TRUE` in `x` relative to the denominator, or `NA` if the |
|
389 |
#' denominator is zero. Note that `NA`s in `x` are never counted or leading to `NA` here. |
|
390 |
#' |
|
391 |
#' @method s_summary logical |
|
392 |
#' |
|
393 |
#' @examples |
|
394 |
#' # `s_summary.logical` |
|
395 |
#' |
|
396 |
#' ## Basic usage: |
|
397 |
#' s_summary(c(TRUE, FALSE, TRUE, TRUE)) |
|
398 |
#' |
|
399 |
#' # Empty factor returns zero-filled items. |
|
400 |
#' s_summary(as.logical(c())) |
|
401 |
#' |
|
402 |
#' ## Management of NA values. |
|
403 |
#' x <- c(NA, TRUE, FALSE) |
|
404 |
#' s_summary(x, na.rm = TRUE) |
|
405 |
#' s_summary(x, na.rm = FALSE) |
|
406 |
#' |
|
407 |
#' ## Different denominators. |
|
408 |
#' x <- c(TRUE, FALSE, TRUE, TRUE) |
|
409 |
#' s_summary(x, denom = "N_row", .N_row = 10L) |
|
410 |
#' s_summary(x, denom = "N_col", .N_col = 20L) |
|
411 |
#' |
|
412 |
#' @export |
|
413 |
s_summary.logical <- function(x, |
|
414 |
na.rm = TRUE, # nolint |
|
415 |
denom = c("n", "N_row", "N_col"), |
|
416 |
.N_row, # nolint |
|
417 |
.N_col, # nolint |
|
418 |
...) { |
|
419 | 116x |
denom <- match.arg(denom) |
420 | 114x |
if (na.rm) x <- x[!is.na(x)] |
421 | 116x |
y <- list() |
422 | 116x |
y$n <- length(x) |
423 | 116x |
count <- sum(x, na.rm = TRUE) |
424 | 116x |
dn <- switch(denom, |
425 | 116x |
n = length(x), |
426 | 116x |
N_row = .N_row, |
427 | 116x |
N_col = .N_col |
428 |
) |
|
429 | 116x |
y$count <- count |
430 | 116x |
y$count_fraction <- c(count, ifelse(dn > 0, count / dn, 0)) |
431 | 116x |
y$n_blq <- 0L |
432 | 116x |
y |
433 |
} |
|
434 | ||
435 |
#' @describeIn analyze_variables Formatted analysis function which is used as `afun` in `analyze_vars()` and |
|
436 |
#' `compare_vars()` and as `cfun` in `summarize_colvars()`. |
|
437 |
#' |
|
438 |
#' @param compare (`logical`)\cr Whether comparison statistics should be analyzed instead of summary statistics |
|
439 |
#' (`compare = TRUE` adds `pval` statistic comparing against reference group). |
|
440 |
#' |
|
441 |
#' @return |
|
442 |
#' * `a_summary()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
443 |
#' |
|
444 |
#' @note |
|
445 |
#' * To use for comparison (with additional p-value statistic), parameter `compare` must be set to `TRUE`. |
|
446 |
#' * Ensure that either all `NA` values are converted to an explicit `NA` level or all `NA` values are left as is. |
|
447 |
#' |
|
448 |
#' @examples |
|
449 |
#' a_summary(factor(c("a", "a", "b", "c", "a")), .N_row = 10, .N_col = 10) |
|
450 |
#' a_summary( |
|
451 |
#' factor(c("a", "a", "b", "c", "a")), |
|
452 |
#' .ref_group = factor(c("a", "a", "b", "c")), compare = TRUE |
|
453 |
#' ) |
|
454 |
#' |
|
455 |
#' a_summary(c("A", "B", "A", "C"), .var = "x", .N_col = 10, .N_row = 10, verbose = FALSE) |
|
456 |
#' a_summary( |
|
457 |
#' c("A", "B", "A", "C"), |
|
458 |
#' .ref_group = c("B", "A", "C"), .var = "x", compare = TRUE, verbose = FALSE |
|
459 |
#' ) |
|
460 |
#' |
|
461 |
#' a_summary(c(TRUE, FALSE, FALSE, TRUE, TRUE), .N_row = 10, .N_col = 10) |
|
462 |
#' a_summary( |
|
463 |
#' c(TRUE, FALSE, FALSE, TRUE, TRUE), |
|
464 |
#' .ref_group = c(TRUE, FALSE), .in_ref_col = TRUE, compare = TRUE |
|
465 |
#' ) |
|
466 |
#' |
|
467 |
#' a_summary(rnorm(10), .N_col = 10, .N_row = 20, .var = "bla") |
|
468 |
#' a_summary(rnorm(10, 5, 1), .ref_group = rnorm(20, -5, 1), .var = "bla", compare = TRUE) |
|
469 |
#' |
|
470 |
#' @export |
|
471 |
a_summary <- function(x, |
|
472 |
.N_col, # nolint |
|
473 |
.N_row, # nolint |
|
474 |
.var = NULL, |
|
475 |
.df_row = NULL, |
|
476 |
.ref_group = NULL, |
|
477 |
.in_ref_col = FALSE, |
|
478 |
compare = FALSE, |
|
479 |
.stats = NULL, |
|
480 |
.formats = NULL, |
|
481 |
.labels = NULL, |
|
482 |
.indent_mods = NULL, |
|
483 |
na.rm = TRUE, # nolint |
|
484 |
na_level = lifecycle::deprecated(), |
|
485 |
na_str = default_na_str(), |
|
486 |
...) { |
|
487 | 327x |
extra_args <- list(...) |
488 | 327x |
if (lifecycle::is_present(na_level)) { |
489 | ! |
lifecycle::deprecate_warn("0.9.1", "a_summary(na_level)", "a_summary(na_str)") |
490 | ! |
na_str <- na_level |
491 |
} |
|
492 | ||
493 | 327x |
if (is.numeric(x)) { |
494 | 96x |
type <- "numeric" |
495 | 96x |
if (!is.null(.stats) && any(grepl("^pval", .stats))) { |
496 | 12x |
.stats[grepl("^pval", .stats)] <- "pval" # tmp fix xxx |
497 |
} |
|
498 |
} else { |
|
499 | 231x |
type <- "counts" |
500 | 231x |
if (!is.null(.stats) && any(grepl("^pval", .stats))) { |
501 | 9x |
.stats[grepl("^pval", .stats)] <- "pval_counts" # tmp fix xxx |
502 |
} |
|
503 |
} |
|
504 | ||
505 |
# If one col has NA vals, must add NA row to other cols (using placeholder lvl `fill-na-level`) |
|
506 | ! |
if (any(is.na(.df_row[[.var]])) && !any(is.na(x)) && !na.rm) levels(x) <- c(levels(x), "fill-na-level") |
507 | ||
508 | 327x |
x_stats <- if (!compare) { |
509 | 305x |
s_summary(x = x, .N_col = .N_col, .N_row = .N_row, na.rm = na.rm, ...) |
510 |
} else { |
|
511 | 22x |
s_compare( |
512 | 22x |
x = x, .N_col = .N_col, .N_row = .N_row, na.rm = na.rm, .ref_group = .ref_group, .in_ref_col = .in_ref_col, ... |
513 |
) |
|
514 |
} |
|
515 | ||
516 |
# Fill in with formatting defaults if needed |
|
517 | 327x |
met_grp <- paste0(c("analyze_vars", type), collapse = "_") |
518 | 327x |
.stats <- get_stats(met_grp, stats_in = .stats, add_pval = compare) |
519 | 327x |
.formats <- get_formats_from_stats(.stats, .formats) |
520 | 327x |
.indent_mods <- get_indents_from_stats(.stats, .indent_mods) |
521 | ||
522 | 327x |
lbls <- get_labels_from_stats(.stats, .labels) |
523 |
# Check for custom labels from control_analyze_vars |
|
524 | 327x |
.labels <- if ("control" %in% names(extra_args)) { |
525 | 1x |
lbls %>% labels_use_control(extra_args[["control"]], .labels) |
526 |
} else { |
|
527 | 326x |
lbls |
528 |
} |
|
529 | ||
530 | ! |
if ("count_fraction_fixed_dp" %in% .stats) x_stats[["count_fraction_fixed_dp"]] <- x_stats[["count_fraction"]] |
531 | 327x |
x_stats <- x_stats[.stats] |
532 | ||
533 | 327x |
if (is.factor(x) || is.character(x)) { |
534 |
# Ungroup statistics with values for each level of x |
|
535 | 230x |
x_ungrp <- ungroup_stats(x_stats, .formats, .labels, .indent_mods) |
536 | 230x |
x_stats <- x_ungrp[["x"]] |
537 | 230x |
.formats <- x_ungrp[[".formats"]] |
538 | 230x |
.labels <- gsub("fill-na-level", "NA", x_ungrp[[".labels"]]) |
539 | 230x |
.indent_mods <- x_ungrp[[".indent_mods"]] |
540 |
} |
|
541 | ||
542 |
# Auto format handling |
|
543 | 327x |
.formats <- apply_auto_formatting(.formats, x_stats, .df_row, .var) |
544 | ||
545 | 327x |
in_rows( |
546 | 327x |
.list = x_stats, |
547 | 327x |
.formats = .formats, |
548 | 327x |
.names = .labels, |
549 | 327x |
.labels = .labels, |
550 | 327x |
.indent_mods = .indent_mods, |
551 | 327x |
.format_na_strs = na_str |
552 |
) |
|
553 |
} |
|
554 | ||
555 |
#' Constructor Function for [analyze_vars()] and [summarize_colvars()] |
|
556 |
#' |
|
557 |
#' @description `r lifecycle::badge("deprecated")` |
|
558 |
#' |
|
559 |
#' Constructor function which creates a combined formatted analysis function. |
|
560 |
#' |
|
561 |
#' @inheritParams argument_convention |
|
562 |
#' @param .indent_mods (named `vector` of `integer`)\cr indent modifiers for the labels. Each element of the vector |
|
563 |
#' should be a name-value pair with name corresponding to a statistic specified in `.stats` and value the indentation |
|
564 |
#' for that statistic's row label. |
|
565 |
#' |
|
566 |
#' @return Combined formatted analysis function for use in [analyze_vars()]. |
|
567 |
#' |
|
568 |
#' @note This function has been deprecated in favor of direct implementation of `a_summary()`. |
|
569 |
#' |
|
570 |
#' @seealso [analyze_vars()] |
|
571 |
#' |
|
572 |
#' @export |
|
573 |
create_afun_summary <- function(.stats, .formats, .labels, .indent_mods) { |
|
574 | 1x |
lifecycle::deprecate_warn( |
575 | 1x |
"0.8.5.9010", |
576 | 1x |
"create_afun_summary()", |
577 | 1x |
details = "Please use a_summary() directly instead." |
578 |
) |
|
579 | 1x |
function(x, |
580 | 1x |
.ref_group, |
581 | 1x |
.in_ref_col, |
582 |
..., |
|
583 | 1x |
.var) { |
584 | 18x |
a_summary(x, |
585 | 18x |
.stats = .stats, |
586 | 18x |
.formats = .formats, |
587 | 18x |
.labels = .labels, |
588 | 18x |
.indent_mods = .indent_mods, |
589 | 18x |
.ref_group = .ref_group, |
590 | 18x |
.in_ref_col = .in_ref_col, |
591 | 18x |
.var = .var, ... |
592 |
) |
|
593 |
} |
|
594 |
} |
|
595 | ||
596 |
#' @describeIn analyze_variables Layout-creating function which can take statistics function arguments |
|
597 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
598 |
#' |
|
599 |
#' @param ... arguments passed to `s_summary()`. |
|
600 |
#' @param .indent_mods (named `vector` of `integer`)\cr indent modifiers for the labels. Each element of the vector |
|
601 |
#' should be a name-value pair with name corresponding to a statistic specified in `.stats` and value the indentation |
|
602 |
#' for that statistic's row label. |
|
603 |
#' |
|
604 |
#' @return |
|
605 |
#' * `analyze_vars()` returns a layout object suitable for passing to further layouting functions, |
|
606 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
607 |
#' the statistics from `s_summary()` to the table layout. |
|
608 |
#' |
|
609 |
#' @examples |
|
610 |
#' ## Fabricated dataset. |
|
611 |
#' dta_test <- data.frame( |
|
612 |
#' USUBJID = rep(1:6, each = 3), |
|
613 |
#' PARAMCD = rep("lab", 6 * 3), |
|
614 |
#' AVISIT = rep(paste0("V", 1:3), 6), |
|
615 |
#' ARM = rep(LETTERS[1:3], rep(6, 3)), |
|
616 |
#' AVAL = c(9:1, rep(NA, 9)) |
|
617 |
#' ) |
|
618 |
#' |
|
619 |
#' # `analyze_vars()` in `rtables` pipelines |
|
620 |
#' ## Default output within a `rtables` pipeline. |
|
621 |
#' l <- basic_table() %>% |
|
622 |
#' split_cols_by(var = "ARM") %>% |
|
623 |
#' split_rows_by(var = "AVISIT") %>% |
|
624 |
#' analyze_vars(vars = "AVAL") |
|
625 |
#' |
|
626 |
#' build_table(l, df = dta_test) |
|
627 |
#' |
|
628 |
#' ## Select and format statistics output. |
|
629 |
#' l <- basic_table() %>% |
|
630 |
#' split_cols_by(var = "ARM") %>% |
|
631 |
#' split_rows_by(var = "AVISIT") %>% |
|
632 |
#' analyze_vars( |
|
633 |
#' vars = "AVAL", |
|
634 |
#' .stats = c("n", "mean_sd", "quantiles"), |
|
635 |
#' .formats = c("mean_sd" = "xx.x, xx.x"), |
|
636 |
#' .labels = c(n = "n", mean_sd = "Mean, SD", quantiles = c("Q1 - Q3")) |
|
637 |
#' ) |
|
638 |
#' |
|
639 |
#' build_table(l, df = dta_test) |
|
640 |
#' |
|
641 |
#' ## Use arguments interpreted by `s_summary`. |
|
642 |
#' l <- basic_table() %>% |
|
643 |
#' split_cols_by(var = "ARM") %>% |
|
644 |
#' split_rows_by(var = "AVISIT") %>% |
|
645 |
#' analyze_vars(vars = "AVAL", na.rm = FALSE) |
|
646 |
#' |
|
647 |
#' build_table(l, df = dta_test) |
|
648 |
#' |
|
649 |
#' ## Handle `NA` levels first when summarizing factors. |
|
650 |
#' dta_test$AVISIT <- NA_character_ |
|
651 |
#' dta_test <- df_explicit_na(dta_test) |
|
652 |
#' l <- basic_table() %>% |
|
653 |
#' split_cols_by(var = "ARM") %>% |
|
654 |
#' analyze_vars(vars = "AVISIT", na.rm = FALSE) |
|
655 |
#' |
|
656 |
#' build_table(l, df = dta_test) |
|
657 |
#' |
|
658 |
#' # auto format |
|
659 |
#' dt <- data.frame("VAR" = c(0.001, 0.2, 0.0011000, 3, 4)) |
|
660 |
#' basic_table() %>% |
|
661 |
#' analyze_vars( |
|
662 |
#' vars = "VAR", |
|
663 |
#' .stats = c("n", "mean", "mean_sd", "range"), |
|
664 |
#' .formats = c("mean_sd" = "auto", "range" = "auto") |
|
665 |
#' ) %>% |
|
666 |
#' build_table(dt) |
|
667 |
#' |
|
668 |
#' @export analyze_vars summarize_vars |
|
669 |
#' @order 2 |
|
670 |
analyze_vars <- function(lyt, |
|
671 |
vars, |
|
672 |
var_labels = vars, |
|
673 |
na_level = lifecycle::deprecated(), |
|
674 |
na_str = default_na_str(), |
|
675 |
nested = TRUE, |
|
676 |
..., |
|
677 |
na.rm = TRUE, # nolint |
|
678 |
show_labels = "default", |
|
679 |
table_names = vars, |
|
680 |
section_div = NA_character_, |
|
681 |
.stats = c("n", "mean_sd", "median", "range", "count_fraction"), |
|
682 |
.formats = NULL, |
|
683 |
.labels = NULL, |
|
684 |
.indent_mods = NULL) { |
|
685 | 26x |
if (lifecycle::is_present(na_level)) { |
686 | ! |
lifecycle::deprecate_warn("0.9.1", "analyze_vars(na_level)", "analyze_vars(na_str)") |
687 | ! |
na_str <- na_level |
688 |
} |
|
689 | ||
690 | 26x |
extra_args <- list(.stats = .stats, na.rm = na.rm, na_str = na_str, ...) |
691 | 2x |
if (!is.null(.formats)) extra_args[[".formats"]] <- .formats |
692 | ! |
if (!is.null(.labels)) extra_args[[".labels"]] <- .labels |
693 | ! |
if (!is.null(.indent_mods)) extra_args[[".indent_mods"]] <- .indent_mods |
694 | ||
695 | 26x |
analyze( |
696 | 26x |
lyt = lyt, |
697 | 26x |
vars = vars, |
698 | 26x |
var_labels = var_labels, |
699 | 26x |
afun = a_summary, |
700 | 26x |
na_str = na_str, |
701 | 26x |
nested = nested, |
702 | 26x |
extra_args = extra_args, |
703 | 26x |
inclNAs = TRUE, |
704 | 26x |
show_labels = show_labels, |
705 | 26x |
table_names = table_names, |
706 | 26x |
section_div = section_div |
707 |
) |
|
708 |
} |
|
709 |
#' @describeIn analyze_variables `r lifecycle::badge("deprecated")` Use `analyze_vars` instead. |
|
710 |
summarize_vars <- function(...) { |
|
711 | ! |
lifecycle::deprecate_warn(when = "0.8.5.9010", "summarize_vars()", "analyze_vars()") |
712 | ! |
analyze_vars(...) |
713 |
} |
1 |
#' Split Function to Configure Risk Difference Column |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Wrapper function for [rtables::add_combo_levels()] which configures settings for the risk difference |
|
6 |
#' column to be added to an `rtables` object. To add a risk difference column to a table, this function |
|
7 |
#' should be used as `split_fun` in calls to [rtables::split_cols_by()], followed by setting argument |
|
8 |
#' `riskdiff` to `TRUE` in all following analyze function calls. |
|
9 |
#' |
|
10 |
#' @param arm_x (`character`)\cr Name of reference arm to use in risk difference calculations. |
|
11 |
#' @param arm_y (`character`)\cr Names of one or more arms to compare to reference arm in risk difference |
|
12 |
#' calculations. A new column will be added for each value of `arm_y`. |
|
13 |
#' @param col_label (`character`)\cr Labels to use when rendering the risk difference column within the table. |
|
14 |
#' If more than one comparison arm is specified in `arm_y`, default labels will specify which two arms are |
|
15 |
#' being compared (reference arm vs. comparison arm). |
|
16 |
#' @param pct (`flag`)\cr whether output should be returned as percentages. Defaults to `TRUE`. |
|
17 |
#' |
|
18 |
#' @return A closure suitable for use as a split function (`split_fun`) within [rtables::split_cols_by()] |
|
19 |
#' when creating a table layout. |
|
20 |
#' |
|
21 |
#' @seealso [stat_propdiff_ci()] for details on risk difference calculation. |
|
22 |
#' |
|
23 |
#' @examples |
|
24 |
#' adae <- tern_ex_adae |
|
25 |
#' adae$AESEV <- factor(adae$AESEV) |
|
26 |
#' |
|
27 |
#' lyt <- basic_table() %>% |
|
28 |
#' split_cols_by("ARMCD", split_fun = add_riskdiff(arm_x = "ARM A", arm_y = c("ARM B", "ARM C"))) %>% |
|
29 |
#' count_occurrences_by_grade( |
|
30 |
#' var = "AESEV", |
|
31 |
#' riskdiff = TRUE |
|
32 |
#' ) |
|
33 |
#' |
|
34 |
#' tbl <- build_table(lyt, df = adae) |
|
35 |
#' tbl |
|
36 |
#' |
|
37 |
#' @export |
|
38 |
add_riskdiff <- function(arm_x, |
|
39 |
arm_y, |
|
40 |
col_label = paste0( |
|
41 |
"Risk Difference (%) (95% CI)", if (length(arm_y) > 1) paste0("\n", arm_x, " vs. ", arm_y) |
|
42 |
), |
|
43 |
pct = TRUE) { |
|
44 | 7x |
checkmate::assert_character(arm_x, len = 1) |
45 | 7x |
checkmate::assert_character(arm_y, min.len = 1) |
46 | 7x |
checkmate::assert_character(col_label, len = length(arm_y)) |
47 | ||
48 | 7x |
combodf <- tibble::tribble(~valname, ~label, ~levelcombo, ~exargs) |
49 | 7x |
for (i in seq_len(length(arm_y))) { |
50 | 7x |
combodf <- rbind( |
51 | 7x |
combodf, |
52 | 7x |
tibble::tribble( |
53 | 7x |
~valname, ~label, ~levelcombo, ~exargs, |
54 | 7x |
paste("riskdiff", arm_x, arm_y[i], sep = "_"), col_label[i], c(arm_x, arm_y[i]), list() |
55 |
) |
|
56 |
) |
|
57 |
} |
|
58 | 7x |
if (pct) combodf$valname <- paste0(combodf$valname, "_pct") |
59 | 7x |
add_combo_levels(combodf) |
60 |
} |
|
61 | ||
62 |
#' Analysis Function to Calculate Risk Difference Column Values |
|
63 |
#' |
|
64 |
#' In the risk difference column, this function uses the statistics function associated with `afun` to |
|
65 |
#' calculates risk difference values from arm X (reference group) and arm Y. These arms are specified |
|
66 |
#' when configuring the risk difference column which is done using the [add_riskdiff()] split function in |
|
67 |
#' the previous call to [rtables::split_cols_by()]. For all other columns, applies `afun` as usual. This |
|
68 |
#' function utilizes the [stat_propdiff_ci()] function to perform risk difference calculations. |
|
69 |
#' |
|
70 |
#' @inheritParams argument_convention |
|
71 |
#' @param afun (named `list`)\cr A named list containing one name-value pair where the name corresponds to |
|
72 |
#' the name of the statistics function that should be used in calculations and the value is the corresponding |
|
73 |
#' analysis function. |
|
74 |
#' @param s_args (named `list`)\cr Additional arguments to be passed to the statistics function and analysis |
|
75 |
#' function supplied in `afun`. |
|
76 |
#' |
|
77 |
#' @return A list of formatted [rtables::CellValue()]. |
|
78 |
#' |
|
79 |
#' @seealso |
|
80 |
#' * [stat_propdiff_ci()] for details on risk difference calculation. |
|
81 |
#' * Split function [add_riskdiff()] which, when used as `split_fun` within [rtables::split_cols_by()] with |
|
82 |
#' `riskdiff` argument set to `TRUE` in subsequent analyze functions calls, adds a risk difference column |
|
83 |
#' to a table layout. |
|
84 |
#' |
|
85 |
#' @keywords internal |
|
86 |
afun_riskdiff <- function(df, |
|
87 |
labelstr = "", |
|
88 |
.var, |
|
89 |
.N_col, # nolint |
|
90 |
.N_row, # nolint |
|
91 |
.df_row, |
|
92 |
.spl_context, |
|
93 |
.all_col_counts, |
|
94 |
.stats, |
|
95 |
.formats = NULL, |
|
96 |
.labels = NULL, |
|
97 |
.indent_mods = NULL, |
|
98 |
na_str = default_na_str(), |
|
99 |
afun, |
|
100 |
s_args = list()) { |
|
101 | 44x |
if (!any(grepl("riskdiff", names(.spl_context)))) { |
102 | ! |
stop( |
103 | ! |
"Please set up levels to use in risk difference calculations using the `add_riskdiff` ", |
104 | ! |
"split function within `split_cols_by`. See ?add_riskdiff for details." |
105 |
) |
|
106 |
} |
|
107 | 44x |
checkmate::assert_list(afun, len = 1, types = "function") |
108 | 44x |
checkmate::assert_named(afun) |
109 | 44x |
afun_args <- list( |
110 | 44x |
.var = .var, .df_row = .df_row, .N_row = .N_row, denom = "N_col", labelstr = labelstr, |
111 | 44x |
.stats = .stats, .formats = .formats, .labels = .labels, .indent_mods = .indent_mods, na_str = na_str |
112 |
) |
|
113 | 44x |
afun_args <- afun_args[intersect(names(afun_args), names(as.list(args(afun[[1]]))))] |
114 | ! |
if ("denom" %in% names(s_args)) afun_args[["denom"]] <- NULL |
115 | ||
116 | 44x |
cur_split <- tail(.spl_context$cur_col_split_val[[1]], 1) |
117 | 44x |
if (!grepl("^riskdiff", cur_split)) { |
118 |
# Apply basic afun (no risk difference) in all other columns |
|
119 | 33x |
do.call(afun[[1]], args = c(list(df = df, .N_col = .N_col), afun_args, s_args)) |
120 |
} else { |
|
121 | 11x |
arm_x <- strsplit(cur_split, "_")[[1]][2] |
122 | 11x |
arm_y <- strsplit(cur_split, "_")[[1]][3] |
123 | 11x |
if (length(.spl_context$cur_col_split[[1]]) > 1) { # Different split name for nested column splits |
124 | ! |
arm_spl_x <- gsub("riskdiff", "", paste0(strsplit(.spl_context$cur_col_id[1], "_")[[1]][c(1, 2)], collapse = "")) |
125 | ! |
arm_spl_y <- gsub("riskdiff", "", paste0(strsplit(.spl_context$cur_col_id[1], "_")[[1]][c(1, 3)], collapse = "")) |
126 |
} else { |
|
127 | 11x |
arm_spl_x <- arm_x |
128 | 11x |
arm_spl_y <- arm_y |
129 |
} |
|
130 | 11x |
N_col_x <- .all_col_counts[[arm_spl_x]] # nolint |
131 | 11x |
N_col_y <- .all_col_counts[[arm_spl_y]] # nolint |
132 | 11x |
cur_var <- tail(.spl_context$cur_col_split[[1]], 1) |
133 | ||
134 |
# Apply statistics function to arm X and arm Y data |
|
135 | 11x |
s_args <- c(s_args, afun_args[intersect(names(afun_args), names(as.list(args(names(afun)))))]) |
136 | 11x |
s_x <- do.call(names(afun), args = c(list(df = df[df[[cur_var]] == arm_x, ], .N_col = N_col_x), s_args)) |
137 | 11x |
s_y <- do.call(names(afun), args = c(list(df = df[df[[cur_var]] == arm_y, ], .N_col = N_col_y), s_args)) |
138 | ||
139 |
# Get statistic name and row names |
|
140 | 11x |
stat <- ifelse("count_fraction" %in% names(s_x), "count_fraction", "unique") |
141 | 11x |
if ("flag_variables" %in% names(s_args)) { |
142 | 1x |
var_nms <- s_args$flag_variables |
143 | 10x |
} else if (!is.null(names(s_x[[stat]]))) { |
144 | 4x |
var_nms <- names(s_x[[stat]]) |
145 |
} else { |
|
146 | 6x |
var_nms <- "" |
147 | 6x |
s_x[[stat]] <- list(s_x[[stat]]) |
148 | 6x |
s_y[[stat]] <- list(s_y[[stat]]) |
149 |
} |
|
150 | ||
151 |
# Calculate risk difference for each row, repeated if multiple statistics in table |
|
152 | 11x |
pct <- tail(strsplit(cur_split, "_")[[1]], 1) == "pct" |
153 | 11x |
rd_ci <- rep(stat_propdiff_ci( |
154 | 11x |
lapply(s_x[[stat]], `[`, 1), lapply(s_y[[stat]], `[`, 1), |
155 | 11x |
N_col_x, N_col_y, |
156 | 11x |
list_names = var_nms, |
157 | 11x |
pct = pct |
158 | 11x |
), max(1, length(.stats))) |
159 | ||
160 | 11x |
in_rows(.list = rd_ci, .formats = "xx.x (xx.x - xx.x)", .indent_mods = .indent_mods) |
161 |
} |
|
162 |
} |
1 |
#' Summary numeric variables in columns |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("experimental")` |
|
4 |
#' |
|
5 |
#' Layout-creating function which can be used for creating column-wise summary tables. |
|
6 |
#' This function sets the analysis methods as column labels and is a wrapper for |
|
7 |
#' [rtables::analyze_colvars()]. It was designed principally for PK tables. |
|
8 |
#' |
|
9 |
#' @inheritParams argument_convention |
|
10 |
#' @inheritParams rtables::analyze_colvars |
|
11 |
#' @param imp_rule (`character`)\cr imputation rule setting. Defaults to `NULL` for no imputation rule. Can |
|
12 |
#' also be `"1/3"` to implement 1/3 imputation rule or `"1/2"` to implement 1/2 imputation rule. In order |
|
13 |
#' to use an imputation rule, the `avalcat_var` argument must be specified. See [imputation_rule()] |
|
14 |
#' for more details on imputation. |
|
15 |
#' @param avalcat_var (`character`)\cr if `imp_rule` is not `NULL`, name of variable that indicates whether a |
|
16 |
#' row in the data corresponds to an analysis value in category `"BLQ"`, `"LTR"`, `"<PCLLOQ"`, or none of |
|
17 |
#' the above (defaults to `"AVALCAT1"`). Variable must be present in the data and should match the variable |
|
18 |
#' used to calculate the `n_blq` statistic (if included in `.stats`). |
|
19 |
#' @param cache (`flag`)\cr whether to store computed values in a temporary caching environment. This will |
|
20 |
#' speed up calculations in large tables, but should be set to `FALSE` if the same `rtable` layout is |
|
21 |
#' used for multiple tables with different data. Defaults to `FALSE`. |
|
22 |
#' @param row_labels (`character`)\cr as this function works in columns space, usual `.labels` |
|
23 |
#' character vector applies on the column space. You can change the row labels by defining this |
|
24 |
#' parameter to a named character vector with names corresponding to the split values. It defaults |
|
25 |
#' to `NULL` and if it contains only one `string`, it will duplicate that as a row label. |
|
26 |
#' @param do_summarize_row_groups (`flag`)\cr defaults to `FALSE` and applies the analysis to the current |
|
27 |
#' label rows. This is a wrapper of [rtables::summarize_row_groups()] and it can accept `labelstr` |
|
28 |
#' to define row labels. This behavior is not supported as we never need to overload row labels. |
|
29 |
#' @param split_col_vars (`flag`)\cr defaults to `TRUE` and puts the analysis results onto the columns. |
|
30 |
#' This option allows you to add multiple instances of this functions, also in a nested fashion, |
|
31 |
#' without adding more splits. This split must happen only one time on a single layout. |
|
32 |
#' |
|
33 |
#' @return |
|
34 |
#' A layout object suitable for passing to further layouting functions, or to [rtables::build_table()]. |
|
35 |
#' Adding this function to an `rtable` layout will summarize the given variables, arrange the output |
|
36 |
#' in columns, and add it to the table layout. |
|
37 |
#' |
|
38 |
#' @note This is an experimental implementation of [rtables::summarize_row_groups()] and |
|
39 |
#' [rtables::analyze_colvars()] that may be subjected to changes as `rtables` extends its |
|
40 |
#' support to more complex analysis pipelines on the column space. For the same reasons, |
|
41 |
#' we encourage to read the examples carefully and file issues for cases that differ from |
|
42 |
#' them. |
|
43 |
#' |
|
44 |
#' Here `labelstr` behaves differently than usual. If it is not defined (default as `NULL`), |
|
45 |
#' row labels are assigned automatically to the split values in case of `rtables::analyze_colvars` |
|
46 |
#' (`do_summarize_row_groups = FALSE`, the default), and to the group label for |
|
47 |
#' `do_summarize_row_groups = TRUE`. |
|
48 |
#' |
|
49 |
#' @seealso [analyze_vars()], [rtables::analyze_colvars()]. |
|
50 |
#' |
|
51 |
#' @examples |
|
52 |
#' library(dplyr) |
|
53 |
#' |
|
54 |
#' # Data preparation |
|
55 |
#' adpp <- tern_ex_adpp %>% h_pkparam_sort() |
|
56 |
#' |
|
57 |
#' lyt <- basic_table() %>% |
|
58 |
#' split_rows_by(var = "STRATA1", label_pos = "topleft") %>% |
|
59 |
#' split_rows_by( |
|
60 |
#' var = "SEX", |
|
61 |
#' label_pos = "topleft", |
|
62 |
#' child_label = "hidden" |
|
63 |
#' ) %>% # Removes duplicated labels |
|
64 |
#' analyze_vars_in_cols(vars = "AGE") |
|
65 |
#' result <- build_table(lyt = lyt, df = adpp) |
|
66 |
#' result |
|
67 |
#' |
|
68 |
#' # By selecting just some statistics and ad-hoc labels |
|
69 |
#' lyt <- basic_table() %>% |
|
70 |
#' split_rows_by(var = "ARM", label_pos = "topleft") %>% |
|
71 |
#' split_rows_by( |
|
72 |
#' var = "SEX", |
|
73 |
#' label_pos = "topleft", |
|
74 |
#' child_labels = "hidden", |
|
75 |
#' split_fun = drop_split_levels |
|
76 |
#' ) %>% |
|
77 |
#' analyze_vars_in_cols( |
|
78 |
#' vars = "AGE", |
|
79 |
#' .stats = c("n", "cv", "geom_mean"), |
|
80 |
#' .labels = c( |
|
81 |
#' n = "aN", |
|
82 |
#' cv = "aCV", |
|
83 |
#' geom_mean = "aGeomMean" |
|
84 |
#' ) |
|
85 |
#' ) |
|
86 |
#' result <- build_table(lyt = lyt, df = adpp) |
|
87 |
#' result |
|
88 |
#' |
|
89 |
#' # Changing row labels |
|
90 |
#' lyt <- basic_table() %>% |
|
91 |
#' analyze_vars_in_cols( |
|
92 |
#' vars = "AGE", |
|
93 |
#' row_labels = "some custom label" |
|
94 |
#' ) |
|
95 |
#' result <- build_table(lyt, df = adpp) |
|
96 |
#' result |
|
97 |
#' |
|
98 |
#' # Pharmacokinetic parameters |
|
99 |
#' lyt <- basic_table() %>% |
|
100 |
#' split_rows_by( |
|
101 |
#' var = "TLG_DISPLAY", |
|
102 |
#' split_label = "PK Parameter", |
|
103 |
#' label_pos = "topleft", |
|
104 |
#' child_label = "hidden" |
|
105 |
#' ) %>% |
|
106 |
#' analyze_vars_in_cols( |
|
107 |
#' vars = "AVAL" |
|
108 |
#' ) |
|
109 |
#' result <- build_table(lyt, df = adpp) |
|
110 |
#' result |
|
111 |
#' |
|
112 |
#' # Multiple calls (summarize label and analyze underneath) |
|
113 |
#' lyt <- basic_table() %>% |
|
114 |
#' split_rows_by( |
|
115 |
#' var = "TLG_DISPLAY", |
|
116 |
#' split_label = "PK Parameter", |
|
117 |
#' label_pos = "topleft" |
|
118 |
#' ) %>% |
|
119 |
#' analyze_vars_in_cols( |
|
120 |
#' vars = "AVAL", |
|
121 |
#' do_summarize_row_groups = TRUE # does a summarize level |
|
122 |
#' ) %>% |
|
123 |
#' split_rows_by("SEX", |
|
124 |
#' child_label = "hidden", |
|
125 |
#' label_pos = "topleft" |
|
126 |
#' ) %>% |
|
127 |
#' analyze_vars_in_cols( |
|
128 |
#' vars = "AVAL", |
|
129 |
#' split_col_vars = FALSE # avoids re-splitting the columns |
|
130 |
#' ) |
|
131 |
#' result <- build_table(lyt, df = adpp) |
|
132 |
#' result |
|
133 |
#' |
|
134 |
#' @export |
|
135 |
analyze_vars_in_cols <- function(lyt, |
|
136 |
vars, |
|
137 |
..., |
|
138 |
.stats = c( |
|
139 |
"n", |
|
140 |
"mean", |
|
141 |
"sd", |
|
142 |
"se", |
|
143 |
"cv", |
|
144 |
"geom_cv" |
|
145 |
), |
|
146 |
.labels = c( |
|
147 |
n = "n", |
|
148 |
mean = "Mean", |
|
149 |
sd = "SD", |
|
150 |
se = "SE", |
|
151 |
cv = "CV (%)", |
|
152 |
geom_cv = "CV % Geometric Mean" |
|
153 |
), |
|
154 |
row_labels = NULL, |
|
155 |
do_summarize_row_groups = FALSE, |
|
156 |
split_col_vars = TRUE, |
|
157 |
imp_rule = NULL, |
|
158 |
avalcat_var = "AVALCAT1", |
|
159 |
cache = FALSE, |
|
160 |
.indent_mods = NULL, |
|
161 |
na_level = lifecycle::deprecated(), |
|
162 |
na_str = default_na_str(), |
|
163 |
nested = TRUE, |
|
164 |
.formats = NULL, |
|
165 |
.aligns = NULL) { |
|
166 | 10x |
extra_args <- list(...) |
167 | 10x |
if (lifecycle::is_present(na_level)) { |
168 | ! |
lifecycle::deprecate_warn("0.9.1", "analyze_vars_in_cols(na_level)", "analyze_vars_in_cols(na_str)") |
169 | ! |
na_str <- na_level |
170 |
} |
|
171 | ||
172 | 10x |
checkmate::assert_string(na_str, na.ok = TRUE, null.ok = TRUE) |
173 | 10x |
checkmate::assert_character(row_labels, null.ok = TRUE) |
174 | 10x |
checkmate::assert_int(.indent_mods, null.ok = TRUE) |
175 | 10x |
checkmate::assert_flag(nested) |
176 | 10x |
checkmate::assert_flag(split_col_vars) |
177 | 10x |
checkmate::assert_flag(do_summarize_row_groups) |
178 | ||
179 |
# Filtering |
|
180 | 10x |
met_grps <- paste0("analyze_vars", c("_numeric", "_counts")) |
181 | 10x |
.stats <- get_stats(met_grps, stats_in = .stats) |
182 | 10x |
formats_v <- get_formats_from_stats(stats = .stats, formats_in = .formats) |
183 | 10x |
labels_v <- get_labels_from_stats(stats = .stats, labels_in = .labels) |
184 | ! |
if ("control" %in% names(extra_args)) labels_v <- labels_v %>% labels_use_control(extra_args[["control"]], .labels) |
185 | ||
186 |
# Check for vars in the case that one or more are used |
|
187 | 10x |
if (length(vars) == 1) { |
188 | 7x |
vars <- rep(vars, length(.stats)) |
189 | 3x |
} else if (length(vars) != length(.stats)) { |
190 | 1x |
stop( |
191 | 1x |
"Analyzed variables (vars) does not have the same ", |
192 | 1x |
"number of elements of specified statistics (.stats)." |
193 |
) |
|
194 |
} |
|
195 | ||
196 | 9x |
if (split_col_vars) { |
197 |
# Checking there is not a previous identical column split |
|
198 | 8x |
clyt <- tail(clayout(lyt), 1)[[1]] |
199 | ||
200 | 8x |
dummy_lyt <- split_cols_by_multivar( |
201 | 8x |
lyt = basic_table(), |
202 | 8x |
vars = vars, |
203 | 8x |
varlabels = labels_v |
204 |
) |
|
205 | ||
206 | 8x |
if (any(sapply(clyt, identical, y = get_last_col_split(dummy_lyt)))) { |
207 | ! |
stop( |
208 | ! |
"Column split called again with the same values. ", |
209 | ! |
"This can create many unwanted columns. Please consider adding ", |
210 | ! |
"split_col_vars = FALSE to the last call of ", |
211 | ! |
deparse(sys.calls()[[sys.nframe() - 1]]), "." |
212 |
) |
|
213 |
} |
|
214 | ||
215 |
# Main col split |
|
216 | 8x |
lyt <- split_cols_by_multivar( |
217 | 8x |
lyt = lyt, |
218 | 8x |
vars = vars, |
219 | 8x |
varlabels = labels_v |
220 |
) |
|
221 |
} |
|
222 | ||
223 | 9x |
env <- new.env() # create caching environment |
224 | ||
225 | 9x |
if (do_summarize_row_groups) { |
226 | 2x |
if (length(unique(vars)) > 1) { |
227 | ! |
stop("When using do_summarize_row_groups only one label level var should be inserted.") |
228 |
} |
|
229 | ||
230 |
# Function list for do_summarize_row_groups. Slightly different handling of labels |
|
231 | 2x |
cfun_list <- Map( |
232 | 2x |
function(stat, use_cache, cache_env) { |
233 | 12x |
function(u, .spl_context, labelstr, .df_row, ...) { |
234 |
# Statistic |
|
235 | 24x |
var_row_val <- paste( |
236 | 24x |
gsub("\\._\\[\\[[0-9]+\\]\\]_\\.", "", paste(tail(.spl_context$cur_col_split_val, 1)[[1]], collapse = "_")), |
237 | 24x |
paste(.spl_context$value, collapse = "_"), |
238 | 24x |
sep = "_" |
239 |
) |
|
240 | 24x |
if (use_cache) { |
241 | ! |
if (is.null(cache_env[[var_row_val]])) cache_env[[var_row_val]] <- s_summary(u, ...) |
242 | ! |
x_stats <- cache_env[[var_row_val]] |
243 |
} else { |
|
244 | 24x |
x_stats <- s_summary(u, ...) |
245 |
} |
|
246 | ||
247 | 24x |
if (is.null(imp_rule) || !stat %in% c("mean", "sd", "cv", "geom_mean", "geom_cv", "median", "min", "max")) { |
248 | 24x |
res <- x_stats[[stat]] |
249 |
} else { |
|
250 | ! |
timept <- as.numeric(gsub(".*?([0-9\\.]+).*", "\\1", tail(.spl_context$value, 1))) |
251 | ! |
res_imp <- imputation_rule( |
252 | ! |
.df_row, x_stats, stat, |
253 | ! |
imp_rule = imp_rule, |
254 | ! |
post = grepl("Predose", tail(.spl_context$value, 1)) || timept > 0, |
255 | ! |
avalcat_var = avalcat_var |
256 |
) |
|
257 | ! |
res <- res_imp[["val"]] |
258 | ! |
na_str <- res_imp[["na_str"]] |
259 |
} |
|
260 | ||
261 |
# Label check and replacement |
|
262 | 24x |
if (length(row_labels) > 1) { |
263 | 12x |
if (!(labelstr %in% names(row_labels))) { |
264 | ! |
stop( |
265 | ! |
"Replacing the labels in do_summarize_row_groups needs a named vector", |
266 | ! |
"that contains the split values. In the current split variable ", |
267 | ! |
.spl_context$split[nrow(.spl_context)], |
268 | ! |
" the labelstr value (split value by default) ", labelstr, " is not in", |
269 | ! |
" row_labels names: ", names(row_labels) |
270 |
) |
|
271 |
} |
|
272 | 12x |
lbl <- unlist(row_labels[labelstr]) |
273 |
} else { |
|
274 | 12x |
lbl <- labelstr |
275 |
} |
|
276 | ||
277 |
# Cell creation |
|
278 | 24x |
rcell(res, |
279 | 24x |
label = lbl, |
280 | 24x |
format = formats_v[names(formats_v) == stat][[1]], |
281 | 24x |
format_na_str = na_str, |
282 | 24x |
indent_mod = ifelse(is.null(.indent_mods), 0L, .indent_mods), |
283 | 24x |
align = .aligns |
284 |
) |
|
285 |
} |
|
286 |
}, |
|
287 | 2x |
stat = .stats, |
288 | 2x |
use_cache = cache, |
289 | 2x |
cache_env = replicate(length(.stats), env) |
290 |
) |
|
291 | ||
292 |
# Main call to rtables |
|
293 | 2x |
summarize_row_groups( |
294 | 2x |
lyt = lyt, |
295 | 2x |
var = unique(vars), |
296 | 2x |
cfun = cfun_list, |
297 | 2x |
na_str = na_str, |
298 | 2x |
extra_args = extra_args |
299 |
) |
|
300 |
} else { |
|
301 |
# Function list for analyze_colvars |
|
302 | 7x |
afun_list <- Map( |
303 | 7x |
function(stat, use_cache, cache_env) { |
304 | 32x |
function(u, .spl_context, .df_row, ...) { |
305 |
# Main statistics |
|
306 | 210x |
var_row_val <- paste( |
307 | 210x |
gsub("\\._\\[\\[[0-9]+\\]\\]_\\.", "", paste(tail(.spl_context$cur_col_split_val, 1)[[1]], collapse = "_")), |
308 | 210x |
paste(.spl_context$value, collapse = "_"), |
309 | 210x |
sep = "_" |
310 |
) |
|
311 | 210x |
if (use_cache) { |
312 | 16x |
if (is.null(cache_env[[var_row_val]])) cache_env[[var_row_val]] <- s_summary(u, ...) |
313 | 56x |
x_stats <- cache_env[[var_row_val]] |
314 |
} else { |
|
315 | 154x |
x_stats <- s_summary(u, ...) |
316 |
} |
|
317 | ||
318 | 210x |
if (is.null(imp_rule) || !stat %in% c("mean", "sd", "cv", "geom_mean", "geom_cv", "median", "min", "max")) { |
319 | 170x |
res <- x_stats[[stat]] |
320 |
} else { |
|
321 | 40x |
timept <- as.numeric(gsub(".*?([0-9\\.]+).*", "\\1", tail(.spl_context$value, 1))) |
322 | 40x |
res_imp <- imputation_rule( |
323 | 40x |
.df_row, x_stats, stat, |
324 | 40x |
imp_rule = imp_rule, |
325 | 40x |
post = grepl("Predose", tail(.spl_context$value, 1)) || timept > 0, |
326 | 40x |
avalcat_var = avalcat_var |
327 |
) |
|
328 | 40x |
res <- res_imp[["val"]] |
329 | 40x |
na_str <- res_imp[["na_str"]] |
330 |
} |
|
331 | ||
332 | 210x |
if (is.list(res)) { |
333 | 19x |
if (length(res) > 1) { |
334 | 1x |
stop("The analyzed column produced more than one category of results.") |
335 |
} else { |
|
336 | 18x |
res <- unlist(res) |
337 |
} |
|
338 |
} |
|
339 | ||
340 |
# Label from context |
|
341 | 209x |
label_from_context <- .spl_context$value[nrow(.spl_context)] |
342 | ||
343 |
# Label switcher |
|
344 | 209x |
if (is.null(row_labels)) { |
345 | 149x |
lbl <- label_from_context |
346 |
} else { |
|
347 | 60x |
if (length(row_labels) > 1) { |
348 | 48x |
if (!(label_from_context %in% names(row_labels))) { |
349 | ! |
stop( |
350 | ! |
"Replacing the labels in do_summarize_row_groups needs a named vector", |
351 | ! |
"that contains the split values. In the current split variable ", |
352 | ! |
.spl_context$split[nrow(.spl_context)], |
353 | ! |
" the split value ", label_from_context, " is not in", |
354 | ! |
" row_labels names: ", names(row_labels) |
355 |
) |
|
356 |
} |
|
357 | 48x |
lbl <- unlist(row_labels[label_from_context]) |
358 |
} else { |
|
359 | 12x |
lbl <- row_labels |
360 |
} |
|
361 |
} |
|
362 | ||
363 |
# Cell creation |
|
364 | 209x |
rcell(res, |
365 | 209x |
label = lbl, |
366 | 209x |
format = formats_v[names(formats_v) == stat][[1]], |
367 | 209x |
format_na_str = na_str, |
368 | 209x |
indent_mod = ifelse(is.null(.indent_mods), 0L, .indent_mods), |
369 | 209x |
align = .aligns |
370 |
) |
|
371 |
} |
|
372 |
}, |
|
373 | 7x |
stat = .stats, |
374 | 7x |
use_cache = cache, |
375 | 7x |
cache_env = replicate(length(.stats), env) |
376 |
) |
|
377 | ||
378 |
# Main call to rtables |
|
379 | 7x |
analyze_colvars(lyt, |
380 | 7x |
afun = afun_list, |
381 | 7x |
na_str = na_str, |
382 | 7x |
nested = nested, |
383 | 7x |
extra_args = extra_args |
384 |
) |
|
385 |
} |
|
386 |
} |
|
387 | ||
388 |
# Help function |
|
389 |
get_last_col_split <- function(lyt) { |
|
390 | 1x |
tail(tail(clayout(lyt), 1)[[1]], 1)[[1]] |
391 |
} |
1 |
#' Subgroup Treatment Effect Pattern (STEP) Fit for Binary (Response) Outcome |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' This fits the Subgroup Treatment Effect Pattern logistic regression models for a binary |
|
6 |
#' (response) outcome. The treatment arm variable must have exactly 2 levels, |
|
7 |
#' where the first one is taken as reference and the estimated odds ratios are |
|
8 |
#' for the comparison of the second level vs. the first one. |
|
9 |
#' |
|
10 |
#' The (conditional) logistic regression model which is fit is: |
|
11 |
#' |
|
12 |
#' `response ~ arm * poly(biomarker, degree) + covariates + strata(strata)` |
|
13 |
#' |
|
14 |
#' where `degree` is specified by `control_step()`. |
|
15 |
#' |
|
16 |
#' @inheritParams argument_convention |
|
17 |
#' @param variables (named `list` of `character`)\cr list of analysis variables: |
|
18 |
#' needs `response`, `arm`, `biomarker`, and optional `covariates` and `strata`. |
|
19 |
#' @param control (named `list`)\cr combined control list from [control_step()] |
|
20 |
#' and [control_logistic()]. |
|
21 |
#' |
|
22 |
#' @return A matrix of class `step`. The first part of the columns describe the |
|
23 |
#' subgroup intervals used for the biomarker variable, including where the |
|
24 |
#' center of the intervals are and their bounds. The second part of the |
|
25 |
#' columns contain the estimates for the treatment arm comparison. |
|
26 |
#' |
|
27 |
#' @note For the default degree 0 the `biomarker` variable is not included in the model. |
|
28 |
#' |
|
29 |
#' @seealso [control_step()] and [control_logistic()] for the available |
|
30 |
#' customization options. |
|
31 |
#' |
|
32 |
#' @examples |
|
33 |
#' # Testing dataset with just two treatment arms. |
|
34 |
#' library(survival) |
|
35 |
#' library(dplyr) |
|
36 |
#' |
|
37 |
#' adrs_f <- tern_ex_adrs %>% |
|
38 |
#' filter( |
|
39 |
#' PARAMCD == "BESRSPI", |
|
40 |
#' ARM %in% c("B: Placebo", "A: Drug X") |
|
41 |
#' ) %>% |
|
42 |
#' mutate( |
|
43 |
#' # Reorder levels of ARM to have Placebo as reference arm for Odds Ratio calculations. |
|
44 |
#' ARM = droplevels(forcats::fct_relevel(ARM, "B: Placebo")), |
|
45 |
#' RSP = case_when(AVALC %in% c("PR", "CR") ~ 1, TRUE ~ 0), |
|
46 |
#' SEX = factor(SEX) |
|
47 |
#' ) |
|
48 |
#' |
|
49 |
#' variables <- list( |
|
50 |
#' arm = "ARM", |
|
51 |
#' biomarker = "BMRKR1", |
|
52 |
#' covariates = "AGE", |
|
53 |
#' response = "RSP" |
|
54 |
#' ) |
|
55 |
#' |
|
56 |
#' # Fit default STEP models: Here a constant treatment effect is estimated in each subgroup. |
|
57 |
#' # We use a large enough bandwidth to avoid too small subgroups and linear separation in those. |
|
58 |
#' step_matrix <- fit_rsp_step( |
|
59 |
#' variables = variables, |
|
60 |
#' data = adrs_f, |
|
61 |
#' control = c(control_logistic(), control_step(bandwidth = 0.5)) |
|
62 |
#' ) |
|
63 |
#' dim(step_matrix) |
|
64 |
#' head(step_matrix) |
|
65 |
#' |
|
66 |
#' # Specify different polynomial degree for the biomarker interaction to use more flexible local |
|
67 |
#' # models. Or specify different logistic regression options, including confidence level. |
|
68 |
#' step_matrix2 <- fit_rsp_step( |
|
69 |
#' variables = variables, |
|
70 |
#' data = adrs_f, |
|
71 |
#' control = c(control_logistic(conf_level = 0.9), control_step(bandwidth = 0.6, degree = 1)) |
|
72 |
#' ) |
|
73 |
#' |
|
74 |
#' # Use a global constant model. This is helpful as a reference for the subgroup models. |
|
75 |
#' step_matrix3 <- fit_rsp_step( |
|
76 |
#' variables = variables, |
|
77 |
#' data = adrs_f, |
|
78 |
#' control = c(control_logistic(), control_step(bandwidth = NULL, num_points = 2L)) |
|
79 |
#' ) |
|
80 |
#' |
|
81 |
#' # It is also possible to use strata, i.e. use conditional logistic regression models. |
|
82 |
#' variables2 <- list( |
|
83 |
#' arm = "ARM", |
|
84 |
#' biomarker = "BMRKR1", |
|
85 |
#' covariates = "AGE", |
|
86 |
#' response = "RSP", |
|
87 |
#' strata = c("STRATA1", "STRATA2") |
|
88 |
#' ) |
|
89 |
#' |
|
90 |
#' step_matrix4 <- fit_rsp_step( |
|
91 |
#' variables = variables2, |
|
92 |
#' data = adrs_f, |
|
93 |
#' control = c(control_logistic(), control_step(bandwidth = 0.6)) |
|
94 |
#' ) |
|
95 |
#' |
|
96 |
#' @export |
|
97 |
fit_rsp_step <- function(variables, |
|
98 |
data, |
|
99 |
control = c(control_step(), control_logistic())) { |
|
100 | 5x |
assert_df_with_variables(data, variables) |
101 | 5x |
checkmate::assert_list(control, names = "named") |
102 | 5x |
data <- data[!is.na(data[[variables$biomarker]]), ] |
103 | 5x |
window_sel <- h_step_window(x = data[[variables$biomarker]], control = control) |
104 | 5x |
interval_center <- window_sel$interval[, "Interval Center"] |
105 | 5x |
form <- h_step_rsp_formula(variables = variables, control = control) |
106 | 5x |
estimates <- if (is.null(control$bandwidth)) { |
107 | 1x |
h_step_rsp_est( |
108 | 1x |
formula = form, |
109 | 1x |
data = data, |
110 | 1x |
variables = variables, |
111 | 1x |
x = interval_center, |
112 | 1x |
control = control |
113 |
) |
|
114 |
} else { |
|
115 | 4x |
tmp <- mapply( |
116 | 4x |
FUN = h_step_rsp_est, |
117 | 4x |
x = interval_center, |
118 | 4x |
subset = as.list(as.data.frame(window_sel$sel)), |
119 | 4x |
MoreArgs = list( |
120 | 4x |
formula = form, |
121 | 4x |
data = data, |
122 | 4x |
variables = variables, |
123 | 4x |
control = control |
124 |
) |
|
125 |
) |
|
126 |
# Maybe we find a more elegant solution than this. |
|
127 | 4x |
rownames(tmp) <- c("n", "logor", "se", "ci_lower", "ci_upper") |
128 | 4x |
t(tmp) |
129 |
} |
|
130 | 5x |
result <- cbind(window_sel$interval, estimates) |
131 | 5x |
structure( |
132 | 5x |
result, |
133 | 5x |
class = c("step", "matrix"), |
134 | 5x |
variables = variables, |
135 | 5x |
control = control |
136 |
) |
|
137 |
} |
1 |
#' Line plot with the optional table |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Line plot with the optional table. |
|
6 |
#' |
|
7 |
#' @param df (`data.frame`)\cr data set containing all analysis variables. |
|
8 |
#' @param alt_counts_df (`data.frame` or `NULL`)\cr data set that will be used (only) |
|
9 |
#' to counts objects in groups for stratification. |
|
10 |
#' @param variables (named `character` vector) of variable names in `df` data set. Details are: |
|
11 |
#' * `x` (`character`)\cr name of x-axis variable. |
|
12 |
#' * `y` (`character`)\cr name of y-axis variable. |
|
13 |
#' * `group_var` (`character`)\cr name of grouping variable (or strata), i.e. treatment arm. |
|
14 |
#' Can be `NA` to indicate lack of groups. |
|
15 |
#' * `subject_var` (`character`)\cr name of subject variable. Only applies if `group_var` is |
|
16 |
#' not NULL. |
|
17 |
#' * `paramcd` (`character`)\cr name of the variable for parameter's code. Used for y-axis label and plot's subtitle. |
|
18 |
#' Can be `NA` if `paramcd` is not to be added to the y-axis label or subtitle. |
|
19 |
#' * `y_unit` (`character`)\cr name of variable with units of `y`. Used for y-axis label and plot's subtitle. |
|
20 |
#' Can be `NA` if y unit is not to be added to the y-axis label or subtitle. |
|
21 |
#' @param mid (`character` or `NULL`)\cr names of the statistics that will be plotted as midpoints. |
|
22 |
#' All the statistics indicated in `mid` variable must be present in the object returned by `sfun`, |
|
23 |
#' and be of a `double` or `numeric` type vector of length one. |
|
24 |
#' @param interval (`character` or `NULL`)\cr names of the statistics that will be plotted as intervals. |
|
25 |
#' All the statistics indicated in `interval` variable must be present in the object returned by `sfun`, |
|
26 |
#' and be of a `double` or `numeric` type vector of length two. Set `interval = NULL` if intervals should not be |
|
27 |
#' added to the plot. |
|
28 |
#' @param whiskers (`character`)\cr names of the interval whiskers that will be plotted. Names must match names |
|
29 |
#' of the list element `interval` that will be returned by `sfun` (e.g. `mean_ci_lwr` element of |
|
30 |
#' `sfun(x)[["mean_ci"]]`). It is possible to specify one whisker only, or to suppress all whiskers by setting |
|
31 |
#' `interval = NULL`. |
|
32 |
#' @param table (`character` or `NULL`)\cr names of the statistics that will be displayed in the table below the plot. |
|
33 |
#' All the statistics indicated in `table` variable must be present in the object returned by `sfun`. |
|
34 |
#' @param sfun (`closure`)\cr the function to compute the values of required statistics. It must return a named `list` |
|
35 |
#' with atomic vectors. The names of the `list` elements refer to the names of the statistics and are used by `mid`, |
|
36 |
#' `interval`, `table`. It must be able to accept as input a vector with data for which statistics are computed. |
|
37 |
#' @param ... optional arguments to `sfun`. |
|
38 |
#' @param mid_type (`character`)\cr controls the type of the `mid` plot, it can be point (`p`), line (`l`), |
|
39 |
#' or point and line (`pl`). |
|
40 |
#' @param mid_point_size (`integer` or `double`)\cr controls the font size of the point for `mid` plot. |
|
41 |
#' @param position (`character` or `call`)\cr geom element position adjustment, either as a string, or the result of |
|
42 |
#' a call to a position adjustment function. |
|
43 |
#' @param legend_title (`character` string)\cr legend title. |
|
44 |
#' @param legend_position (`character`)\cr the position of the plot legend (`none`, `left`, `right`, `bottom`, `top`, |
|
45 |
#' or two-element numeric vector). |
|
46 |
#' @param ggtheme (`theme`)\cr a graphical theme as provided by `ggplot2` to control styling of the plot. |
|
47 |
#' @param x_lab (`character`)\cr x-axis label. If equal to `NULL`, then no label will be added. |
|
48 |
#' @param y_lab (`character`)\cr y-axis label. If equal to `NULL`, then no label will be added. |
|
49 |
#' @param y_lab_add_paramcd (`logical`)\cr should `paramcd`, i.e. `unique(df[[variables["paramcd"]]])` be added to the |
|
50 |
#' y-axis label `y_lab`? |
|
51 |
#' @param y_lab_add_unit (`logical`)\cr should y unit, i.e. `unique(df[[variables["y_unit"]]])` be added to the y-axis |
|
52 |
#' label `y_lab`? |
|
53 |
#' @param title (`character`)\cr plot title. |
|
54 |
#' @param subtitle (`character`)\cr plot subtitle. |
|
55 |
#' @param subtitle_add_paramcd (`logical`)\cr should `paramcd`, i.e. `unique(df[[variables["paramcd"]]])` be added to |
|
56 |
#' the plot's subtitle `subtitle`? |
|
57 |
#' @param subtitle_add_unit (`logical`)\cr should y unit, i.e. `unique(df[[variables["y_unit"]]])` be added to the |
|
58 |
#' plot's subtitle `subtitle`? |
|
59 |
#' @param caption (`character`)\cr optional caption below the plot. |
|
60 |
#' @param table_format (named `character` or `NULL`)\cr format patterns for descriptive statistics used in the |
|
61 |
#' (optional) table appended to the plot. It is passed directly to the `h_format_row` function through the `format` |
|
62 |
#' parameter. Names of `table_format` must match the names of statistics returned by `sfun` function. |
|
63 |
#' @param table_labels (named `character` or `NULL`)\cr labels for descriptive statistics used in the (optional) table |
|
64 |
#' appended to the plot. Names of `table_labels` must match the names of statistics returned by `sfun` function. |
|
65 |
#' @param table_font_size (`integer` or `double`)\cr controls the font size of values in the table. |
|
66 |
#' @param newpage (`logical`)\cr should plot be drawn on new page? |
|
67 |
#' @param col (`character`)\cr colors. |
|
68 |
#' |
|
69 |
#' @return A `ggplot` line plot (and statistics table if applicable). |
|
70 |
#' |
|
71 |
#' @examples |
|
72 |
#' library(nestcolor) |
|
73 |
#' |
|
74 |
#' adsl <- tern_ex_adsl |
|
75 |
#' adlb <- tern_ex_adlb %>% dplyr::filter(ANL01FL == "Y", PARAMCD == "ALT", AVISIT != "SCREENING") |
|
76 |
#' adlb$AVISIT <- droplevels(adlb$AVISIT) |
|
77 |
#' adlb <- dplyr::mutate(adlb, AVISIT = forcats::fct_reorder(AVISIT, AVISITN, min)) |
|
78 |
#' |
|
79 |
#' # Mean with CI |
|
80 |
#' g_lineplot(adlb, adsl, subtitle = "Laboratory Test:") |
|
81 |
#' |
|
82 |
#' # Mean with CI, no stratification with group_var |
|
83 |
#' g_lineplot(adlb, variables = control_lineplot_vars(group_var = NA)) |
|
84 |
#' |
|
85 |
#' # Mean, upper whisker of CI, no group_var(strata) counts N |
|
86 |
#' g_lineplot( |
|
87 |
#' adlb, |
|
88 |
#' whiskers = "mean_ci_upr", |
|
89 |
#' title = "Plot of Mean and Upper 95% Confidence Limit by Visit" |
|
90 |
#' ) |
|
91 |
#' |
|
92 |
#' # Median with CI |
|
93 |
#' g_lineplot( |
|
94 |
#' adlb, |
|
95 |
#' adsl, |
|
96 |
#' mid = "median", |
|
97 |
#' interval = "median_ci", |
|
98 |
#' whiskers = c("median_ci_lwr", "median_ci_upr"), |
|
99 |
#' title = "Plot of Median and 95% Confidence Limits by Visit" |
|
100 |
#' ) |
|
101 |
#' |
|
102 |
#' # Mean, +/- SD |
|
103 |
#' g_lineplot(adlb, adsl, |
|
104 |
#' interval = "mean_sdi", |
|
105 |
#' whiskers = c("mean_sdi_lwr", "mean_sdi_upr"), |
|
106 |
#' title = "Plot of Median +/- SD by Visit" |
|
107 |
#' ) |
|
108 |
#' |
|
109 |
#' # Mean with CI plot with stats table |
|
110 |
#' g_lineplot(adlb, adsl, table = c("n", "mean", "mean_ci")) |
|
111 |
#' |
|
112 |
#' # Mean with CI, table and customized confidence level |
|
113 |
#' g_lineplot( |
|
114 |
#' adlb, |
|
115 |
#' adsl, |
|
116 |
#' table = c("n", "mean", "mean_ci"), |
|
117 |
#' control = control_analyze_vars(conf_level = 0.80), |
|
118 |
#' title = "Plot of Mean and 80% Confidence Limits by Visit" |
|
119 |
#' ) |
|
120 |
#' |
|
121 |
#' # Mean with CI, table, filtered data |
|
122 |
#' adlb_f <- dplyr::filter(adlb, ARMCD != "ARM A" | AVISIT == "BASELINE") |
|
123 |
#' g_lineplot(adlb_f, table = c("n", "mean")) |
|
124 |
#' |
|
125 |
#' @export |
|
126 |
g_lineplot <- function(df, |
|
127 |
alt_counts_df = NULL, |
|
128 |
variables = control_lineplot_vars(), |
|
129 |
mid = "mean", |
|
130 |
interval = "mean_ci", |
|
131 |
whiskers = c("mean_ci_lwr", "mean_ci_upr"), |
|
132 |
table = NULL, |
|
133 |
sfun = tern::s_summary, |
|
134 |
..., |
|
135 |
mid_type = "pl", |
|
136 |
mid_point_size = 2, |
|
137 |
position = ggplot2::position_dodge(width = 0.4), |
|
138 |
legend_title = NULL, |
|
139 |
legend_position = "bottom", |
|
140 |
ggtheme = nestcolor::theme_nest(), |
|
141 |
x_lab = obj_label(df[[variables[["x"]]]]), |
|
142 |
y_lab = NULL, |
|
143 |
y_lab_add_paramcd = TRUE, |
|
144 |
y_lab_add_unit = TRUE, |
|
145 |
title = "Plot of Mean and 95% Confidence Limits by Visit", |
|
146 |
subtitle = "", |
|
147 |
subtitle_add_paramcd = TRUE, |
|
148 |
subtitle_add_unit = TRUE, |
|
149 |
caption = NULL, |
|
150 |
table_format = summary_formats(), |
|
151 |
table_labels = summary_labels(), |
|
152 |
table_font_size = 3, |
|
153 |
newpage = TRUE, |
|
154 |
col = NULL) { |
|
155 | 3x |
checkmate::assert_character(variables, any.missing = TRUE) |
156 | 3x |
checkmate::assert_character(mid, null.ok = TRUE) |
157 | 3x |
checkmate::assert_character(interval, null.ok = TRUE) |
158 | 3x |
checkmate::assert_character(col, null.ok = TRUE) |
159 | ||
160 | 3x |
checkmate::assert_string(title, null.ok = TRUE) |
161 | 3x |
checkmate::assert_string(subtitle, null.ok = TRUE) |
162 | ||
163 | 3x |
if (is.character(interval)) { |
164 | 3x |
checkmate::assert_vector(whiskers, min.len = 0, max.len = 2) |
165 |
} |
|
166 | ||
167 | 3x |
if (length(whiskers) == 1) { |
168 | ! |
checkmate::assert_character(mid) |
169 |
} |
|
170 | ||
171 | 3x |
if (is.character(mid)) { |
172 | 3x |
checkmate::assert_scalar(mid_type) |
173 | 3x |
checkmate::assert_subset(mid_type, c("pl", "p", "l")) |
174 |
} |
|
175 | ||
176 | 3x |
x <- variables[["x"]] |
177 | 3x |
y <- variables[["y"]] |
178 | 3x |
paramcd <- variables["paramcd"] # NA if paramcd == NA or it is not in variables |
179 | 3x |
y_unit <- variables["y_unit"] # NA if y_unit == NA or it is not in variables |
180 | 3x |
if (is.na(variables["group_var"])) { |
181 | ! |
group_var <- NULL # NULL if group_var == NA or it is not in variables |
182 |
} else { |
|
183 | 3x |
group_var <- variables[["group_var"]] |
184 | 3x |
subject_var <- variables[["subject_var"]] |
185 |
} |
|
186 | 3x |
checkmate::assert_flag(y_lab_add_paramcd, null.ok = TRUE) |
187 | 3x |
checkmate::assert_flag(subtitle_add_paramcd, null.ok = TRUE) |
188 | 3x |
if ((!is.null(y_lab) && y_lab_add_paramcd) || (!is.null(subtitle) && subtitle_add_paramcd)) { |
189 | 3x |
checkmate::assert_false(is.na(paramcd)) |
190 | 3x |
checkmate::assert_scalar(unique(df[[paramcd]])) |
191 |
} |
|
192 | ||
193 | 3x |
checkmate::assert_flag(y_lab_add_unit, null.ok = TRUE) |
194 | 3x |
checkmate::assert_flag(subtitle_add_unit, null.ok = TRUE) |
195 | 3x |
if ((!is.null(y_lab) && y_lab_add_unit) || (!is.null(subtitle) && subtitle_add_unit)) { |
196 | 3x |
checkmate::assert_false(is.na(y_unit)) |
197 | 3x |
checkmate::assert_scalar(unique(df[[y_unit]])) |
198 |
} |
|
199 | ||
200 | 3x |
if (!is.null(group_var) && !is.null(alt_counts_df)) { |
201 | 3x |
checkmate::assert_set_equal(unique(alt_counts_df[[group_var]]), unique(df[[group_var]])) |
202 |
} |
|
203 | ||
204 |
####################################### | |
|
205 |
# ---- Compute required statistics ---- |
|
206 |
####################################### | |
|
207 | 3x |
if (!is.null(group_var)) { |
208 | 3x |
df_grp <- tidyr::expand(df, .data[[group_var]], .data[[x]]) # expand based on levels of factors |
209 |
} else { |
|
210 | ! |
df_grp <- tidyr::expand(df, NULL, .data[[x]]) |
211 |
} |
|
212 | 3x |
df_grp <- df_grp %>% |
213 | 3x |
dplyr::full_join(y = df[, c(group_var, x, y)], by = c(group_var, x), multiple = "all") %>% |
214 | 3x |
dplyr::group_by_at(c(group_var, x)) |
215 | ||
216 | 3x |
df_stats <- df_grp %>% |
217 | 3x |
dplyr::summarise( |
218 | 3x |
data.frame(t(do.call(c, unname(sfun(.data[[y]], ...)[c(mid, interval)])))), |
219 | 3x |
.groups = "drop" |
220 |
) |
|
221 | ||
222 | 3x |
df_stats <- df_stats[!is.na(df_stats[[mid]]), ] |
223 | ||
224 |
# add number of objects N in group_var (strata) |
|
225 | 3x |
if (!is.null(group_var) && !is.null(alt_counts_df)) { |
226 | 3x |
strata_N <- paste0(group_var, "_N") # nolint |
227 | ||
228 | 3x |
df_N <- stats::aggregate(eval(parse(text = subject_var)) ~ eval(parse(text = group_var)), data = alt_counts_df, FUN = function(x) length(unique(x))) # nolint |
229 | 3x |
colnames(df_N) <- c(group_var, "N") # nolint |
230 | 3x |
df_N[[strata_N]] <- paste0(df_N[[group_var]], " (N = ", df_N$N, ")") # nolint |
231 | ||
232 |
# strata_N should not be in clonames(df_stats) |
|
233 | 3x |
checkmate::assert_disjunct(strata_N, colnames(df_stats)) |
234 | ||
235 | 3x |
df_stats <- merge(x = df_stats, y = df_N[, c(group_var, strata_N)], by = group_var) |
236 | ! |
} else if (!is.null(group_var)) { |
237 | ! |
strata_N <- group_var # nolint |
238 |
} else { |
|
239 | ! |
strata_N <- NULL # nolint |
240 |
} |
|
241 | ||
242 |
############################################### | |
|
243 |
# ---- Prepare certain plot's properties. ---- |
|
244 |
############################################### | |
|
245 |
# legend title |
|
246 | 3x |
if (is.null(legend_title) && !is.null(group_var) && legend_position != "none") { |
247 | 3x |
legend_title <- attr(df[[group_var]], "label") |
248 |
} |
|
249 | ||
250 |
# y label |
|
251 | 3x |
if (!is.null(y_lab)) { |
252 | 2x |
if (y_lab_add_paramcd) { |
253 | 2x |
y_lab <- paste(y_lab, unique(df[[paramcd]])) |
254 |
} |
|
255 | ||
256 | 2x |
if (y_lab_add_unit) { |
257 | 2x |
y_lab <- paste0(y_lab, " (", unique(df[[y_unit]]), ")") |
258 |
} |
|
259 | ||
260 | 2x |
y_lab <- trimws(y_lab) |
261 |
} |
|
262 | ||
263 |
# subtitle |
|
264 | 3x |
if (!is.null(subtitle)) { |
265 | 3x |
if (subtitle_add_paramcd) { |
266 | 3x |
subtitle <- paste(subtitle, unique(df[[paramcd]])) |
267 |
} |
|
268 | ||
269 | 3x |
if (subtitle_add_unit) { |
270 | 3x |
subtitle <- paste0(subtitle, " (", unique(df[[y_unit]]), ")") |
271 |
} |
|
272 | ||
273 | 3x |
subtitle <- trimws(subtitle) |
274 |
} |
|
275 | ||
276 |
############################### | |
|
277 |
# ---- Build plot object. ---- |
|
278 |
############################### | |
|
279 | 3x |
p <- ggplot2::ggplot( |
280 | 3x |
data = df_stats, |
281 | 3x |
mapping = ggplot2::aes( |
282 | 3x |
x = .data[[x]], y = .data[[mid]], |
283 | 3x |
color = if (is.null(strata_N)) NULL else .data[[strata_N]], |
284 | 3x |
shape = if (is.null(strata_N)) NULL else .data[[strata_N]], |
285 | 3x |
lty = if (is.null(strata_N)) NULL else .data[[strata_N]], |
286 | 3x |
group = if (is.null(strata_N)) NULL else .data[[strata_N]] |
287 |
) |
|
288 |
) |
|
289 | ||
290 | 3x |
if (!is.null(mid)) { |
291 |
# points |
|
292 | 3x |
if (grepl("p", mid_type, fixed = TRUE)) { |
293 | 3x |
p <- p + ggplot2::geom_point(position = position, size = mid_point_size, na.rm = TRUE) |
294 |
} |
|
295 | ||
296 |
# lines |
|
297 |
# further conditions in if are to ensure that not all of the groups consist of only one observation |
|
298 | 3x |
if (grepl("l", mid_type, fixed = TRUE) && !is.null(group_var) && |
299 | 3x |
!all(dplyr::summarise(df_grp, count_n = dplyr::n())[["count_n"]] == 1L)) { # nolint |
300 | 3x |
p <- p + ggplot2::geom_line(position = position, na.rm = TRUE) |
301 |
} |
|
302 |
} |
|
303 | ||
304 |
# interval |
|
305 | 3x |
if (!is.null(interval)) { |
306 | 3x |
p <- p + |
307 | 3x |
ggplot2::geom_errorbar( |
308 | 3x |
ggplot2::aes(ymin = .data[[whiskers[1]]], ymax = .data[[whiskers[max(1, length(whiskers))]]]), |
309 | 3x |
width = 0.45, |
310 | 3x |
position = position |
311 |
) |
|
312 | ||
313 | 3x |
if (length(whiskers) == 1) { # lwr or upr only; mid is then required |
314 |
# workaround as geom_errorbar does not provide single-direction whiskers |
|
315 | ! |
p <- p + |
316 | ! |
ggplot2::geom_linerange( |
317 | ! |
data = df_stats[!is.na(df_stats[[whiskers]]), ], # as na.rm =TRUE does not suppress warnings |
318 | ! |
ggplot2::aes(ymin = .data[[mid]], ymax = .data[[whiskers]]), |
319 | ! |
position = position, |
320 | ! |
na.rm = TRUE, |
321 | ! |
show.legend = FALSE |
322 |
) |
|
323 |
} |
|
324 |
} |
|
325 | ||
326 | 3x |
p <- p + |
327 | 3x |
ggplot2::scale_y_continuous(labels = scales::comma) + |
328 | 3x |
ggplot2::labs( |
329 | 3x |
title = title, |
330 | 3x |
subtitle = subtitle, |
331 | 3x |
caption = caption, |
332 | 3x |
color = legend_title, |
333 | 3x |
lty = legend_title, |
334 | 3x |
shape = legend_title, |
335 | 3x |
x = x_lab, |
336 | 3x |
y = y_lab |
337 |
) |
|
338 | ||
339 | 3x |
if (!is.null(col)) { |
340 | ! |
p <- p + |
341 | ! |
ggplot2::scale_color_manual(values = col) |
342 |
} |
|
343 | ||
344 | 3x |
if (!is.null(ggtheme)) { |
345 | 3x |
p <- p + ggtheme |
346 |
} else { |
|
347 | ! |
p <- p + |
348 | ! |
ggplot2::theme_bw() + |
349 | ! |
ggplot2::theme( |
350 | ! |
legend.key.width = grid::unit(1, "cm"), |
351 | ! |
legend.position = legend_position, |
352 | ! |
legend.direction = ifelse( |
353 | ! |
legend_position %in% c("top", "bottom"), |
354 | ! |
"horizontal", |
355 | ! |
"vertical" |
356 |
) |
|
357 |
) |
|
358 |
} |
|
359 | ||
360 |
############################################################# | |
|
361 |
# ---- Optionally, add table to the bottom of the plot. ---- |
|
362 |
############################################################# | |
|
363 | 3x |
if (!is.null(table)) { |
364 | 2x |
df_stats_table <- df_grp %>% |
365 | 2x |
dplyr::summarise( |
366 | 2x |
h_format_row( |
367 | 2x |
x = sfun(.data[[y]], ...)[table], |
368 | 2x |
format = table_format, |
369 | 2x |
labels = table_labels |
370 |
), |
|
371 | 2x |
.groups = "drop" |
372 |
) |
|
373 | ||
374 | 2x |
stats_lev <- rev(setdiff(colnames(df_stats_table), c(group_var, x))) |
375 | ||
376 | 2x |
df_stats_table <- df_stats_table %>% |
377 | 2x |
tidyr::pivot_longer( |
378 | 2x |
cols = -dplyr::all_of(c(group_var, x)), |
379 | 2x |
names_to = "stat", |
380 | 2x |
values_to = "value", |
381 | 2x |
names_ptypes = list(stat = factor(levels = stats_lev)) |
382 |
) |
|
383 | ||
384 | 2x |
tbl <- ggplot2::ggplot( |
385 | 2x |
df_stats_table, |
386 | 2x |
ggplot2::aes(x = .data[[x]], y = .data[["stat"]], label = .data[["value"]]) |
387 |
) + |
|
388 | 2x |
ggplot2::geom_text(size = table_font_size) + |
389 | 2x |
ggplot2::theme_bw() + |
390 | 2x |
ggplot2::theme( |
391 | 2x |
panel.border = ggplot2::element_blank(), |
392 | 2x |
panel.grid.major = ggplot2::element_blank(), |
393 | 2x |
panel.grid.minor = ggplot2::element_blank(), |
394 | 2x |
axis.ticks = ggplot2::element_blank(), |
395 | 2x |
axis.title = ggplot2::element_blank(), |
396 | 2x |
axis.text.x = ggplot2::element_blank(), |
397 | 2x |
axis.text.y = ggplot2::element_text(margin = ggplot2::margin(t = 0, r = 0, b = 0, l = 5)), |
398 | 2x |
strip.text = ggplot2::element_text(hjust = 0), |
399 | 2x |
strip.text.x = ggplot2::element_text(margin = ggplot2::margin(1.5, 0, 1.5, 0, "pt")), |
400 | 2x |
strip.background = ggplot2::element_rect(fill = "grey95", color = NA), |
401 | 2x |
legend.position = "none" |
402 |
) |
|
403 | ||
404 | 2x |
if (!is.null(group_var)) { |
405 | 2x |
tbl <- tbl + ggplot2::facet_wrap(facets = group_var, ncol = 1) |
406 |
} |
|
407 | ||
408 |
# align plot and table |
|
409 | 2x |
cowplot::plot_grid(p, tbl, ncol = 1, align = "v", axis = "tblr") |
410 |
} else { |
|
411 | 1x |
p |
412 |
} |
|
413 |
} |
|
414 | ||
415 |
#' Helper function to get the right formatting in the optional table in `g_lineplot`. |
|
416 |
#' |
|
417 |
#' @description `r lifecycle::badge("stable")` |
|
418 |
#' |
|
419 |
#' @param x (named `list`)\cr list of numerical values to be formatted and optionally labeled. |
|
420 |
#' Elements of `x` must be `numeric` vectors. |
|
421 |
#' @param format (named `character` or `NULL`)\cr format patterns for `x`. Names of the `format` must |
|
422 |
#' match the names of `x`. This parameter is passed directly to the `rtables::format_rcell` |
|
423 |
#' function through the `format` parameter. |
|
424 |
#' @param labels (named `character` or `NULL`)\cr optional labels for `x`. Names of the `labels` must |
|
425 |
#' match the names of `x`. When a label is not specified for an element of `x`, |
|
426 |
#' then this function tries to use `label` or `names` (in this order) attribute of that element |
|
427 |
#' (depending on which one exists and it is not `NULL` or `NA` or `NaN`). If none of these attributes |
|
428 |
#' are attached to a given element of `x`, then the label is automatically generated. |
|
429 |
#' |
|
430 |
#' @return A single row `data.frame` object. |
|
431 |
#' |
|
432 |
#' @examples |
|
433 |
#' mean_ci <- c(48, 51) |
|
434 |
#' x <- list(mean = 50, mean_ci = mean_ci) |
|
435 |
#' format <- c(mean = "xx.x", mean_ci = "(xx.xx, xx.xx)") |
|
436 |
#' labels <- c(mean = "My Mean") |
|
437 |
#' h_format_row(x, format, labels) |
|
438 |
#' |
|
439 |
#' attr(mean_ci, "label") <- "Mean 95% CI" |
|
440 |
#' x <- list(mean = 50, mean_ci = mean_ci) |
|
441 |
#' h_format_row(x, format, labels) |
|
442 |
#' |
|
443 |
#' @export |
|
444 |
h_format_row <- function(x, format, labels = NULL) { |
|
445 |
# cell: one row, one column data.frame |
|
446 | 37x |
format_cell <- function(x, format, label = NULL) { |
447 | 110x |
fc <- format_rcell(x = x, format = unlist(format)) |
448 | 110x |
if (is.na(fc)) { |
449 | ! |
fc <- "NA" |
450 |
} |
|
451 | 110x |
x_label <- attr(x, "label") |
452 | 110x |
if (!is.null(label) && !is.na(label)) { |
453 | 109x |
names(fc) <- label |
454 | 1x |
} else if (!is.null(x_label) && !is.na(x_label)) { |
455 | ! |
names(fc) <- x_label |
456 | 1x |
} else if (length(x) == length(fc)) { |
457 | ! |
names(fc) <- names(x) |
458 |
} |
|
459 | 110x |
as.data.frame(t(fc)) |
460 |
} |
|
461 | ||
462 | 37x |
row <- do.call( |
463 | 37x |
cbind, |
464 | 37x |
lapply( |
465 | 37x |
names(x), function(xn) format_cell(x[[xn]], format = format[xn], label = labels[xn]) |
466 |
) |
|
467 |
) |
|
468 | ||
469 | 37x |
row |
470 |
} |
|
471 | ||
472 |
#' Control Function for `g_lineplot` Function |
|
473 |
#' |
|
474 |
#' @description `r lifecycle::badge("stable")` |
|
475 |
#' |
|
476 |
#' Default values for `variables` parameter in `g_lineplot` function. |
|
477 |
#' A variable's default value can be overwritten for any variable. |
|
478 |
#' |
|
479 |
#' @param x (`character`)\cr x variable name. |
|
480 |
#' @param y (`character`)\cr y variable name. |
|
481 |
#' @param group_var (`character` or `NA`)\cr group variable name. |
|
482 |
#' @param strata (`character` or `NA`)\cr deprecated - group variable name. |
|
483 |
#' @param subject_var (`character` or `NA`)\cr subject variable name. |
|
484 |
#' @param cohort_id (`character` or `NA`)\cr deprecated - subject variable name. |
|
485 |
#' @param paramcd (`character` or `NA`)\cr `paramcd` variable name. |
|
486 |
#' @param y_unit (`character` or `NA`)\cr `y_unit` variable name. |
|
487 |
#' |
|
488 |
#' @return A named character vector of variable names. |
|
489 |
#' |
|
490 |
#' @examples |
|
491 |
#' control_lineplot_vars() |
|
492 |
#' control_lineplot_vars(group_var = NA) |
|
493 |
#' |
|
494 |
#' @export |
|
495 |
control_lineplot_vars <- function(x = "AVISIT", y = "AVAL", group_var = "ARM", paramcd = "PARAMCD", y_unit = "AVALU", |
|
496 |
subject_var = "USUBJID", strata = lifecycle::deprecated(), |
|
497 |
cohort_id = lifecycle::deprecated()) { |
|
498 | 3x |
if (lifecycle::is_present(strata)) { |
499 | ! |
lifecycle::deprecate_warn("0.9.2", "control_lineplot_vars(strata)", "control_lineplot_vars(group_var)") |
500 | ! |
group_var <- strata |
501 |
} |
|
502 | ||
503 | 3x |
if (lifecycle::is_present(cohort_id)) { |
504 | ! |
lifecycle::deprecate_warn("0.9.2", "control_lineplot_vars(cohort_id)", "control_lineplot_vars(subject_id)") |
505 | ! |
subject_id <- cohort_id |
506 |
} |
|
507 | ||
508 | 3x |
checkmate::assert_string(x) |
509 | 3x |
checkmate::assert_string(y) |
510 | 3x |
checkmate::assert_string(group_var, na.ok = TRUE) |
511 | 3x |
checkmate::assert_string(subject_var, na.ok = TRUE) |
512 | 3x |
checkmate::assert_string(paramcd, na.ok = TRUE) |
513 | 3x |
checkmate::assert_string(y_unit, na.ok = TRUE) |
514 | ||
515 | 3x |
variables <- c(x = x, y = y, group_var = group_var, paramcd = paramcd, y_unit = y_unit, subject_var = subject_var) |
516 | 3x |
return(variables) |
517 |
} |
1 |
#' Multivariate Logistic Regression Table |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Layout-creating function which summarizes a logistic variable regression for binary outcome with |
|
6 |
#' categorical/continuous covariates in model statement. For each covariate category (if categorical) |
|
7 |
#' or specified values (if continuous), present degrees of freedom, regression parameter estimate and |
|
8 |
#' standard error (SE) relative to reference group or category. Report odds ratios for each covariate |
|
9 |
#' category or specified values and corresponding Wald confidence intervals as default but allow user |
|
10 |
#' to specify other confidence levels. Report p-value for Wald chi-square test of the null hypothesis |
|
11 |
#' that covariate has no effect on response in model containing all specified covariates. |
|
12 |
#' Allow option to include one two-way interaction and present similar output for |
|
13 |
#' each interaction degree of freedom. |
|
14 |
#' |
|
15 |
#' @inheritParams argument_convention |
|
16 |
#' @param drop_and_remove_str (`character`)\cr string to be dropped and removed. |
|
17 |
#' |
|
18 |
#' @return A layout object suitable for passing to further layouting functions, or to [rtables::build_table()]. |
|
19 |
#' Adding this function to an `rtable` layout will add a logistic regression variable summary to the table layout. |
|
20 |
#' |
|
21 |
#' @note For the formula, the variable names need to be standard `data.frame` column names without |
|
22 |
#' special characters. |
|
23 |
#' |
|
24 |
#' @examples |
|
25 |
#' library(dplyr) |
|
26 |
#' library(broom) |
|
27 |
#' |
|
28 |
#' adrs_f <- tern_ex_adrs %>% |
|
29 |
#' filter(PARAMCD == "BESRSPI") %>% |
|
30 |
#' filter(RACE %in% c("ASIAN", "WHITE", "BLACK OR AFRICAN AMERICAN")) %>% |
|
31 |
#' mutate( |
|
32 |
#' Response = case_when(AVALC %in% c("PR", "CR") ~ 1, TRUE ~ 0), |
|
33 |
#' RACE = factor(RACE), |
|
34 |
#' SEX = factor(SEX) |
|
35 |
#' ) |
|
36 |
#' formatters::var_labels(adrs_f) <- c(formatters::var_labels(tern_ex_adrs), Response = "Response") |
|
37 |
#' mod1 <- fit_logistic( |
|
38 |
#' data = adrs_f, |
|
39 |
#' variables = list( |
|
40 |
#' response = "Response", |
|
41 |
#' arm = "ARMCD", |
|
42 |
#' covariates = c("AGE", "RACE") |
|
43 |
#' ) |
|
44 |
#' ) |
|
45 |
#' mod2 <- fit_logistic( |
|
46 |
#' data = adrs_f, |
|
47 |
#' variables = list( |
|
48 |
#' response = "Response", |
|
49 |
#' arm = "ARMCD", |
|
50 |
#' covariates = c("AGE", "RACE"), |
|
51 |
#' interaction = "AGE" |
|
52 |
#' ) |
|
53 |
#' ) |
|
54 |
#' |
|
55 |
#' df <- tidy(mod1, conf_level = 0.99) |
|
56 |
#' df2 <- tidy(mod2, conf_level = 0.99) |
|
57 |
#' |
|
58 |
#' # flagging empty strings with "_" |
|
59 |
#' df <- df_explicit_na(df, na_level = "_") |
|
60 |
#' df2 <- df_explicit_na(df2, na_level = "_") |
|
61 |
#' |
|
62 |
#' result1 <- basic_table() %>% |
|
63 |
#' summarize_logistic( |
|
64 |
#' conf_level = 0.95, |
|
65 |
#' drop_and_remove_str = "_" |
|
66 |
#' ) %>% |
|
67 |
#' build_table(df = df) |
|
68 |
#' result1 |
|
69 |
#' |
|
70 |
#' result2 <- basic_table() %>% |
|
71 |
#' summarize_logistic( |
|
72 |
#' conf_level = 0.95, |
|
73 |
#' drop_and_remove_str = "_" |
|
74 |
#' ) %>% |
|
75 |
#' build_table(df = df2) |
|
76 |
#' result2 |
|
77 |
#' |
|
78 |
#' @export |
|
79 |
#' @order 1 |
|
80 |
summarize_logistic <- function(lyt, |
|
81 |
conf_level, |
|
82 |
drop_and_remove_str = "", |
|
83 |
.indent_mods = NULL) { |
|
84 |
# checks |
|
85 | 3x |
checkmate::assert_string(drop_and_remove_str) |
86 | ||
87 | 3x |
sum_logistic_variable_test <- logistic_summary_by_flag("is_variable_summary") |
88 | 3x |
sum_logistic_term_estimates <- logistic_summary_by_flag("is_term_summary", .indent_mods = .indent_mods) |
89 | 3x |
sum_logistic_odds_ratios <- logistic_summary_by_flag("is_reference_summary", .indent_mods = .indent_mods) |
90 | 3x |
split_fun <- drop_and_remove_levels(drop_and_remove_str) |
91 | ||
92 | 3x |
lyt <- logistic_regression_cols(lyt, conf_level = conf_level) |
93 | 3x |
lyt <- split_rows_by(lyt, var = "variable", labels_var = "variable_label", split_fun = split_fun) |
94 | 3x |
lyt <- sum_logistic_variable_test(lyt) |
95 | 3x |
lyt <- split_rows_by(lyt, var = "term", labels_var = "term_label", split_fun = split_fun) |
96 | 3x |
lyt <- sum_logistic_term_estimates(lyt) |
97 | 3x |
lyt <- split_rows_by(lyt, var = "interaction", labels_var = "interaction_label", split_fun = split_fun) |
98 | 3x |
lyt <- split_rows_by(lyt, var = "reference", labels_var = "reference_label", split_fun = split_fun) |
99 | 3x |
lyt <- sum_logistic_odds_ratios(lyt) |
100 | 3x |
lyt |
101 |
} |
|
102 | ||
103 |
#' Fit for Logistic Regression |
|
104 |
#' |
|
105 |
#' @description `r lifecycle::badge("stable")` |
|
106 |
#' |
|
107 |
#' Fit a (conditional) logistic regression model. |
|
108 |
#' |
|
109 |
#' @inheritParams argument_convention |
|
110 |
#' @param data (`data.frame`)\cr the data frame on which the model was fit. |
|
111 |
#' @param response_definition (`string`)\cr the definition of what an event is in terms of `response`. |
|
112 |
#' This will be used when fitting the (conditional) logistic regression model on the left hand |
|
113 |
#' side of the formula. |
|
114 |
#' |
|
115 |
#' @return A fitted logistic regression model. |
|
116 |
#' |
|
117 |
#' @section Model Specification: |
|
118 |
#' |
|
119 |
#' The `variables` list needs to include the following elements: |
|
120 |
#' * `arm`: Treatment arm variable name. |
|
121 |
#' * `response`: The response arm variable name. Usually this is a 0/1 variable. |
|
122 |
#' * `covariates`: This is either `NULL` (no covariates) or a character vector of covariate variable names. |
|
123 |
#' * `interaction`: This is either `NULL` (no interaction) or a string of a single covariate variable name already |
|
124 |
#' included in `covariates`. Then the interaction with the treatment arm is included in the model. |
|
125 |
#' |
|
126 |
#' @examples |
|
127 |
#' library(dplyr) |
|
128 |
#' |
|
129 |
#' adrs_f <- tern_ex_adrs %>% |
|
130 |
#' filter(PARAMCD == "BESRSPI") %>% |
|
131 |
#' filter(RACE %in% c("ASIAN", "WHITE", "BLACK OR AFRICAN AMERICAN")) %>% |
|
132 |
#' mutate( |
|
133 |
#' Response = case_when(AVALC %in% c("PR", "CR") ~ 1, TRUE ~ 0), |
|
134 |
#' RACE = factor(RACE), |
|
135 |
#' SEX = factor(SEX) |
|
136 |
#' ) |
|
137 |
#' formatters::var_labels(adrs_f) <- c(formatters::var_labels(tern_ex_adrs), Response = "Response") |
|
138 |
#' mod1 <- fit_logistic( |
|
139 |
#' data = adrs_f, |
|
140 |
#' variables = list( |
|
141 |
#' response = "Response", |
|
142 |
#' arm = "ARMCD", |
|
143 |
#' covariates = c("AGE", "RACE") |
|
144 |
#' ) |
|
145 |
#' ) |
|
146 |
#' mod2 <- fit_logistic( |
|
147 |
#' data = adrs_f, |
|
148 |
#' variables = list( |
|
149 |
#' response = "Response", |
|
150 |
#' arm = "ARMCD", |
|
151 |
#' covariates = c("AGE", "RACE"), |
|
152 |
#' interaction = "AGE" |
|
153 |
#' ) |
|
154 |
#' ) |
|
155 |
#' |
|
156 |
#' @export |
|
157 |
fit_logistic <- function(data, |
|
158 |
variables = list( |
|
159 |
response = "Response", |
|
160 |
arm = "ARMCD", |
|
161 |
covariates = NULL, |
|
162 |
interaction = NULL, |
|
163 |
strata = NULL |
|
164 |
), |
|
165 |
response_definition = "response") { |
|
166 | 74x |
assert_df_with_variables(data, variables) |
167 | 74x |
checkmate::assert_subset(names(variables), c("response", "arm", "covariates", "interaction", "strata")) |
168 | 74x |
checkmate::assert_string(response_definition) |
169 | 74x |
checkmate::assert_true(grepl("response", response_definition)) |
170 | ||
171 | 74x |
response_definition <- sub( |
172 | 74x |
pattern = "response", |
173 | 74x |
replacement = variables$response, |
174 | 74x |
x = response_definition, |
175 | 74x |
fixed = TRUE |
176 |
) |
|
177 | 74x |
form <- paste0(response_definition, " ~ ", variables$arm) |
178 | 74x |
if (!is.null(variables$covariates)) { |
179 | 28x |
form <- paste0(form, " + ", paste(variables$covariates, collapse = " + ")) |
180 |
} |
|
181 | 74x |
if (!is.null(variables$interaction)) { |
182 | 17x |
checkmate::assert_string(variables$interaction) |
183 | 17x |
checkmate::assert_subset(variables$interaction, variables$covariates) |
184 | 17x |
form <- paste0(form, " + ", variables$arm, ":", variables$interaction) |
185 |
} |
|
186 | 74x |
if (!is.null(variables$strata)) { |
187 | 14x |
strata_arg <- if (length(variables$strata) > 1) { |
188 | 7x |
paste0("I(interaction(", paste0(variables$strata, collapse = ", "), "))") |
189 |
} else { |
|
190 | 7x |
variables$strata |
191 |
} |
|
192 | 14x |
form <- paste0(form, "+ strata(", strata_arg, ")") |
193 |
} |
|
194 | 74x |
formula <- stats::as.formula(form) |
195 | 74x |
if (is.null(variables$strata)) { |
196 | 60x |
stats::glm( |
197 | 60x |
formula = formula, |
198 | 60x |
data = data, |
199 | 60x |
family = stats::binomial("logit") |
200 |
) |
|
201 |
} else { |
|
202 | 14x |
clogit_with_tryCatch( |
203 | 14x |
formula = formula, |
204 | 14x |
data = data, |
205 | 14x |
x = TRUE |
206 |
) |
|
207 |
} |
|
208 |
} |
|
209 | ||
210 |
#' Custom Tidy Method for Binomial GLM Results |
|
211 |
#' |
|
212 |
#' @description `r lifecycle::badge("stable")` |
|
213 |
#' |
|
214 |
#' Helper method (for [broom::tidy()]) to prepare a data frame from a `glm` object |
|
215 |
#' with `binomial` family. |
|
216 |
#' |
|
217 |
#' @inheritParams argument_convention |
|
218 |
#' @param at (`NULL` or `numeric`)\cr optional values for the interaction variable. Otherwise the median is used. |
|
219 |
#' @param x logistic regression model fitted by [stats::glm()] with "binomial" family. |
|
220 |
#' |
|
221 |
#' @return A `data.frame` containing the tidied model. |
|
222 |
#' |
|
223 |
#' @method tidy glm |
|
224 |
#' |
|
225 |
#' @seealso [h_logistic_regression] for relevant helper functions. |
|
226 |
#' |
|
227 |
#' @examples |
|
228 |
#' library(dplyr) |
|
229 |
#' library(broom) |
|
230 |
#' |
|
231 |
#' adrs_f <- tern_ex_adrs %>% |
|
232 |
#' filter(PARAMCD == "BESRSPI") %>% |
|
233 |
#' filter(RACE %in% c("ASIAN", "WHITE", "BLACK OR AFRICAN AMERICAN")) %>% |
|
234 |
#' mutate( |
|
235 |
#' Response = case_when(AVALC %in% c("PR", "CR") ~ 1, TRUE ~ 0), |
|
236 |
#' RACE = factor(RACE), |
|
237 |
#' SEX = factor(SEX) |
|
238 |
#' ) |
|
239 |
#' formatters::var_labels(adrs_f) <- c(formatters::var_labels(tern_ex_adrs), Response = "Response") |
|
240 |
#' mod1 <- fit_logistic( |
|
241 |
#' data = adrs_f, |
|
242 |
#' variables = list( |
|
243 |
#' response = "Response", |
|
244 |
#' arm = "ARMCD", |
|
245 |
#' covariates = c("AGE", "RACE") |
|
246 |
#' ) |
|
247 |
#' ) |
|
248 |
#' mod2 <- fit_logistic( |
|
249 |
#' data = adrs_f, |
|
250 |
#' variables = list( |
|
251 |
#' response = "Response", |
|
252 |
#' arm = "ARMCD", |
|
253 |
#' covariates = c("AGE", "RACE"), |
|
254 |
#' interaction = "AGE" |
|
255 |
#' ) |
|
256 |
#' ) |
|
257 |
#' |
|
258 |
#' df <- tidy(mod1, conf_level = 0.99) |
|
259 |
#' df2 <- tidy(mod2, conf_level = 0.99) |
|
260 |
#' |
|
261 |
#' @export |
|
262 |
tidy.glm <- function(x, # nolint |
|
263 |
conf_level = 0.95, |
|
264 |
at = NULL, |
|
265 |
...) { |
|
266 | 5x |
checkmate::assert_class(x, "glm") |
267 | 5x |
checkmate::assert_set_equal(x$family$family, "binomial") |
268 | ||
269 | 5x |
terms_name <- attr(stats::terms(x), "term.labels") |
270 | 5x |
xs_class <- attr(x$terms, "dataClasses") |
271 | 5x |
interaction <- terms_name[which(!terms_name %in% names(xs_class))] |
272 | 5x |
df <- if (length(interaction) == 0) { |
273 | 2x |
h_logistic_simple_terms( |
274 | 2x |
x = terms_name, |
275 | 2x |
fit_glm = x, |
276 | 2x |
conf_level = conf_level |
277 |
) |
|
278 |
} else { |
|
279 | 3x |
h_logistic_inter_terms( |
280 | 3x |
x = terms_name, |
281 | 3x |
fit_glm = x, |
282 | 3x |
conf_level = conf_level, |
283 | 3x |
at = at |
284 |
) |
|
285 |
} |
|
286 | 5x |
for (var in c("variable", "term", "interaction", "reference")) { |
287 | 20x |
df[[var]] <- factor(df[[var]], levels = unique(df[[var]])) |
288 |
} |
|
289 | 5x |
df |
290 |
} |
|
291 | ||
292 |
#' Logistic Regression Multivariate Column Layout Function |
|
293 |
#' |
|
294 |
#' @description `r lifecycle::badge("stable")` |
|
295 |
#' |
|
296 |
#' Layout-creating function which creates a multivariate column layout summarizing logistic |
|
297 |
#' regression results. This function is a wrapper for [rtables::split_cols_by_multivar()]. |
|
298 |
#' |
|
299 |
#' @inheritParams argument_convention |
|
300 |
#' |
|
301 |
#' @return A layout object suitable for passing to further layouting functions. Adding this |
|
302 |
#' function to an `rtable` layout will split the table into columns corresponding to |
|
303 |
#' statistics `df`, `estimate`, `std_error`, `odds_ratio`, `ci`, and `pvalue`. |
|
304 |
#' |
|
305 |
#' @export |
|
306 |
logistic_regression_cols <- function(lyt, |
|
307 |
conf_level = 0.95) { |
|
308 | 4x |
vars <- c("df", "estimate", "std_error", "odds_ratio", "ci", "pvalue") |
309 | 4x |
var_labels <- c( |
310 | 4x |
df = "Degrees of Freedom", |
311 | 4x |
estimate = "Parameter Estimate", |
312 | 4x |
std_error = "Standard Error", |
313 | 4x |
odds_ratio = "Odds Ratio", |
314 | 4x |
ci = paste("Wald", f_conf_level(conf_level)), |
315 | 4x |
pvalue = "p-value" |
316 |
) |
|
317 | 4x |
split_cols_by_multivar( |
318 | 4x |
lyt = lyt, |
319 | 4x |
vars = vars, |
320 | 4x |
varlabels = var_labels |
321 |
) |
|
322 |
} |
|
323 | ||
324 |
#' Logistic Regression Summary Table Constructor Function |
|
325 |
#' |
|
326 |
#' @description `r lifecycle::badge("stable")` |
|
327 |
#' |
|
328 |
#' Constructor for content functions to be used in [`summarize_logistic()`] to summarize |
|
329 |
#' logistic regression results. This function is a wrapper for [rtables::summarize_row_groups()]. |
|
330 |
#' |
|
331 |
#' @inheritParams argument_convention |
|
332 |
#' @param flag_var (`string`)\cr variable name identifying which row should be used in this |
|
333 |
#' content function. |
|
334 |
#' |
|
335 |
#' @return A content function. |
|
336 |
#' |
|
337 |
#' @export |
|
338 |
logistic_summary_by_flag <- function(flag_var, na_str = default_na_str(), .indent_mods = NULL) { |
|
339 | 10x |
checkmate::assert_string(flag_var) |
340 | 10x |
function(lyt) { |
341 | 10x |
cfun_list <- list( |
342 | 10x |
df = cfun_by_flag("df", flag_var, format = "xx.", .indent_mods = .indent_mods), |
343 | 10x |
estimate = cfun_by_flag("estimate", flag_var, format = "xx.xxx", .indent_mods = .indent_mods), |
344 | 10x |
std_error = cfun_by_flag("std_error", flag_var, format = "xx.xxx", .indent_mods = .indent_mods), |
345 | 10x |
odds_ratio = cfun_by_flag("odds_ratio", flag_var, format = ">999.99", .indent_mods = .indent_mods), |
346 | 10x |
ci = cfun_by_flag("ci", flag_var, format = format_extreme_values_ci(2L), .indent_mods = .indent_mods), |
347 | 10x |
pvalue = cfun_by_flag("pvalue", flag_var, format = "x.xxxx | (<0.0001)", .indent_mods = .indent_mods) |
348 |
) |
|
349 | 10x |
summarize_row_groups( |
350 | 10x |
lyt = lyt, |
351 | 10x |
cfun = cfun_list, |
352 | 10x |
na_str = na_str |
353 |
) |
|
354 |
} |
|
355 |
} |
1 |
#' Combination Functions Class |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' `CombinationFunction` is an S4 class which extends standard functions. These are special functions that |
|
6 |
#' can be combined and negated with the logical operators. |
|
7 |
#' |
|
8 |
#' @param e1 (`CombinationFunction`)\cr left hand side of logical operator. |
|
9 |
#' @param e2 (`CombinationFunction`)\cr right hand side of logical operator. |
|
10 |
#' @param x (`CombinationFunction`)\cr the function which should be negated. |
|
11 |
#' |
|
12 |
#' @return Returns a logical value indicating whether the left hand side of the equation equals the right hand side. |
|
13 |
#' |
|
14 |
#' @exportClass CombinationFunction |
|
15 |
#' @export CombinationFunction |
|
16 |
#' |
|
17 |
#' @examples |
|
18 |
#' higher <- function(a) { |
|
19 |
#' force(a) |
|
20 |
#' CombinationFunction( |
|
21 |
#' function(x) { |
|
22 |
#' x > a |
|
23 |
#' } |
|
24 |
#' ) |
|
25 |
#' } |
|
26 |
#' |
|
27 |
#' lower <- function(b) { |
|
28 |
#' force(b) |
|
29 |
#' CombinationFunction( |
|
30 |
#' function(x) { |
|
31 |
#' x < b |
|
32 |
#' } |
|
33 |
#' ) |
|
34 |
#' } |
|
35 |
#' |
|
36 |
#' c1 <- higher(5) |
|
37 |
#' c2 <- lower(10) |
|
38 |
#' c3 <- higher(5) & lower(10) |
|
39 |
#' c3(7) |
|
40 |
#' |
|
41 |
#' @aliases CombinationFunction-class |
|
42 |
#' @name combination_function |
|
43 |
CombinationFunction <- methods::setClass("CombinationFunction", contains = "function") # nolint |
|
44 | ||
45 |
#' @describeIn combination_function Logical "AND" combination of `CombinationFunction` functions. |
|
46 |
#' The resulting object is of the same class, and evaluates the two argument functions. The result |
|
47 |
#' is then the "AND" of the two individual results. |
|
48 |
#' |
|
49 |
#' @export |
|
50 |
methods::setMethod( |
|
51 |
"&", |
|
52 |
signature = c(e1 = "CombinationFunction", e2 = "CombinationFunction"), |
|
53 |
definition = function(e1, e2) { |
|
54 | 4x |
CombinationFunction(function(...) { |
55 | 490x |
e1(...) && e2(...) |
56 |
}) |
|
57 |
} |
|
58 |
) |
|
59 | ||
60 |
#' @describeIn combination_function Logical "OR" combination of `CombinationFunction` functions. |
|
61 |
#' The resulting object is of the same class, and evaluates the two argument functions. The result |
|
62 |
#' is then the "OR" of the two individual results. |
|
63 |
#' |
|
64 |
#' @export |
|
65 |
methods::setMethod( |
|
66 |
"|", |
|
67 |
signature = c(e1 = "CombinationFunction", e2 = "CombinationFunction"), |
|
68 |
definition = function(e1, e2) { |
|
69 | 2x |
CombinationFunction(function(...) { |
70 | 4x |
e1(...) || e2(...) |
71 |
}) |
|
72 |
} |
|
73 |
) |
|
74 | ||
75 |
#' @describeIn combination_function Logical negation of `CombinationFunction` functions. |
|
76 |
#' The resulting object is of the same class, and evaluates the original function. The result |
|
77 |
#' is then the opposite of this results. |
|
78 |
#' |
|
79 |
#' @export |
|
80 |
methods::setMethod( |
|
81 |
"!", |
|
82 |
signature = c(x = "CombinationFunction"), |
|
83 |
definition = function(x) { |
|
84 | 2x |
CombinationFunction(function(...) { |
85 | 305x |
!x(...) |
86 |
}) |
|
87 |
} |
|
88 |
) |
1 |
#' Helper Function to create a map dataframe that can be used in `trim_levels_to_map` split function. |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Helper Function to create a map dataframe from the input dataset, which can be used as an argument in the |
|
6 |
#' `trim_levels_to_map` split function. Based on different method, the map is constructed differently. |
|
7 |
#' |
|
8 |
#' @inheritParams argument_convention |
|
9 |
#' @param abnormal (named `list`)\cr identifying the abnormal range level(s) in `df`. Based on the levels of |
|
10 |
#' abnormality of the input dataset, it can be something like `list(Low = "LOW LOW", High = "HIGH HIGH")` or |
|
11 |
#' `abnormal = list(Low = "LOW", High = "HIGH"))` |
|
12 |
#' @param method (`string`)\cr indicates how the returned map will be constructed. Can be `"default"` or `"range"`. |
|
13 |
#' |
|
14 |
#' @return A map `data.frame`. |
|
15 |
#' |
|
16 |
#' @note If method is `"default"`, the returned map will only have the abnormal directions that are observed in the |
|
17 |
#' `df`, and records with all normal values will be excluded to avoid error in creating layout. If method is |
|
18 |
#' `"range"`, the returned map will be based on the rule that at least one observation with low range > 0 |
|
19 |
#' for low direction and at least one observation with high range is not missing for high direction. |
|
20 |
#' |
|
21 |
#' @examples |
|
22 |
#' adlb <- df_explicit_na(tern_ex_adlb) |
|
23 |
#' |
|
24 |
#' h_map_for_count_abnormal( |
|
25 |
#' df = adlb, |
|
26 |
#' variables = list(anl = "ANRIND", split_rows = c("LBCAT", "PARAM")), |
|
27 |
#' abnormal = list(low = c("LOW"), high = c("HIGH")), |
|
28 |
#' method = "default", |
|
29 |
#' na_str = "<Missing>" |
|
30 |
#' ) |
|
31 |
#' |
|
32 |
#' df <- data.frame( |
|
33 |
#' USUBJID = c(rep("1", 4), rep("2", 4), rep("3", 4)), |
|
34 |
#' AVISIT = c( |
|
35 |
#' rep("WEEK 1", 2), |
|
36 |
#' rep("WEEK 2", 2), |
|
37 |
#' rep("WEEK 1", 2), |
|
38 |
#' rep("WEEK 2", 2), |
|
39 |
#' rep("WEEK 1", 2), |
|
40 |
#' rep("WEEK 2", 2) |
|
41 |
#' ), |
|
42 |
#' PARAM = rep(c("ALT", "CPR"), 6), |
|
43 |
#' ANRIND = c( |
|
44 |
#' "NORMAL", "NORMAL", "LOW", |
|
45 |
#' "HIGH", "LOW", "LOW", "HIGH", "HIGH", rep("NORMAL", 4) |
|
46 |
#' ), |
|
47 |
#' ANRLO = rep(5, 12), |
|
48 |
#' ANRHI = rep(20, 12) |
|
49 |
#' ) |
|
50 |
#' df$ANRIND <- factor(df$ANRIND, levels = c("LOW", "HIGH", "NORMAL")) |
|
51 |
#' h_map_for_count_abnormal( |
|
52 |
#' df = df, |
|
53 |
#' variables = list( |
|
54 |
#' anl = "ANRIND", |
|
55 |
#' split_rows = c("PARAM"), |
|
56 |
#' range_low = "ANRLO", |
|
57 |
#' range_high = "ANRHI" |
|
58 |
#' ), |
|
59 |
#' abnormal = list(low = c("LOW"), high = c("HIGH")), |
|
60 |
#' method = "range", |
|
61 |
#' na_str = "<Missing>" |
|
62 |
#' ) |
|
63 |
#' |
|
64 |
#' @export |
|
65 |
h_map_for_count_abnormal <- function(df, |
|
66 |
variables = list( |
|
67 |
anl = "ANRIND", |
|
68 |
split_rows = c("PARAM"), |
|
69 |
range_low = "ANRLO", |
|
70 |
range_high = "ANRHI" |
|
71 |
), |
|
72 |
abnormal = list(low = c("LOW", "LOW LOW"), high = c("HIGH", "HIGH HIGH")), |
|
73 |
method = c("default", "range"), |
|
74 |
na_level = lifecycle::deprecated(), |
|
75 |
na_str = "<Missing>") { |
|
76 | 7x |
if (lifecycle::is_present(na_level)) { |
77 | ! |
lifecycle::deprecate_warn("0.9.1", "h_map_for_count_abnormal(na_level)", "h_map_for_count_abnormal(na_str)") |
78 | ! |
na_str <- na_level |
79 |
} |
|
80 | ||
81 | 7x |
method <- match.arg(method) |
82 | 7x |
checkmate::assert_subset(c("anl", "split_rows"), names(variables)) |
83 | 7x |
checkmate::assert_false(anyNA(df[variables$split_rows])) |
84 | 7x |
assert_df_with_variables(df, |
85 | 7x |
variables = list(anl = variables$anl, split_rows = variables$split_rows), |
86 | 7x |
na_level = na_str |
87 |
) |
|
88 | 7x |
assert_df_with_factors(df, list(val = variables$anl)) |
89 | 7x |
assert_valid_factor(df[[variables$anl]], any.missing = FALSE) |
90 | 7x |
assert_list_of_variables(variables) |
91 | 7x |
checkmate::assert_list(abnormal, types = "character", len = 2) |
92 | ||
93 |
# Drop usued levels from df as they are not supposed to be in the final map |
|
94 | 7x |
df <- droplevels(df) |
95 | ||
96 | 7x |
normal_value <- setdiff(levels(df[[variables$anl]]), unlist(abnormal)) |
97 | ||
98 |
# Based on the understanding of clinical data, there should only be one level of normal which is "NORMAL" |
|
99 | 7x |
checkmate::assert_vector(normal_value, len = 1) |
100 | ||
101 |
# Default method will only have what is observed in the df, and records with all normal values will be excluded to |
|
102 |
# avoid error in layout building. |
|
103 | 7x |
if (method == "default") { |
104 | 3x |
df_abnormal <- subset(df, df[[variables$anl]] %in% unlist(abnormal)) |
105 | 3x |
map <- unique(df_abnormal[c(variables$split_rows, variables$anl)]) |
106 | 3x |
map_normal <- unique(subset(map, select = variables$split_rows)) |
107 | 3x |
map_normal[[variables$anl]] <- normal_value |
108 | 3x |
map <- rbind(map, map_normal) |
109 | 4x |
} else if (method == "range") { |
110 |
# range method follows the rule that at least one observation with ANRLO > 0 for low |
|
111 |
# direction and at least one observation with ANRHI is not missing for high direction. |
|
112 | 4x |
checkmate::assert_subset(c("range_low", "range_high"), names(variables)) |
113 | 4x |
checkmate::assert_subset(c("LOW", "HIGH"), toupper(names(abnormal))) |
114 | ||
115 | 4x |
assert_df_with_variables(df, |
116 | 4x |
variables = list( |
117 | 4x |
range_low = variables$range_low, |
118 | 4x |
range_high = variables$range_high |
119 |
) |
|
120 |
) |
|
121 | ||
122 |
# Define low direction of map |
|
123 | 4x |
df_low <- subset(df, df[[variables$range_low]] > 0) |
124 | 4x |
map_low <- unique(df_low[variables$split_rows]) |
125 | 4x |
low_levels <- unname(unlist(abnormal[toupper(names(abnormal)) == "LOW"])) |
126 | 4x |
low_levels_df <- as.data.frame(low_levels) |
127 | 4x |
colnames(low_levels_df) <- variables$anl |
128 | 4x |
low_levels_df <- do.call("rbind", replicate(nrow(map_low), low_levels_df, simplify = FALSE)) |
129 | 4x |
rownames(map_low) <- NULL # Just to avoid strange row index in case upstream functions changed |
130 | 4x |
map_low <- map_low[rep(seq_len(nrow(map_low)), each = length(low_levels)), , drop = FALSE] |
131 | 4x |
map_low <- cbind(map_low, low_levels_df) |
132 | ||
133 |
# Define high direction of map |
|
134 | 4x |
df_high <- subset(df, df[[variables$range_high]] != na_str | !is.na(df[[variables$range_high]])) |
135 | 4x |
map_high <- unique(df_high[variables$split_rows]) |
136 | 4x |
high_levels <- unname(unlist(abnormal[toupper(names(abnormal)) == "HIGH"])) |
137 | 4x |
high_levels_df <- as.data.frame(high_levels) |
138 | 4x |
colnames(high_levels_df) <- variables$anl |
139 | 4x |
high_levels_df <- do.call("rbind", replicate(nrow(map_high), high_levels_df, simplify = FALSE)) |
140 | 4x |
rownames(map_high) <- NULL |
141 | 4x |
map_high <- map_high[rep(seq_len(nrow(map_high)), each = length(high_levels)), , drop = FALSE] |
142 | 4x |
map_high <- cbind(map_high, high_levels_df) |
143 | ||
144 |
# Define normal of map |
|
145 | 4x |
map_normal <- unique(rbind(map_low, map_high)[variables$split_rows]) |
146 | 4x |
map_normal[variables$anl] <- normal_value |
147 | ||
148 | 4x |
map <- rbind(map_low, map_high, map_normal) |
149 |
} |
|
150 | ||
151 |
# map should be all characters |
|
152 | 7x |
map <- data.frame(lapply(map, as.character), stringsAsFactors = FALSE) |
153 | ||
154 |
# sort the map final output by split_rows variables |
|
155 | 7x |
for (i in rev(seq_len(length(variables$split_rows)))) { |
156 | 7x |
map <- map[order(map[[i]]), ] |
157 |
} |
|
158 | 7x |
map |
159 |
} |
1 |
#' Create a Forest Plot based on a Table |
|
2 |
#' |
|
3 |
#' Create a forest plot from any [rtables::rtable()] object that has a |
|
4 |
#' column with a single value and a column with 2 values. |
|
5 |
#' |
|
6 |
#' @description `r lifecycle::badge("stable")` |
|
7 |
#' |
|
8 |
#' @inheritParams grid::gTree |
|
9 |
#' @inheritParams argument_convention |
|
10 |
#' @param tbl (`rtable`) |
|
11 |
#' @param col_x (`integer`)\cr column index with estimator. By default tries to get this from |
|
12 |
#' `tbl` attribute `col_x`, otherwise needs to be manually specified. |
|
13 |
#' @param col_ci (`integer`)\cr column index with confidence intervals. By default tries |
|
14 |
#' to get this from `tbl` attribute `col_ci`, otherwise needs to be manually specified. |
|
15 |
#' @param vline (`number`)\cr x coordinate for vertical line, if `NULL` then the line is omitted. |
|
16 |
#' @param forest_header (`character`, length 2)\cr text displayed to the left and right of `vline`, respectively. |
|
17 |
#' If `vline = NULL` then `forest_header` needs to be `NULL` too. |
|
18 |
#' By default tries to get this from `tbl` attribute `forest_header`. |
|
19 |
#' @param xlim (`numeric`)\cr limits for x axis. |
|
20 |
#' @param logx (`flag`)\cr show the x-values on logarithm scale. |
|
21 |
#' @param x_at (`numeric`)\cr x-tick locations, if `NULL` they get automatically chosen. |
|
22 |
#' @param width_row_names (`unit`)\cr width for row names. |
|
23 |
#' If `NULL` the widths get automatically calculated. See [grid::unit()]. |
|
24 |
#' @param width_columns (`unit`)\cr widths for the table columns. |
|
25 |
#' If `NULL` the widths get automatically calculated. See [grid::unit()]. |
|
26 |
#' @param width_forest (`unit`)\cr width for the forest column. |
|
27 |
#' If `NULL` the widths get automatically calculated. See [grid::unit()]. |
|
28 |
#' @param col_symbol_size (`integer`)\cr column index from `tbl` containing data to be used |
|
29 |
#' to determine relative size for estimator plot symbol. Typically, the symbol size is proportional |
|
30 |
#' to the sample size used to calculate the estimator. If `NULL`, the same symbol size is used for all subgroups. |
|
31 |
#' By default tries to get this from `tbl` attribute `col_symbol_size`, otherwise needs to be manually specified. |
|
32 |
#' @param col (`character`)\cr color(s). |
|
33 |
#' |
|
34 |
#' @return `gTree` object containing the forest plot and table. |
|
35 |
#' |
|
36 |
#' @examples |
|
37 |
#' \donttest{ |
|
38 |
#' library(dplyr) |
|
39 |
#' library(forcats) |
|
40 |
#' library(nestcolor) |
|
41 |
#' |
|
42 |
#' adrs <- tern_ex_adrs |
|
43 |
#' n_records <- 20 |
|
44 |
#' adrs_labels <- formatters::var_labels(adrs, fill = TRUE) |
|
45 |
#' adrs <- adrs %>% |
|
46 |
#' filter(PARAMCD == "BESRSPI") %>% |
|
47 |
#' filter(ARM %in% c("A: Drug X", "B: Placebo")) %>% |
|
48 |
#' slice(seq_len(n_records)) %>% |
|
49 |
#' droplevels() %>% |
|
50 |
#' mutate( |
|
51 |
#' # Reorder levels of factor to make the placebo group the reference arm. |
|
52 |
#' ARM = fct_relevel(ARM, "B: Placebo"), |
|
53 |
#' rsp = AVALC == "CR" |
|
54 |
#' ) |
|
55 |
#' formatters::var_labels(adrs) <- c(adrs_labels, "Response") |
|
56 |
#' df <- extract_rsp_subgroups( |
|
57 |
#' variables = list(rsp = "rsp", arm = "ARM", subgroups = c("SEX", "STRATA2")), |
|
58 |
#' data = adrs |
|
59 |
#' ) |
|
60 |
#' # Full commonly used response table. |
|
61 |
#' |
|
62 |
#' tbl <- basic_table() %>% |
|
63 |
#' tabulate_rsp_subgroups(df) |
|
64 |
#' p <- g_forest(tbl, gp = grid::gpar(fontsize = 10)) |
|
65 |
#' |
|
66 |
#' draw_grob(p) |
|
67 |
#' |
|
68 |
#' # Odds ratio only table. |
|
69 |
#' |
|
70 |
#' tbl_or <- basic_table() %>% |
|
71 |
#' tabulate_rsp_subgroups(df, vars = c("n_tot", "or", "ci")) |
|
72 |
#' tbl_or |
|
73 |
#' p <- g_forest( |
|
74 |
#' tbl_or, |
|
75 |
#' forest_header = c("Comparison\nBetter", "Treatment\nBetter") |
|
76 |
#' ) |
|
77 |
#' |
|
78 |
#' draw_grob(p) |
|
79 |
#' |
|
80 |
#' # Survival forest plot example. |
|
81 |
#' adtte <- tern_ex_adtte |
|
82 |
#' # Save variable labels before data processing steps. |
|
83 |
#' adtte_labels <- formatters::var_labels(adtte, fill = TRUE) |
|
84 |
#' adtte_f <- adtte %>% |
|
85 |
#' filter( |
|
86 |
#' PARAMCD == "OS", |
|
87 |
#' ARM %in% c("B: Placebo", "A: Drug X"), |
|
88 |
#' SEX %in% c("M", "F") |
|
89 |
#' ) %>% |
|
90 |
#' mutate( |
|
91 |
#' # Reorder levels of ARM to display reference arm before treatment arm. |
|
92 |
#' ARM = droplevels(fct_relevel(ARM, "B: Placebo")), |
|
93 |
#' SEX = droplevels(SEX), |
|
94 |
#' AVALU = as.character(AVALU), |
|
95 |
#' is_event = CNSR == 0 |
|
96 |
#' ) |
|
97 |
#' labels <- list( |
|
98 |
#' "ARM" = adtte_labels["ARM"], |
|
99 |
#' "SEX" = adtte_labels["SEX"], |
|
100 |
#' "AVALU" = adtte_labels["AVALU"], |
|
101 |
#' "is_event" = "Event Flag" |
|
102 |
#' ) |
|
103 |
#' formatters::var_labels(adtte_f)[names(labels)] <- as.character(labels) |
|
104 |
#' df <- extract_survival_subgroups( |
|
105 |
#' variables = list( |
|
106 |
#' tte = "AVAL", |
|
107 |
#' is_event = "is_event", |
|
108 |
#' arm = "ARM", subgroups = c("SEX", "BMRKR2") |
|
109 |
#' ), |
|
110 |
#' data = adtte_f |
|
111 |
#' ) |
|
112 |
#' table_hr <- basic_table() %>% |
|
113 |
#' tabulate_survival_subgroups(df, time_unit = adtte_f$AVALU[1]) |
|
114 |
#' g_forest(table_hr) |
|
115 |
#' # Works with any `rtable`. |
|
116 |
#' tbl <- rtable( |
|
117 |
#' header = c("E", "CI", "N"), |
|
118 |
#' rrow("", 1, c(.8, 1.2), 200), |
|
119 |
#' rrow("", 1.2, c(1.1, 1.4), 50) |
|
120 |
#' ) |
|
121 |
#' g_forest( |
|
122 |
#' tbl = tbl, |
|
123 |
#' col_x = 1, |
|
124 |
#' col_ci = 2, |
|
125 |
#' xlim = c(0.5, 2), |
|
126 |
#' x_at = c(0.5, 1, 2), |
|
127 |
#' col_symbol_size = 3 |
|
128 |
#' ) |
|
129 |
#' tbl <- rtable( |
|
130 |
#' header = rheader( |
|
131 |
#' rrow("", rcell("A", colspan = 2)), |
|
132 |
#' rrow("", "c1", "c2") |
|
133 |
#' ), |
|
134 |
#' rrow("row 1", 1, c(.8, 1.2)), |
|
135 |
#' rrow("row 2", 1.2, c(1.1, 1.4)) |
|
136 |
#' ) |
|
137 |
#' g_forest( |
|
138 |
#' tbl = tbl, |
|
139 |
#' col_x = 1, |
|
140 |
#' col_ci = 2, |
|
141 |
#' xlim = c(0.5, 2), |
|
142 |
#' x_at = c(0.5, 1, 2), |
|
143 |
#' vline = 1, |
|
144 |
#' forest_header = c("Hello", "World") |
|
145 |
#' ) |
|
146 |
#' } |
|
147 |
#' |
|
148 |
#' @export |
|
149 |
g_forest <- function(tbl, |
|
150 |
col_x = attr(tbl, "col_x"), |
|
151 |
col_ci = attr(tbl, "col_ci"), |
|
152 |
vline = 1, |
|
153 |
forest_header = attr(tbl, "forest_header"), |
|
154 |
xlim = c(0.1, 10), |
|
155 |
logx = TRUE, |
|
156 |
x_at = c(0.1, 1, 10), |
|
157 |
width_row_names = NULL, |
|
158 |
width_columns = NULL, |
|
159 |
width_forest = grid::unit(1, "null"), |
|
160 |
col_symbol_size = attr(tbl, "col_symbol_size"), |
|
161 |
col = getOption("ggplot2.discrete.colour")[1], |
|
162 |
gp = NULL, |
|
163 |
draw = TRUE, |
|
164 |
newpage = TRUE) { |
|
165 | 2x |
checkmate::assert_class(tbl, "VTableTree") |
166 | ||
167 | 2x |
nr <- nrow(tbl) |
168 | 2x |
nc <- ncol(tbl) |
169 | 2x |
if (is.null(col)) { |
170 | 2x |
col <- "blue" |
171 |
} |
|
172 | ||
173 | 2x |
checkmate::assert_number(col_x, lower = 0, upper = nc, null.ok = FALSE) |
174 | 2x |
checkmate::assert_number(col_ci, lower = 0, upper = nc, null.ok = FALSE) |
175 | 2x |
checkmate::assert_number(col_symbol_size, lower = 0, upper = nc, null.ok = TRUE) |
176 | 2x |
checkmate::assert_true(col_x > 0) |
177 | 2x |
checkmate::assert_true(col_ci > 0) |
178 | 2x |
checkmate::assert_character(col) |
179 | 2x |
if (!is.null(col_symbol_size)) { |
180 | 1x |
checkmate::assert_true(col_symbol_size > 0) |
181 |
} |
|
182 | ||
183 | 2x |
x_e <- vapply(seq_len(nr), function(i) { |
184 |
# If a label row is selected NULL is returned with a warning (suppressed) |
|
185 | 9x |
xi <- suppressWarnings(as.vector(tbl[i, col_x, drop = TRUE])) |
186 | ||
187 | 9x |
if (!is.null(xi) && !(length(xi) <= 0) && is.numeric(xi)) { |
188 | 7x |
xi |
189 |
} else { |
|
190 | 2x |
NA_real_ |
191 |
} |
|
192 | 2x |
}, numeric(1)) |
193 | ||
194 | 2x |
x_ci <- lapply(seq_len(nr), function(i) { |
195 | 9x |
xi <- suppressWarnings(as.vector(tbl[i, col_ci, drop = TRUE])) # as above |
196 | ||
197 | 9x |
if (!is.null(xi) && !(length(xi) <= 0) && is.numeric(xi)) { |
198 | 7x |
if (length(xi) != 2) { |
199 | ! |
stop("ci column needs two elements") |
200 |
} |
|
201 | 7x |
xi |
202 |
} else { |
|
203 | 2x |
c(NA_real_, NA_real_) |
204 |
} |
|
205 |
}) |
|
206 | ||
207 | 2x |
lower <- vapply(x_ci, `[`, numeric(1), 1) |
208 | 2x |
upper <- vapply(x_ci, `[`, numeric(1), 2) |
209 | ||
210 | 2x |
symbol_size <- if (!is.null(col_symbol_size)) { |
211 | 1x |
tmp_symbol_size <- vapply(seq_len(nr), function(i) { |
212 | 7x |
suppressWarnings(xi <- as.vector(tbl[i, col_symbol_size, drop = TRUE])) |
213 | ||
214 | 7x |
if (!is.null(xi) && !(length(xi) <= 0) && is.numeric(xi)) { |
215 | 5x |
xi |
216 |
} else { |
|
217 | 1x |
NA_real_ |
218 |
} |
|
219 | 1x |
}, numeric(1)) |
220 | ||
221 |
# Scale symbol size. |
|
222 | 1x |
tmp_symbol_size <- sqrt(tmp_symbol_size) |
223 | 1x |
max_size <- max(tmp_symbol_size, na.rm = TRUE) |
224 |
# Biggest points have radius is 2 * (1/3.5) lines not to overlap. |
|
225 |
# See forest_dot_line. |
|
226 | 1x |
2 * tmp_symbol_size / max_size |
227 |
} else { |
|
228 | 1x |
NULL |
229 |
} |
|
230 | ||
231 | 2x |
grob_forest <- forest_grob( |
232 | 2x |
tbl, |
233 | 2x |
x_e, |
234 | 2x |
lower, |
235 | 2x |
upper, |
236 | 2x |
vline, |
237 | 2x |
forest_header, |
238 | 2x |
xlim, |
239 | 2x |
logx, |
240 | 2x |
x_at, |
241 | 2x |
width_row_names, |
242 | 2x |
width_columns, |
243 | 2x |
width_forest, |
244 | 2x |
symbol_size = symbol_size, |
245 | 2x |
col = col, |
246 | 2x |
gp = gp, |
247 | 2x |
vp = grid::plotViewport(margins = rep(1, 4)) |
248 |
) |
|
249 | ||
250 | 2x |
if (draw) { |
251 | 2x |
if (newpage) grid::grid.newpage() |
252 | 2x |
grid::grid.draw(grob_forest) |
253 |
} |
|
254 | ||
255 | 2x |
invisible(grob_forest) |
256 |
} |
|
257 | ||
258 |
#' Forest Plot Grob |
|
259 |
#' |
|
260 |
#' @inheritParams g_forest |
|
261 |
#' @param tbl ([rtables::rtable()]) |
|
262 |
#' @param x (`numeric`)\cr coordinate of point. |
|
263 |
#' @param lower,upper (`numeric`)\cr lower/upper bound of the confidence interval. |
|
264 |
#' @param symbol_size (`numeric`)\cr vector with relative size for plot symbol. |
|
265 |
#' If `NULL`, the same symbol size is used. |
|
266 |
#' |
|
267 |
#' @details |
|
268 |
#' The heights get automatically determined. |
|
269 |
#' |
|
270 |
#' @noRd |
|
271 |
#' |
|
272 |
#' @examples |
|
273 |
#' tbl <- rtable( |
|
274 |
#' header = rheader( |
|
275 |
#' rrow("", "E", rcell("CI", colspan = 2), "N"), |
|
276 |
#' rrow("", "A", "B", "C", "D") |
|
277 |
#' ), |
|
278 |
#' rrow("row 1", 1, 0.8, 1.1, 16), |
|
279 |
#' rrow("row 2", 1.4, 0.8, 1.6, 25), |
|
280 |
#' rrow("row 3", 1.2, 0.8, 1.6, 36) |
|
281 |
#' ) |
|
282 |
#' |
|
283 |
#' x <- c(1, 1.4, 1.2) |
|
284 |
#' lower <- c(0.8, 0.8, 0.8) |
|
285 |
#' upper <- c(1.1, 1.6, 1.6) |
|
286 |
#' # numeric vector with multiplication factor to scale each circle radius |
|
287 |
#' # default radius is 1/3.5 lines |
|
288 |
#' symbol_scale <- c(1, 1.25, 1.5) |
|
289 |
#' |
|
290 |
#' # Internal function - forest_grob |
|
291 |
#' \donttest{ |
|
292 |
#' p <- forest_grob(tbl, x, lower, upper, |
|
293 |
#' vline = 1, forest_header = c("A", "B"), |
|
294 |
#' x_at = c(.1, 1, 10), xlim = c(0.1, 10), logx = TRUE, symbol_size = symbol_scale, |
|
295 |
#' vp = grid::plotViewport(margins = c(1, 1, 1, 1)) |
|
296 |
#' ) |
|
297 |
#' |
|
298 |
#' draw_grob(p) |
|
299 |
#' } |
|
300 |
forest_grob <- function(tbl, |
|
301 |
x, |
|
302 |
lower, |
|
303 |
upper, |
|
304 |
vline, |
|
305 |
forest_header, |
|
306 |
xlim = NULL, |
|
307 |
logx = FALSE, |
|
308 |
x_at = NULL, |
|
309 |
width_row_names = NULL, |
|
310 |
width_columns = NULL, |
|
311 |
width_forest = grid::unit(1, "null"), |
|
312 |
symbol_size = NULL, |
|
313 |
col = "blue", |
|
314 |
name = NULL, |
|
315 |
gp = NULL, |
|
316 |
vp = NULL) { |
|
317 | 2x |
nr <- nrow(tbl) |
318 | 2x |
if (is.null(vline)) { |
319 | ! |
checkmate::assert_true(is.null(forest_header)) |
320 |
} else { |
|
321 | 2x |
checkmate::assert_number(vline) |
322 | 2x |
checkmate::assert_character(forest_header, len = 2, null.ok = TRUE) |
323 |
} |
|
324 | ||
325 | 2x |
checkmate::assert_numeric(x, len = nr) |
326 | 2x |
checkmate::assert_numeric(lower, len = nr) |
327 | 2x |
checkmate::assert_numeric(upper, len = nr) |
328 | 2x |
checkmate::assert_numeric(symbol_size, len = nr, null.ok = TRUE) |
329 | 2x |
checkmate::assert_character(col) |
330 | ||
331 | 2x |
if (is.null(symbol_size)) { |
332 | 1x |
symbol_size <- rep(1, nr) |
333 |
} |
|
334 | ||
335 | 2x |
if (is.null(xlim)) { |
336 | ! |
r <- range(c(x, lower, upper), na.rm = TRUE) |
337 | ! |
xlim <- r + c(-0.05, 0.05) * diff(r) |
338 |
} |
|
339 | ||
340 | 2x |
if (logx) { |
341 | 2x |
if (is.null(x_at)) { |
342 | ! |
x_at <- pretty(log(stats::na.omit(c(x, lower, upper)))) |
343 | ! |
x_labels <- exp(x_at) |
344 |
} else { |
|
345 | 2x |
x_labels <- x_at |
346 | 2x |
x_at <- log(x_at) |
347 |
} |
|
348 | 2x |
xlim <- log(xlim) |
349 | 2x |
x <- log(x) |
350 | 2x |
lower <- log(lower) |
351 | 2x |
upper <- log(upper) |
352 | 2x |
if (!is.null(vline)) { |
353 | 2x |
vline <- log(vline) |
354 |
} |
|
355 |
} else { |
|
356 | ! |
x_labels <- TRUE |
357 |
} |
|
358 | ||
359 | 2x |
data_forest_vp <- grid::dataViewport(xlim, c(0, 1)) |
360 | ||
361 |
# Get table content as matrix form. |
|
362 | 2x |
mf <- matrix_form(tbl) |
363 | ||
364 |
# Use `rtables` indent_string eventually. |
|
365 | 2x |
mf$strings[, 1] <- paste0( |
366 | 2x |
strrep(" ", c(rep(0, attr(mf, "nrow_header")), mf$row_info$indent)), |
367 | 2x |
mf$strings[, 1] |
368 |
) |
|
369 | ||
370 | 2x |
n_header <- attr(mf, "nrow_header") |
371 | ||
372 | ! |
if (any(mf$display[, 1] == FALSE)) stop("row names need to be always displayed") |
373 | ||
374 |
# Pre-process the data to be used in lapply and cell_in_rows. |
|
375 | 2x |
to_args_for_cell_in_rows_fun <- function(part = c("body", "header"), |
376 | 2x |
underline_colspan = FALSE) { |
377 | 4x |
part <- match.arg(part) |
378 | 4x |
if (part == "body") { |
379 | 2x |
mat_row_indices <- seq_len(nrow(tbl)) + n_header |
380 | 2x |
row_ind_offset <- -n_header |
381 |
} else { |
|
382 | 2x |
mat_row_indices <- seq_len(n_header) |
383 | 2x |
row_ind_offset <- 0 |
384 |
} |
|
385 | ||
386 | 4x |
lapply(mat_row_indices, function(i) { |
387 | 13x |
disp <- mf$display[i, -1] |
388 | 13x |
list( |
389 | 13x |
row_name = mf$strings[i, 1], |
390 | 13x |
cells = mf$strings[i, -1][disp], |
391 | 13x |
cell_spans = mf$spans[i, -1][disp], |
392 | 13x |
row_index = i + row_ind_offset, |
393 | 13x |
underline_colspan = underline_colspan |
394 |
) |
|
395 |
}) |
|
396 |
} |
|
397 | ||
398 | 2x |
args_header <- to_args_for_cell_in_rows_fun("header", underline_colspan = TRUE) |
399 | 2x |
args_body <- to_args_for_cell_in_rows_fun("body", underline_colspan = FALSE) |
400 | ||
401 | 2x |
grid::gTree( |
402 | 2x |
name = name, |
403 | 2x |
children = grid::gList( |
404 | 2x |
grid::gTree( |
405 | 2x |
children = do.call(grid::gList, lapply(args_header, do.call, what = cell_in_rows)), |
406 | 2x |
vp = grid::vpPath("vp_table_layout", "vp_header") |
407 |
), |
|
408 | 2x |
grid::gTree( |
409 | 2x |
children = do.call(grid::gList, lapply(args_body, do.call, what = cell_in_rows)), |
410 | 2x |
vp = grid::vpPath("vp_table_layout", "vp_body") |
411 |
), |
|
412 | 2x |
grid::linesGrob( |
413 | 2x |
grid::unit(c(0, 1), "npc"), |
414 | 2x |
y = grid::unit(c(.5, .5), "npc"), |
415 | 2x |
vp = grid::vpPath("vp_table_layout", "vp_spacer") |
416 |
), |
|
417 |
# forest part |
|
418 | 2x |
if (is.null(vline)) { |
419 | ! |
NULL |
420 |
} else { |
|
421 | 2x |
grid::gTree( |
422 | 2x |
children = grid::gList( |
423 | 2x |
grid::gTree( |
424 | 2x |
children = grid::gList( |
425 |
# this may overflow, to fix, look here |
|
426 |
# https://stackoverflow.com/questions/33623169/add-multi-line-footnote-to-tablegrob-while-using-gridextra-in-r #nolintr |
|
427 | 2x |
grid::textGrob( |
428 | 2x |
forest_header[1], |
429 | 2x |
x = grid::unit(vline, "native") - grid::unit(1, "lines"), |
430 | 2x |
just = c("right", "center") |
431 |
), |
|
432 | 2x |
grid::textGrob( |
433 | 2x |
forest_header[2], |
434 | 2x |
x = grid::unit(vline, "native") + grid::unit(1, "lines"), |
435 | 2x |
just = c("left", "center") |
436 |
) |
|
437 |
), |
|
438 | 2x |
vp = grid::vpStack(grid::viewport(layout.pos.col = ncol(tbl) + 2), data_forest_vp) |
439 |
) |
|
440 |
), |
|
441 | 2x |
vp = grid::vpPath("vp_table_layout", "vp_header") |
442 |
) |
|
443 |
}, |
|
444 | 2x |
grid::gTree( |
445 | 2x |
children = grid::gList( |
446 | 2x |
grid::gTree( |
447 | 2x |
children = grid::gList( |
448 | 2x |
grid::rectGrob(gp = grid::gpar(col = "gray90", fill = "gray90")), |
449 | 2x |
if (is.null(vline)) { |
450 | ! |
NULL |
451 |
} else { |
|
452 | 2x |
grid::linesGrob( |
453 | 2x |
x = grid::unit(rep(vline, 2), "native"), |
454 | 2x |
y = grid::unit(c(0, 1), "npc"), |
455 | 2x |
gp = grid::gpar(lwd = 2), |
456 | 2x |
vp = data_forest_vp |
457 |
) |
|
458 |
}, |
|
459 | 2x |
grid::xaxisGrob(at = x_at, label = x_labels, vp = data_forest_vp) |
460 |
), |
|
461 | 2x |
vp = grid::viewport(layout.pos.col = ncol(tbl) + 2) |
462 |
) |
|
463 |
), |
|
464 | 2x |
vp = grid::vpPath("vp_table_layout", "vp_body") |
465 |
), |
|
466 | 2x |
grid::gTree( |
467 | 2x |
children = do.call( |
468 | 2x |
grid::gList, |
469 | 2x |
Map( |
470 | 2x |
function(xi, li, ui, row_index, size_i, col) { |
471 | 9x |
forest_dot_line( |
472 | 9x |
xi, |
473 | 9x |
li, |
474 | 9x |
ui, |
475 | 9x |
row_index, |
476 | 9x |
xlim, |
477 | 9x |
symbol_size = size_i, |
478 | 9x |
col = col, |
479 | 9x |
datavp = data_forest_vp |
480 |
) |
|
481 |
}, |
|
482 | 2x |
x, |
483 | 2x |
lower, |
484 | 2x |
upper, |
485 | 2x |
seq_along(x), |
486 | 2x |
symbol_size, |
487 | 2x |
col, |
488 | 2x |
USE.NAMES = FALSE |
489 |
) |
|
490 |
), |
|
491 | 2x |
vp = grid::vpPath("vp_table_layout", "vp_body") |
492 |
) |
|
493 |
), |
|
494 | 2x |
childrenvp = forest_viewport(tbl, width_row_names, width_columns, width_forest), |
495 | 2x |
vp = vp, |
496 | 2x |
gp = gp |
497 |
) |
|
498 |
} |
|
499 | ||
500 | ||
501 |
cell_in_rows <- function(row_name, |
|
502 |
cells, |
|
503 |
cell_spans, |
|
504 |
row_index, |
|
505 |
underline_colspan = FALSE) { |
|
506 | 13x |
checkmate::assert_string(row_name) |
507 | 13x |
checkmate::assert_character(cells, min.len = 1, any.missing = FALSE) |
508 | 13x |
checkmate::assert_numeric(cell_spans, len = length(cells), any.missing = FALSE) |
509 | 13x |
checkmate::assert_number(row_index) |
510 | 13x |
checkmate::assert_flag(underline_colspan) |
511 | ||
512 | 13x |
vp_name_rn <- paste0("rowname-", row_index) |
513 | 13x |
g_rowname <- if (!is.null(row_name) && row_name != "") { |
514 | 10x |
grid::textGrob( |
515 | 10x |
name = vp_name_rn, |
516 | 10x |
label = row_name, |
517 | 10x |
x = grid::unit(0, "npc"), |
518 | 10x |
just = c("left", "center"), |
519 | 10x |
vp = grid::vpPath(paste0("rowname-", row_index)) |
520 |
) |
|
521 |
} else { |
|
522 | 3x |
NULL |
523 |
} |
|
524 | ||
525 | 13x |
gl_cols <- if (!(length(cells) > 0)) { |
526 | ! |
list(NULL) |
527 |
} else { |
|
528 | 13x |
j <- 1 # column index of cell |
529 | ||
530 | 13x |
lapply(seq_along(cells), function(k) { |
531 | 67x |
cell_ascii <- cells[[k]] |
532 | 67x |
cs <- cell_spans[[k]] |
533 | ||
534 | 67x |
if (is.na(cell_ascii) || is.null(cell_ascii)) { |
535 | ! |
cell_ascii <- "NA" |
536 |
} |
|
537 | ||
538 | 67x |
cell_name <- paste0("g-cell-", row_index, "-", j) |
539 | ||
540 | 67x |
cell_grobs <- if (identical(cell_ascii, "")) { |
541 | 14x |
NULL |
542 |
} else { |
|
543 | 53x |
if (cs == 1) { |
544 | 49x |
grid::textGrob( |
545 | 49x |
label = cell_ascii, |
546 | 49x |
name = cell_name, |
547 | 49x |
vp = grid::vpPath(paste0("cell-", row_index, "-", j)) |
548 |
) |
|
549 |
} else { |
|
550 |
# +1 because of rowname |
|
551 | 4x |
vp_joined_cols <- grid::viewport(layout.pos.row = row_index, layout.pos.col = seq(j + 1, j + cs)) |
552 | ||
553 | 4x |
lab <- grid::textGrob( |
554 | 4x |
label = cell_ascii, |
555 | 4x |
name = cell_name, |
556 | 4x |
vp = vp_joined_cols |
557 |
) |
|
558 | ||
559 | 4x |
if (!underline_colspan || grepl("^[[:space:]]*$", cell_ascii)) { |
560 | 1x |
lab |
561 |
} else { |
|
562 | 3x |
grid::gList( |
563 | 3x |
lab, |
564 | 3x |
grid::linesGrob( |
565 | 3x |
x = grid::unit.c(grid::unit(.2, "lines"), grid::unit(1, "npc") - grid::unit(.2, "lines")), |
566 | 3x |
y = grid::unit(c(0, 0), "npc"), |
567 | 3x |
vp = vp_joined_cols |
568 |
) |
|
569 |
) |
|
570 |
} |
|
571 |
} |
|
572 |
} |
|
573 | 67x |
j <<- j + cs |
574 | ||
575 | 67x |
cell_grobs |
576 |
}) |
|
577 |
} |
|
578 | ||
579 | 13x |
grid::gList( |
580 | 13x |
g_rowname, |
581 | 13x |
do.call(grid::gList, gl_cols) |
582 |
) |
|
583 |
} |
|
584 | ||
585 |
#' Graphic Object: Forest Dot Line |
|
586 |
#' |
|
587 |
#' Calculate the `grob` corresponding to the dot line within the forest plot. |
|
588 |
#' |
|
589 |
#' @noRd |
|
590 |
forest_dot_line <- function(x, |
|
591 |
lower, |
|
592 |
upper, |
|
593 |
row_index, |
|
594 |
xlim, |
|
595 |
symbol_size = 1, |
|
596 |
col = "blue", |
|
597 |
datavp) { |
|
598 | 9x |
ci <- c(lower, upper) |
599 | 9x |
if (any(!is.na(c(x, ci)))) { |
600 |
# line |
|
601 | 7x |
y <- grid::unit(c(0.5, 0.5), "npc") |
602 | ||
603 | 7x |
g_line <- if (all(!is.na(ci)) && ci[2] > xlim[1] && ci[1] < xlim[2]) { |
604 |
# - |
|
605 | 7x |
if (ci[1] >= xlim[1] && ci[2] <= xlim[2]) { |
606 | 2x |
grid::linesGrob(x = grid::unit(c(ci[1], ci[2]), "native"), y = y) |
607 | 5x |
} else if (ci[1] < xlim[1] && ci[2] > xlim[2]) { |
608 |
# <-> |
|
609 | 3x |
grid::linesGrob( |
610 | 3x |
x = grid::unit(xlim, "native"), |
611 | 3x |
y = y, |
612 | 3x |
arrow = grid::arrow(angle = 30, length = grid::unit(0.5, "lines"), ends = "both") |
613 |
) |
|
614 | 2x |
} else if (ci[1] < xlim[1] && ci[2] <= xlim[2]) { |
615 |
# <- |
|
616 | ! |
grid::linesGrob( |
617 | ! |
x = grid::unit(c(xlim[1], ci[2]), "native"), |
618 | ! |
y = y, |
619 | ! |
arrow = grid::arrow(angle = 30, length = grid::unit(0.5, "lines"), ends = "first") |
620 |
) |
|
621 | 2x |
} else if (ci[1] >= xlim[1] && ci[2] > xlim[2]) { |
622 |
# -> |
|
623 | 2x |
grid::linesGrob( |
624 | 2x |
x = grid::unit(c(ci[1], xlim[2]), "native"), |
625 | 2x |
y = y, |
626 | 2x |
arrow = grid::arrow(angle = 30, length = grid::unit(0.5, "lines"), ends = "last") |
627 |
) |
|
628 |
} |
|
629 |
} else { |
|
630 | ! |
NULL |
631 |
} |
|
632 | ||
633 | 7x |
g_circle <- if (!is.na(x) && x >= xlim[1] && x <= xlim[2]) { |
634 | 6x |
grid::circleGrob( |
635 | 6x |
x = grid::unit(x, "native"), |
636 | 6x |
y = y, |
637 | 6x |
r = grid::unit(1 / 3.5 * symbol_size, "lines"), |
638 | 6x |
name = "point" |
639 |
) |
|
640 |
} else { |
|
641 | 1x |
NULL |
642 |
} |
|
643 | ||
644 | 7x |
grid::gTree( |
645 | 7x |
children = grid::gList( |
646 | 7x |
grid::gTree( |
647 | 7x |
children = grid::gList( |
648 | 7x |
grid::gList( |
649 | 7x |
g_line, |
650 | 7x |
g_circle |
651 |
) |
|
652 |
), |
|
653 | 7x |
vp = datavp, |
654 | 7x |
gp = grid::gpar(col = col, fill = col) |
655 |
) |
|
656 |
), |
|
657 | 7x |
vp = grid::vpPath(paste0("forest-", row_index)) |
658 |
) |
|
659 |
} else { |
|
660 | 2x |
NULL |
661 |
} |
|
662 |
} |
|
663 | ||
664 |
#' Create a Viewport Tree for the Forest Plot |
|
665 |
#' @param tbl (`rtable`) |
|
666 |
#' @param width_row_names (`grid::unit`)\cr Width of row names |
|
667 |
#' @param width_columns (`grid::unit`)\cr Width of column spans |
|
668 |
#' @param width_forest (`grid::unit`)\cr Width of the forest plot |
|
669 |
#' @param gap_column (`grid::unit`)\cr Gap width between the columns |
|
670 |
#' @param gap_header (`grid::unit`)\cr Gap width between the header |
|
671 |
#' @param mat_form matrix print form of the table |
|
672 |
#' @return A viewport tree. |
|
673 |
#' |
|
674 |
#' @examples |
|
675 |
#' library(grid) |
|
676 |
#' |
|
677 |
#' tbl <- rtable( |
|
678 |
#' header = rheader( |
|
679 |
#' rrow("", "E", rcell("CI", colspan = 2)), |
|
680 |
#' rrow("", "A", "B", "C") |
|
681 |
#' ), |
|
682 |
#' rrow("row 1", 1, 0.8, 1.1), |
|
683 |
#' rrow("row 2", 1.4, 0.8, 1.6), |
|
684 |
#' rrow("row 3", 1.2, 0.8, 1.2) |
|
685 |
#' ) |
|
686 |
#' |
|
687 |
#' \donttest{ |
|
688 |
#' v <- forest_viewport(tbl) |
|
689 |
#' |
|
690 |
#' grid::grid.newpage() |
|
691 |
#' showViewport(v) |
|
692 |
#' } |
|
693 |
#' |
|
694 |
#' @export |
|
695 |
forest_viewport <- function(tbl, |
|
696 |
width_row_names = NULL, |
|
697 |
width_columns = NULL, |
|
698 |
width_forest = grid::unit(1, "null"), |
|
699 |
gap_column = grid::unit(1, "lines"), |
|
700 |
gap_header = grid::unit(1, "lines"), |
|
701 |
mat_form = NULL) { |
|
702 | 2x |
checkmate::assert_class(tbl, "VTableTree") |
703 | 2x |
checkmate::assert_true(grid::is.unit(width_forest)) |
704 | 2x |
if (!is.null(width_row_names)) { |
705 | ! |
checkmate::assert_true(grid::is.unit(width_row_names)) |
706 |
} |
|
707 | 2x |
if (!is.null(width_columns)) { |
708 | ! |
checkmate::assert_true(grid::is.unit(width_columns)) |
709 |
} |
|
710 | ||
711 | 2x |
if (is.null(mat_form)) mat_form <- matrix_form(tbl) |
712 | ||
713 | 2x |
mat_form$strings[!mat_form$display] <- "" |
714 | ||
715 | 2x |
nr <- nrow(tbl) |
716 | 2x |
nc <- ncol(tbl) |
717 | 2x |
nr_h <- attr(mat_form, "nrow_header") |
718 | ||
719 | 2x |
if (is.null(width_row_names) || is.null(width_columns)) { |
720 | 2x |
tbl_widths <- formatters::propose_column_widths(mat_form) |
721 | 2x |
strs_with_width <- strrep("x", tbl_widths) # that works for mono spaced fonts |
722 | 2x |
if (is.null(width_row_names)) width_row_names <- grid::stringWidth(strs_with_width[1]) |
723 | 2x |
if (is.null(width_columns)) width_columns <- grid::stringWidth(strs_with_width[-1]) |
724 |
} |
|
725 | ||
726 |
# Widths for row name, cols, forest. |
|
727 | 2x |
widths <- grid::unit.c( |
728 | 2x |
width_row_names + gap_column, |
729 | 2x |
width_columns + gap_column, |
730 | 2x |
width_forest |
731 |
) |
|
732 | ||
733 | 2x |
n_lines_per_row <- apply( |
734 | 2x |
X = mat_form$strings, |
735 | 2x |
MARGIN = 1, |
736 | 2x |
FUN = function(row) { |
737 | 13x |
tmp <- vapply( |
738 | 13x |
gregexpr("\n", row, fixed = TRUE), |
739 | 13x |
attr, numeric(1), |
740 | 13x |
"match.length" |
741 | 13x |
) + 1 |
742 | 13x |
max(c(tmp, 1)) |
743 |
} |
|
744 |
) |
|
745 | ||
746 | 2x |
i_header <- seq_len(nr_h) |
747 | ||
748 | 2x |
height_body_rows <- grid::unit(n_lines_per_row[-i_header] * 1.2, "lines") |
749 | 2x |
height_header_rows <- grid::unit(n_lines_per_row[i_header] * 1.2, "lines") |
750 | ||
751 | 2x |
height_body <- grid::unit(sum(n_lines_per_row[-i_header]) * 1.2, "lines") |
752 | 2x |
height_header <- grid::unit(sum(n_lines_per_row[i_header]) * 1.2, "lines") |
753 | ||
754 | 2x |
nc_g <- nc + 2 # number of columns incl. row names and forest |
755 | ||
756 | 2x |
vp_tbl <- grid::vpTree( |
757 | 2x |
parent = grid::viewport( |
758 | 2x |
name = "vp_table_layout", |
759 | 2x |
layout = grid::grid.layout( |
760 | 2x |
nrow = 3, ncol = 1, |
761 | 2x |
heights = grid::unit.c(height_header, gap_header, height_body) |
762 |
) |
|
763 |
), |
|
764 | 2x |
children = grid::vpList( |
765 | 2x |
vp_forest_table_part(nr_h, nc_g, 1, 1, widths, height_header_rows, "vp_header"), |
766 | 2x |
vp_forest_table_part(nr, nc_g, 3, 1, widths, height_body_rows, "vp_body"), |
767 | 2x |
grid::viewport(name = "vp_spacer", layout.pos.row = 2, layout.pos.col = 1) |
768 |
) |
|
769 |
) |
|
770 | 2x |
vp_tbl |
771 |
} |
|
772 | ||
773 |
#' Viewport Forest Plot: Table Part |
|
774 |
#' |
|
775 |
#' Prepares a viewport for the table included in the forest plot. |
|
776 |
#' |
|
777 |
#' @noRd |
|
778 |
vp_forest_table_part <- function(nrow, |
|
779 |
ncol, |
|
780 |
l_row, |
|
781 |
l_col, |
|
782 |
widths, |
|
783 |
heights, |
|
784 |
name) { |
|
785 | 4x |
grid::vpTree( |
786 | 4x |
grid::viewport( |
787 | 4x |
name = name, |
788 | 4x |
layout.pos.row = l_row, |
789 | 4x |
layout.pos.col = l_col, |
790 | 4x |
layout = grid::grid.layout(nrow = nrow, ncol = ncol, widths = widths, heights = heights) |
791 |
), |
|
792 | 4x |
children = grid::vpList( |
793 | 4x |
do.call( |
794 | 4x |
grid::vpList, |
795 | 4x |
lapply( |
796 | 4x |
seq_len(nrow), function(i) { |
797 | 13x |
grid::viewport(layout.pos.row = i, layout.pos.col = 1, name = paste0("rowname-", i)) |
798 |
} |
|
799 |
) |
|
800 |
), |
|
801 | 4x |
do.call( |
802 | 4x |
grid::vpList, |
803 | 4x |
apply( |
804 | 4x |
expand.grid(seq_len(nrow), seq_len(ncol - 2)), |
805 | 4x |
1, |
806 | 4x |
function(x) { |
807 | 71x |
i <- x[1] |
808 | 71x |
j <- x[2] |
809 | 71x |
grid::viewport(layout.pos.row = i, layout.pos.col = j + 1, name = paste0("cell-", i, "-", j)) |
810 |
} |
|
811 |
) |
|
812 |
), |
|
813 | 4x |
do.call( |
814 | 4x |
grid::vpList, |
815 | 4x |
lapply( |
816 | 4x |
seq_len(nrow), |
817 | 4x |
function(i) { |
818 | 13x |
grid::viewport(layout.pos.row = i, layout.pos.col = ncol, name = paste0("forest-", i)) |
819 |
} |
|
820 |
) |
|
821 |
) |
|
822 |
) |
|
823 |
) |
|
824 |
} |
|
825 | ||
826 |
#' Forest Rendering |
|
827 |
#' |
|
828 |
#' Renders the forest grob. |
|
829 |
#' |
|
830 |
#' @noRd |
|
831 |
grid.forest <- function(...) { # nolint |
|
832 | ! |
grid::grid.draw(forest_grob(...)) |
833 |
} |
1 |
#' Number of Patients |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Count the number of unique and non-unique patients in a column (variable). |
|
6 |
#' |
|
7 |
#' @inheritParams argument_convention |
|
8 |
#' @param count_by (`vector`)\cr optional vector of any type to be combined with `x` when counting `nonunique` |
|
9 |
#' records. |
|
10 |
#' @param unique_count_suffix (`logical`)\cr should `"(n)"` suffix be added to `unique_count` labels. |
|
11 |
#' Defaults to `TRUE`. |
|
12 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("summarize_num_patients")` |
|
13 |
#' to see available statistics for this function. |
|
14 |
#' |
|
15 |
#' @name summarize_num_patients |
|
16 |
#' @order 1 |
|
17 |
NULL |
|
18 | ||
19 |
#' @describeIn summarize_num_patients Statistics function which counts the number of |
|
20 |
#' unique patients, the corresponding percentage taken with respect to the |
|
21 |
#' total number of patients, and the number of non-unique patients. |
|
22 |
#' |
|
23 |
#' @param x (`character` or `factor`)\cr vector of patient IDs. |
|
24 |
#' |
|
25 |
#' @return |
|
26 |
#' * `s_num_patients()` returns a named `list` of 3 statistics: |
|
27 |
#' * `unique`: Vector of counts and percentages. |
|
28 |
#' * `nonunique`: Vector of counts. |
|
29 |
#' * `unique_count`: Counts. |
|
30 |
#' |
|
31 |
#' @examples |
|
32 |
#' # Use the statistics function to count number of unique and nonunique patients. |
|
33 |
#' s_num_patients(x = as.character(c(1, 1, 1, 2, 4, NA)), labelstr = "", .N_col = 6L) |
|
34 |
#' s_num_patients( |
|
35 |
#' x = as.character(c(1, 1, 1, 2, 4, NA)), |
|
36 |
#' labelstr = "", |
|
37 |
#' .N_col = 6L, |
|
38 |
#' count_by = c(1, 1, 2, 1, 1, 1) |
|
39 |
#' ) |
|
40 |
#' |
|
41 |
#' @export |
|
42 |
s_num_patients <- function(x, labelstr, .N_col, count_by = NULL, unique_count_suffix = TRUE) { # nolint |
|
43 | ||
44 | 109x |
checkmate::assert_string(labelstr) |
45 | 109x |
checkmate::assert_count(.N_col) |
46 | 109x |
checkmate::assert_multi_class(x, classes = c("factor", "character")) |
47 | 109x |
checkmate::assert_flag(unique_count_suffix) |
48 | ||
49 | 109x |
count1 <- n_available(unique(x)) |
50 | 109x |
count2 <- n_available(x) |
51 | ||
52 | 109x |
if (!is.null(count_by)) { |
53 | 10x |
checkmate::assert_vector(count_by, len = length(x)) |
54 | 10x |
count2 <- n_available(unique(interaction(x, count_by))) |
55 |
} |
|
56 | ||
57 | 109x |
out <- list( |
58 | 109x |
unique = formatters::with_label(c(count1, ifelse(count1 == 0 && .N_col == 0, 0, count1 / .N_col)), labelstr), |
59 | 109x |
nonunique = formatters::with_label(count2, labelstr), |
60 | 109x |
unique_count = formatters::with_label( |
61 | 109x |
count1, ifelse(unique_count_suffix, paste0(labelstr, if (nzchar(labelstr)) " ", "(n)"), labelstr) |
62 |
) |
|
63 |
) |
|
64 | ||
65 | 109x |
out |
66 |
} |
|
67 | ||
68 |
#' @describeIn summarize_num_patients Statistics function which counts the number of unique patients |
|
69 |
#' in a column (variable), the corresponding percentage taken with respect to the total number of |
|
70 |
#' patients, and the number of non-unique patients in the column. |
|
71 |
#' |
|
72 |
#' @param required (`character` or `NULL`)\cr optional name of a variable that is required to be non-missing. |
|
73 |
#' |
|
74 |
#' @return |
|
75 |
#' * `s_num_patients_content()` returns the same values as `s_num_patients()`. |
|
76 |
#' |
|
77 |
#' @examples |
|
78 |
#' # Count number of unique and non-unique patients. |
|
79 |
#' |
|
80 |
#' df <- data.frame( |
|
81 |
#' USUBJID = as.character(c(1, 2, 1, 4, NA)), |
|
82 |
#' EVENT = as.character(c(10, 15, 10, 17, 8)) |
|
83 |
#' ) |
|
84 |
#' s_num_patients_content(df, .N_col = 5, .var = "USUBJID") |
|
85 |
#' |
|
86 |
#' df_by_event <- data.frame( |
|
87 |
#' USUBJID = as.character(c(1, 2, 1, 4, NA)), |
|
88 |
#' EVENT = c(10, 15, 10, 17, 8) |
|
89 |
#' ) |
|
90 |
#' s_num_patients_content(df_by_event, .N_col = 5, .var = "USUBJID", count_by = "EVENT") |
|
91 |
#' |
|
92 |
#' @export |
|
93 |
s_num_patients_content <- function(df, |
|
94 |
labelstr = "", |
|
95 |
.N_col, # nolint |
|
96 |
.var, |
|
97 |
required = NULL, |
|
98 |
count_by = NULL, |
|
99 |
unique_count_suffix = TRUE) { |
|
100 | 46x |
checkmate::assert_string(.var) |
101 | 46x |
checkmate::assert_data_frame(df) |
102 | 46x |
if (is.null(count_by)) { |
103 | 43x |
assert_df_with_variables(df, list(id = .var)) |
104 |
} else { |
|
105 | 3x |
assert_df_with_variables(df, list(id = .var, count_by = count_by)) |
106 |
} |
|
107 | 46x |
if (!is.null(required)) { |
108 | ! |
checkmate::assert_string(required) |
109 | ! |
assert_df_with_variables(df, list(required = required)) |
110 | ! |
df <- df[!is.na(df[[required]]), , drop = FALSE] |
111 |
} |
|
112 | ||
113 | 46x |
x <- df[[.var]] |
114 | 46x |
y <- if (is.null(count_by)) NULL else df[[count_by]] |
115 | ||
116 | 46x |
s_num_patients( |
117 | 46x |
x = x, |
118 | 46x |
labelstr = labelstr, |
119 | 46x |
.N_col = .N_col, |
120 | 46x |
count_by = y, |
121 | 46x |
unique_count_suffix = unique_count_suffix |
122 |
) |
|
123 |
} |
|
124 | ||
125 |
c_num_patients <- make_afun( |
|
126 |
s_num_patients_content, |
|
127 |
.stats = c("unique", "nonunique", "unique_count"), |
|
128 |
.formats = c(unique = format_count_fraction_fixed_dp, nonunique = "xx", unique_count = "xx") |
|
129 |
) |
|
130 | ||
131 |
#' @describeIn summarize_num_patients Layout-creating function which can take statistics function arguments |
|
132 |
#' and additional format arguments. This function is a wrapper for [rtables::summarize_row_groups()]. |
|
133 |
#' |
|
134 |
#' @return |
|
135 |
#' * `summarize_num_patients()` returns a layout object suitable for passing to further layouting functions, |
|
136 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
137 |
#' the statistics from `s_num_patients_content()` to the table layout. |
|
138 |
#' |
|
139 |
#' @export |
|
140 |
#' @order 3 |
|
141 |
summarize_num_patients <- function(lyt, |
|
142 |
var, |
|
143 |
required = NULL, |
|
144 |
count_by = NULL, |
|
145 |
unique_count_suffix = TRUE, |
|
146 |
na_str = default_na_str(), |
|
147 |
.stats = NULL, |
|
148 |
.formats = NULL, |
|
149 |
.labels = c( |
|
150 |
unique = "Number of patients with at least one event", |
|
151 |
nonunique = "Number of events" |
|
152 |
), |
|
153 |
indent_mod = lifecycle::deprecated(), |
|
154 |
.indent_mods = 0L, |
|
155 |
riskdiff = FALSE, |
|
156 |
...) { |
|
157 | 9x |
checkmate::assert_flag(riskdiff) |
158 | ||
159 | 9x |
if (lifecycle::is_present(indent_mod)) { |
160 | ! |
lifecycle::deprecate_warn("0.8.2", "summarize_num_patients(indent_mod)", "summarize_num_patients(.indent_mods)") |
161 | ! |
.indent_mods <- indent_mod |
162 |
} |
|
163 | ||
164 | 4x |
if (is.null(.stats)) .stats <- c("unique", "nonunique", "unique_count") |
165 | 2x |
if (length(.labels) > length(.stats)) .labels <- .labels[names(.labels) %in% .stats] |
166 | ||
167 | 9x |
s_args <- list(required = required, count_by = count_by, unique_count_suffix = unique_count_suffix, ...) |
168 | ||
169 | 9x |
cfun <- make_afun( |
170 | 9x |
c_num_patients, |
171 | 9x |
.stats = .stats, |
172 | 9x |
.formats = .formats, |
173 | 9x |
.labels = .labels |
174 |
) |
|
175 | ||
176 | 9x |
extra_args <- if (isFALSE(riskdiff)) { |
177 | 8x |
s_args |
178 |
} else { |
|
179 | 1x |
list( |
180 | 1x |
afun = list("s_num_patients_content" = cfun), |
181 | 1x |
.stats = .stats, |
182 | 1x |
.indent_mods = .indent_mods, |
183 | 1x |
s_args = s_args |
184 |
) |
|
185 |
} |
|
186 | ||
187 | 9x |
summarize_row_groups( |
188 | 9x |
lyt = lyt, |
189 | 9x |
var = var, |
190 | 9x |
cfun = ifelse(isFALSE(riskdiff), cfun, afun_riskdiff), |
191 | 9x |
na_str = na_str, |
192 | 9x |
extra_args = extra_args, |
193 | 9x |
indent_mod = .indent_mods |
194 |
) |
|
195 |
} |
|
196 | ||
197 |
#' @describeIn summarize_num_patients Layout-creating function which can take statistics function arguments |
|
198 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
199 |
#' |
|
200 |
#' @return |
|
201 |
#' * `analyze_num_patients()` returns a layout object suitable for passing to further layouting functions, |
|
202 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
203 |
#' the statistics from `s_num_patients_content()` to the table layout. |
|
204 |
#' |
|
205 |
#' @details In general, functions that starts with `analyze*` are expected to |
|
206 |
#' work like [rtables::analyze()], while functions that starts with `summarize*` |
|
207 |
#' are based upon [rtables::summarize_row_groups()]. The latter provides a |
|
208 |
#' value for each dividing split in the row and column space, but, being it |
|
209 |
#' bound to the fundamental splits, it is repeated by design in every page |
|
210 |
#' when pagination is involved. |
|
211 |
#' |
|
212 |
#' @note As opposed to [summarize_num_patients()], this function does not repeat the produced rows. |
|
213 |
#' |
|
214 |
#' @examples |
|
215 |
#' df <- data.frame( |
|
216 |
#' USUBJID = as.character(c(1, 2, 1, 4, NA, 6, 6, 8, 9)), |
|
217 |
#' ARM = c("A", "A", "A", "A", "A", "B", "B", "B", "B"), |
|
218 |
#' AGE = c(10, 15, 10, 17, 8, 11, 11, 19, 17) |
|
219 |
#' ) |
|
220 |
#' |
|
221 |
#' tbl <- basic_table() %>% |
|
222 |
#' split_cols_by("ARM") %>% |
|
223 |
#' add_colcounts() %>% |
|
224 |
#' analyze_num_patients("USUBJID", .stats = c("unique")) %>% |
|
225 |
#' build_table(df) |
|
226 |
#' |
|
227 |
#' tbl |
|
228 |
#' |
|
229 |
#' @export |
|
230 |
#' @order 2 |
|
231 |
analyze_num_patients <- function(lyt, |
|
232 |
vars, |
|
233 |
required = NULL, |
|
234 |
count_by = NULL, |
|
235 |
unique_count_suffix = TRUE, |
|
236 |
na_str = default_na_str(), |
|
237 |
nested = TRUE, |
|
238 |
.stats = NULL, |
|
239 |
.formats = NULL, |
|
240 |
.labels = c( |
|
241 |
unique = "Number of patients with at least one event", |
|
242 |
nonunique = "Number of events" |
|
243 |
), |
|
244 |
show_labels = c("default", "visible", "hidden"), |
|
245 |
indent_mod = lifecycle::deprecated(), |
|
246 |
.indent_mods = 0L, |
|
247 |
riskdiff = FALSE, |
|
248 |
...) { |
|
249 | 3x |
checkmate::assert_flag(riskdiff) |
250 | ||
251 | 3x |
if (lifecycle::is_present(indent_mod)) { |
252 | ! |
lifecycle::deprecate_warn("0.8.2", "analyze_num_patients(indent_mod)", "analyze_num_patients(.indent_mods)") |
253 | ! |
.indent_mods <- indent_mod |
254 |
} |
|
255 | ||
256 | ! |
if (is.null(.stats)) .stats <- c("unique", "nonunique", "unique_count") |
257 | ! |
if (length(.labels) > length(.stats)) .labels <- .labels[names(.labels) %in% .stats] |
258 | ||
259 | 3x |
s_args <- list(required = required, count_by = count_by, unique_count_suffix = unique_count_suffix, ...) |
260 | ||
261 | 3x |
afun <- make_afun( |
262 | 3x |
c_num_patients, |
263 | 3x |
.stats = .stats, |
264 | 3x |
.formats = .formats, |
265 | 3x |
.labels = .labels |
266 |
) |
|
267 | ||
268 | 3x |
extra_args <- if (isFALSE(riskdiff)) { |
269 | 2x |
s_args |
270 |
} else { |
|
271 | 1x |
list( |
272 | 1x |
afun = list("s_num_patients_content" = afun), |
273 | 1x |
.stats = .stats, |
274 | 1x |
.indent_mods = .indent_mods, |
275 | 1x |
s_args = s_args |
276 |
) |
|
277 |
} |
|
278 | ||
279 | 3x |
analyze( |
280 | 3x |
afun = ifelse(isFALSE(riskdiff), afun, afun_riskdiff), |
281 | 3x |
lyt = lyt, |
282 | 3x |
vars = vars, |
283 | 3x |
na_str = na_str, |
284 | 3x |
nested = nested, |
285 | 3x |
extra_args = extra_args, |
286 | 3x |
show_labels = show_labels, |
287 | 3x |
indent_mod = .indent_mods |
288 |
) |
|
289 |
} |
1 |
#' Create a STEP Graph |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Based on the STEP results, creates a `ggplot` graph showing the estimated HR or OR |
|
6 |
#' along the continuous biomarker value subgroups. |
|
7 |
#' |
|
8 |
#' @param df (`tibble`)\cr result of [tidy.step()]. |
|
9 |
#' @param use_percentile (`flag`)\cr whether to use percentiles for the x axis or actual |
|
10 |
#' biomarker values. |
|
11 |
#' @param est (named `list`)\cr `col` and `lty` settings for estimate line. |
|
12 |
#' @param ci_ribbon (named `list` or `NULL`)\cr `fill` and `alpha` settings for the confidence interval |
|
13 |
#' ribbon area, or `NULL` to not plot a CI ribbon. |
|
14 |
#' @param col (`character`)\cr colors. |
|
15 |
#' |
|
16 |
#' @return A `ggplot` STEP graph. |
|
17 |
#' |
|
18 |
#' @seealso Custom tidy method [tidy.step()]. |
|
19 |
#' |
|
20 |
#' @examples |
|
21 |
#' library(nestcolor) |
|
22 |
#' library(survival) |
|
23 |
#' lung$sex <- factor(lung$sex) |
|
24 |
#' |
|
25 |
#' # Survival example. |
|
26 |
#' vars <- list( |
|
27 |
#' time = "time", |
|
28 |
#' event = "status", |
|
29 |
#' arm = "sex", |
|
30 |
#' biomarker = "age" |
|
31 |
#' ) |
|
32 |
#' |
|
33 |
#' step_matrix <- fit_survival_step( |
|
34 |
#' variables = vars, |
|
35 |
#' data = lung, |
|
36 |
#' control = c(control_coxph(), control_step(num_points = 10, degree = 2)) |
|
37 |
#' ) |
|
38 |
#' step_data <- broom::tidy(step_matrix) |
|
39 |
#' |
|
40 |
#' # Default plot. |
|
41 |
#' g_step(step_data) |
|
42 |
#' |
|
43 |
#' # Add the reference 1 horizontal line. |
|
44 |
#' library(ggplot2) |
|
45 |
#' g_step(step_data) + |
|
46 |
#' ggplot2::geom_hline(ggplot2::aes(yintercept = 1), linetype = 2) |
|
47 |
#' |
|
48 |
#' # Use actual values instead of percentiles, different color for estimate and no CI, |
|
49 |
#' # use log scale for y axis. |
|
50 |
#' g_step( |
|
51 |
#' step_data, |
|
52 |
#' use_percentile = FALSE, |
|
53 |
#' est = list(col = "blue", lty = 1), |
|
54 |
#' ci_ribbon = NULL |
|
55 |
#' ) + scale_y_log10() |
|
56 |
#' |
|
57 |
#' # Adding another curve based on additional column. |
|
58 |
#' step_data$extra <- exp(step_data$`Percentile Center`) |
|
59 |
#' g_step(step_data) + |
|
60 |
#' ggplot2::geom_line(ggplot2::aes(y = extra), linetype = 2, color = "green") |
|
61 |
#' |
|
62 |
#' # Response example. |
|
63 |
#' vars <- list( |
|
64 |
#' response = "status", |
|
65 |
#' arm = "sex", |
|
66 |
#' biomarker = "age" |
|
67 |
#' ) |
|
68 |
#' |
|
69 |
#' step_matrix <- fit_rsp_step( |
|
70 |
#' variables = vars, |
|
71 |
#' data = lung, |
|
72 |
#' control = c( |
|
73 |
#' control_logistic(response_definition = "I(response == 2)"), |
|
74 |
#' control_step() |
|
75 |
#' ) |
|
76 |
#' ) |
|
77 |
#' step_data <- broom::tidy(step_matrix) |
|
78 |
#' g_step(step_data) |
|
79 |
#' |
|
80 |
#' @export |
|
81 |
g_step <- function(df, |
|
82 |
use_percentile = "Percentile Center" %in% names(df), |
|
83 |
est = list(col = "blue", lty = 1), |
|
84 |
ci_ribbon = list(fill = getOption("ggplot2.discrete.colour")[1], alpha = 0.5), |
|
85 |
col = getOption("ggplot2.discrete.colour")) { |
|
86 | 2x |
checkmate::assert_tibble(df) |
87 | 2x |
checkmate::assert_flag(use_percentile) |
88 | 2x |
checkmate::assert_character(col, null.ok = TRUE) |
89 | 2x |
checkmate::assert_list(est, names = "named") |
90 | 2x |
checkmate::assert_list(ci_ribbon, names = "named", null.ok = TRUE) |
91 | ||
92 | 2x |
x_var <- ifelse(use_percentile, "Percentile Center", "Interval Center") |
93 | 2x |
df$x <- df[[x_var]] |
94 | 2x |
attrs <- attributes(df) |
95 | 2x |
df$y <- df[[attrs$estimate]] |
96 | ||
97 |
# Set legend names. To be modified also at call level |
|
98 | 2x |
legend_names <- c("Estimate", "CI 95%") |
99 | ||
100 | 2x |
p <- ggplot2::ggplot(df, ggplot2::aes(x = .data[["x"]], y = .data[["y"]])) |
101 | ||
102 | 2x |
if (!is.null(col)) { |
103 | 2x |
p <- p + |
104 | 2x |
ggplot2::scale_color_manual(values = col) |
105 |
} |
|
106 | ||
107 | 2x |
if (!is.null(ci_ribbon)) { |
108 | 1x |
if (is.null(ci_ribbon$fill)) { |
109 | ! |
ci_ribbon$fill <- "lightblue" |
110 |
} |
|
111 | 1x |
p <- p + ggplot2::geom_ribbon( |
112 | 1x |
ggplot2::aes( |
113 | 1x |
ymin = .data[["ci_lower"]], ymax = .data[["ci_upper"]], |
114 | 1x |
fill = legend_names[2] |
115 |
), |
|
116 | 1x |
alpha = ci_ribbon$alpha |
117 |
) + |
|
118 | 1x |
scale_fill_manual( |
119 | 1x |
name = "", values = c("CI 95%" = ci_ribbon$fill) |
120 |
) |
|
121 |
} |
|
122 | 2x |
suppressMessages(p <- p + |
123 | 2x |
ggplot2::geom_line( |
124 | 2x |
ggplot2::aes(y = .data[["y"]], color = legend_names[1]), |
125 | 2x |
linetype = est$lty |
126 |
) + |
|
127 | 2x |
scale_colour_manual( |
128 | 2x |
name = "", values = c("Estimate" = "blue") |
129 |
)) |
|
130 | ||
131 | 2x |
p <- p + ggplot2::labs(x = attrs$biomarker, y = attrs$estimate) |
132 | 2x |
if (use_percentile) { |
133 | 1x |
p <- p + ggplot2::scale_x_continuous(labels = scales::percent) |
134 |
} |
|
135 | 2x |
p |
136 |
} |
|
137 | ||
138 |
#' Custom Tidy Method for STEP Results |
|
139 |
#' |
|
140 |
#' @description `r lifecycle::badge("stable")` |
|
141 |
#' |
|
142 |
#' Tidy the STEP results into a `tibble` format ready for plotting. |
|
143 |
#' |
|
144 |
#' @param x (`step` matrix)\cr results from [fit_survival_step()]. |
|
145 |
#' @param ... not used here. |
|
146 |
#' |
|
147 |
#' @return A `tibble` with one row per STEP subgroup. The estimates and CIs are on the HR or OR scale, |
|
148 |
#' respectively. Additional attributes carry metadata also used for plotting. |
|
149 |
#' |
|
150 |
#' @seealso [g_step()] which consumes the result from this function. |
|
151 |
#' |
|
152 |
#' @method tidy step |
|
153 |
#' |
|
154 |
#' @examples |
|
155 |
#' library(survival) |
|
156 |
#' lung$sex <- factor(lung$sex) |
|
157 |
#' vars <- list( |
|
158 |
#' time = "time", |
|
159 |
#' event = "status", |
|
160 |
#' arm = "sex", |
|
161 |
#' biomarker = "age" |
|
162 |
#' ) |
|
163 |
#' step_matrix <- fit_survival_step( |
|
164 |
#' variables = vars, |
|
165 |
#' data = lung, |
|
166 |
#' control = c(control_coxph(), control_step(num_points = 10, degree = 2)) |
|
167 |
#' ) |
|
168 |
#' broom::tidy(step_matrix) |
|
169 |
#' |
|
170 |
#' @export |
|
171 |
tidy.step <- function(x, ...) { # nolint |
|
172 | 7x |
checkmate::assert_class(x, "step") |
173 | 7x |
dat <- as.data.frame(x) |
174 | 7x |
nams <- names(dat) |
175 | 7x |
is_surv <- "loghr" %in% names(dat) |
176 | 7x |
est_var <- ifelse(is_surv, "loghr", "logor") |
177 | 7x |
new_est_var <- ifelse(is_surv, "Hazard Ratio", "Odds Ratio") |
178 | 7x |
new_y_vars <- c(new_est_var, c("ci_lower", "ci_upper")) |
179 | 7x |
names(dat)[match(est_var, nams)] <- new_est_var |
180 | 7x |
dat[, new_y_vars] <- exp(dat[, new_y_vars]) |
181 | 7x |
any_is_na <- any(is.na(dat[, new_y_vars])) |
182 | 7x |
any_is_very_large <- any(abs(dat[, new_y_vars]) > 1e10, na.rm = TRUE) |
183 | 7x |
if (any_is_na) { |
184 | 2x |
warning(paste( |
185 | 2x |
"Missing values in the point estimate or CI columns,", |
186 | 2x |
"this will lead to holes in the `g_step()` plot" |
187 |
)) |
|
188 |
} |
|
189 | 7x |
if (any_is_very_large) { |
190 | 2x |
warning(paste( |
191 | 2x |
"Very large absolute values in the point estimate or CI columns,", |
192 | 2x |
"consider adding `scale_y_log10()` to the `g_step()` result for plotting" |
193 |
)) |
|
194 |
} |
|
195 | 7x |
if (any_is_na || any_is_very_large) { |
196 | 4x |
warning("Consider using larger `bandwidth`, less `num_points` in `control_step()` settings for fitting") |
197 |
} |
|
198 | 7x |
structure( |
199 | 7x |
tibble::as_tibble(dat), |
200 | 7x |
estimate = new_est_var, |
201 | 7x |
biomarker = attr(x, "variables")$biomarker, |
202 | 7x |
ci = f_conf_level(attr(x, "control")$conf_level) |
203 |
) |
|
204 |
} |
1 |
#' Encode Categorical Missing Values in a Data Frame |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' This is a helper function to encode missing entries across groups of categorical |
|
6 |
#' variables in a data frame. |
|
7 |
#' |
|
8 |
#' @details Missing entries are those with `NA` or empty strings and will |
|
9 |
#' be replaced with a specified value. If factor variables include missing |
|
10 |
#' values, the missing value will be inserted as the last level. |
|
11 |
#' Similarly, in case character or logical variables should be converted to factors |
|
12 |
#' with the `char_as_factor` or `logical_as_factor` options, the missing values will |
|
13 |
#' be set as the last level. |
|
14 |
#' |
|
15 |
#' @param data (`data.frame`)\cr data set. |
|
16 |
#' @param omit_columns (`character`)\cr names of variables from `data` that should |
|
17 |
#' not be modified by this function. |
|
18 |
#' @param char_as_factor (`flag`)\cr whether to convert character variables |
|
19 |
#' in `data` to factors. |
|
20 |
#' @param logical_as_factor (`flag`)\cr whether to convert logical variables |
|
21 |
#' in `data` to factors. |
|
22 |
#' @param na_level (`string`)\cr used to replace all `NA` or empty |
|
23 |
#' values inside non-`omit_columns` columns. |
|
24 |
#' |
|
25 |
#' @return A `data.frame` with the chosen modifications applied. |
|
26 |
#' |
|
27 |
#' @seealso [sas_na()] and [explicit_na()] for other missing data helper functions. |
|
28 |
#' |
|
29 |
#' @examples |
|
30 |
#' my_data <- data.frame( |
|
31 |
#' u = c(TRUE, FALSE, NA, TRUE), |
|
32 |
#' v = factor(c("A", NA, NA, NA), levels = c("Z", "A")), |
|
33 |
#' w = c("A", "B", NA, "C"), |
|
34 |
#' x = c("D", "E", "F", NA), |
|
35 |
#' y = c("G", "H", "I", ""), |
|
36 |
#' z = c(1, 2, 3, 4), |
|
37 |
#' stringsAsFactors = FALSE |
|
38 |
#' ) |
|
39 |
#' |
|
40 |
#' # Example 1 |
|
41 |
#' # Encode missing values in all character or factor columns. |
|
42 |
#' df_explicit_na(my_data) |
|
43 |
#' # Also convert logical columns to factor columns. |
|
44 |
#' df_explicit_na(my_data, logical_as_factor = TRUE) |
|
45 |
#' # Encode missing values in a subset of columns. |
|
46 |
#' df_explicit_na(my_data, omit_columns = c("x", "y")) |
|
47 |
#' |
|
48 |
#' # Example 2 |
|
49 |
#' # Here we purposefully convert all `M` values to `NA` in the `SEX` variable. |
|
50 |
#' # After running `df_explicit_na` the `NA` values are encoded as `<Missing>` but they are not |
|
51 |
#' # included when generating `rtables`. |
|
52 |
#' adsl <- tern_ex_adsl |
|
53 |
#' adsl$SEX[adsl$SEX == "M"] <- NA |
|
54 |
#' adsl <- df_explicit_na(adsl) |
|
55 |
#' |
|
56 |
#' # If you want the `Na` values to be displayed in the table use the `na_level` argument. |
|
57 |
#' adsl <- tern_ex_adsl |
|
58 |
#' adsl$SEX[adsl$SEX == "M"] <- NA |
|
59 |
#' adsl <- df_explicit_na(adsl, na_level = "Missing Values") |
|
60 |
#' |
|
61 |
#' # Example 3 |
|
62 |
#' # Numeric variables that have missing values are not altered. This means that any `NA` value in |
|
63 |
#' # a numeric variable will not be included in the summary statistics, nor will they be included |
|
64 |
#' # in the denominator value for calculating the percent values. |
|
65 |
#' adsl <- tern_ex_adsl |
|
66 |
#' adsl$AGE[adsl$AGE < 30] <- NA |
|
67 |
#' adsl <- df_explicit_na(adsl) |
|
68 |
#' |
|
69 |
#' @export |
|
70 |
df_explicit_na <- function(data, |
|
71 |
omit_columns = NULL, |
|
72 |
char_as_factor = TRUE, |
|
73 |
logical_as_factor = FALSE, |
|
74 |
na_level = "<Missing>") { |
|
75 | 22x |
checkmate::assert_character(omit_columns, null.ok = TRUE, min.len = 1, any.missing = FALSE) |
76 | 21x |
checkmate::assert_data_frame(data) |
77 | 20x |
checkmate::assert_flag(char_as_factor) |
78 | 19x |
checkmate::assert_flag(logical_as_factor) |
79 | 19x |
checkmate::assert_string(na_level) |
80 | ||
81 | 17x |
target_vars <- if (is.null(omit_columns)) { |
82 | 15x |
names(data) |
83 |
} else { |
|
84 | 2x |
setdiff(names(data), omit_columns) # May have duplicates. |
85 |
} |
|
86 | 17x |
if (length(target_vars) == 0) { |
87 | 1x |
return(data) |
88 |
} |
|
89 | ||
90 | 16x |
l_target_vars <- split(target_vars, target_vars) |
91 | ||
92 |
# Makes sure target_vars exist in data and names are not duplicated. |
|
93 | 16x |
assert_df_with_variables(data, l_target_vars) |
94 | ||
95 | 16x |
for (x in target_vars) { |
96 | 304x |
xi <- data[[x]] |
97 | 304x |
xi_label <- obj_label(xi) |
98 | ||
99 |
# Determine whether to convert character or logical input. |
|
100 | 304x |
do_char_conversion <- is.character(xi) && char_as_factor |
101 | 304x |
do_logical_conversion <- is.logical(xi) && logical_as_factor |
102 | ||
103 |
# Pre-convert logical to character to deal correctly with replacing NA |
|
104 |
# values below. |
|
105 | 304x |
if (do_logical_conversion) { |
106 | 2x |
xi <- as.character(xi) |
107 |
} |
|
108 | ||
109 | 304x |
if (is.factor(xi) || is.character(xi)) { |
110 |
# Handle empty strings and NA values. |
|
111 | 217x |
xi <- explicit_na(sas_na(xi), label = na_level) |
112 | ||
113 |
# Convert to factors if requested for the original type, |
|
114 |
# set na_level as the last value. |
|
115 | 217x |
if (do_char_conversion || do_logical_conversion) { |
116 | 78x |
levels_xi <- setdiff(sort(unique(xi)), na_level) |
117 | 78x |
if (na_level %in% unique(xi)) { |
118 | 18x |
levels_xi <- c(levels_xi, na_level) |
119 |
} |
|
120 | ||
121 | 78x |
xi <- factor(xi, levels = levels_xi) |
122 |
} |
|
123 | ||
124 | 217x |
data[, x] <- formatters::with_label(xi, label = xi_label) |
125 |
} |
|
126 |
} |
|
127 | 16x |
return(data) |
128 |
} |
1 |
#' Helper Functions for Subgroup Treatment Effect Pattern (STEP) Calculations |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Helper functions that are used internally for the STEP calculations. |
|
6 |
#' |
|
7 |
#' @inheritParams argument_convention |
|
8 |
#' |
|
9 |
#' @name h_step |
|
10 |
#' @include control_step.R |
|
11 |
NULL |
|
12 | ||
13 |
#' @describeIn h_step creates the windows for STEP, based on the control settings |
|
14 |
#' provided. |
|
15 |
#' |
|
16 |
#' @param x (`numeric`)\cr biomarker value(s) to use (without `NA`). |
|
17 |
#' @param control (named `list`)\cr output from `control_step()`. |
|
18 |
#' |
|
19 |
#' @return |
|
20 |
#' * `h_step_window()` returns a list containing the window-selection matrix `sel` |
|
21 |
#' and the interval information matrix `interval`. |
|
22 |
#' |
|
23 |
#' @export |
|
24 |
h_step_window <- function(x, |
|
25 |
control = control_step()) { |
|
26 | 12x |
checkmate::assert_numeric(x, min.len = 1, any.missing = FALSE) |
27 | 12x |
checkmate::assert_list(control, names = "named") |
28 | ||
29 | 12x |
sel <- matrix(FALSE, length(x), control$num_points) |
30 | 12x |
out <- matrix(0, control$num_points, 3) |
31 | 12x |
colnames(out) <- paste("Interval", c("Center", "Lower", "Upper")) |
32 | 12x |
if (control$use_percentile) { |
33 |
# Create windows according to percentile cutoffs. |
|
34 | 9x |
out <- cbind(out, out) |
35 | 9x |
colnames(out)[1:3] <- paste("Percentile", c("Center", "Lower", "Upper")) |
36 | 9x |
xs <- seq(0, 1, length = control$num_points + 2)[-1] |
37 | 9x |
for (i in seq_len(control$num_points)) { |
38 | 185x |
out[i, 2:3] <- c( |
39 | 185x |
max(xs[i] - control$bandwidth, 0), |
40 | 185x |
min(xs[i] + control$bandwidth, 1) |
41 |
) |
|
42 | 185x |
out[i, 5:6] <- stats::quantile(x, out[i, 2:3]) |
43 | 185x |
sel[, i] <- x >= out[i, 5] & x <= out[i, 6] |
44 |
} |
|
45 |
# Center is the middle point of the percentile window. |
|
46 | 9x |
out[, 1] <- xs[-control$num_points - 1] |
47 | 9x |
out[, 4] <- stats::quantile(x, out[, 1]) |
48 |
} else { |
|
49 |
# Create windows according to cutoffs. |
|
50 | 3x |
m <- c(min(x), max(x)) |
51 | 3x |
xs <- seq(m[1], m[2], length = control$num_points + 2)[-1] |
52 | 3x |
for (i in seq_len(control$num_points)) { |
53 | 11x |
out[i, 2:3] <- c( |
54 | 11x |
max(xs[i] - control$bandwidth, m[1]), |
55 | 11x |
min(xs[i] + control$bandwidth, m[2]) |
56 |
) |
|
57 | 11x |
sel[, i] <- x >= out[i, 2] & x <= out[i, 3] |
58 |
} |
|
59 |
# Center is the same as the point for predicting. |
|
60 | 3x |
out[, 1] <- xs[-control$num_points - 1] |
61 |
} |
|
62 | 12x |
list(sel = sel, interval = out) |
63 |
} |
|
64 | ||
65 |
#' @describeIn h_step calculates the estimated treatment effect estimate |
|
66 |
#' on the linear predictor scale and corresponding standard error from a STEP `model` fitted |
|
67 |
#' on `data` given `variables` specification, for a single biomarker value `x`. |
|
68 |
#' This works for both `coxph` and `glm` models, i.e. for calculating log hazard ratio or log odds |
|
69 |
#' ratio estimates. |
|
70 |
#' |
|
71 |
#' @param model the regression model object. |
|
72 |
#' |
|
73 |
#' @return |
|
74 |
#' * `h_step_trt_effect()` returns a vector with elements `est` and `se`. |
|
75 |
#' |
|
76 |
#' @export |
|
77 |
h_step_trt_effect <- function(data, |
|
78 |
model, |
|
79 |
variables, |
|
80 |
x) { |
|
81 | 208x |
checkmate::assert_multi_class(model, c("coxph", "glm")) |
82 | 208x |
checkmate::assert_number(x) |
83 | 208x |
assert_df_with_variables(data, variables) |
84 | 208x |
checkmate::assert_factor(data[[variables$arm]], n.levels = 2) |
85 | ||
86 | 208x |
newdata <- data[c(1, 1), ] |
87 | 208x |
newdata[, variables$biomarker] <- x |
88 | 208x |
newdata[, variables$arm] <- levels(data[[variables$arm]]) |
89 | 208x |
model_terms <- stats::delete.response(stats::terms(model)) |
90 | 208x |
model_frame <- stats::model.frame(model_terms, data = newdata, xlev = model$xlevels) |
91 | 208x |
mat <- stats::model.matrix(model_terms, data = model_frame, contrasts.arg = model$contrasts) |
92 | 208x |
coefs <- stats::coef(model) |
93 |
# Note: It is important to use the coef subset from matrix, otherwise intercept and |
|
94 |
# strata are included for coxph() models. |
|
95 | 208x |
mat <- mat[, names(coefs)] |
96 | 208x |
mat_diff <- diff(mat) |
97 | 208x |
est <- mat_diff %*% coefs |
98 | 208x |
var <- mat_diff %*% stats::vcov(model) %*% t(mat_diff) |
99 | 208x |
se <- sqrt(var) |
100 | 208x |
c( |
101 | 208x |
est = est, |
102 | 208x |
se = se |
103 |
) |
|
104 |
} |
|
105 | ||
106 |
#' @describeIn h_step builds the model formula used in survival STEP calculations. |
|
107 |
#' |
|
108 |
#' @return |
|
109 |
#' * `h_step_survival_formula()` returns a model formula. |
|
110 |
#' |
|
111 |
#' @export |
|
112 |
h_step_survival_formula <- function(variables, |
|
113 |
control = control_step()) { |
|
114 | 10x |
checkmate::assert_character(variables$covariates, null.ok = TRUE) |
115 | ||
116 | 10x |
assert_list_of_variables(variables[c("arm", "biomarker", "event", "time")]) |
117 | 10x |
form <- paste0("Surv(", variables$time, ", ", variables$event, ") ~ ", variables$arm) |
118 | 10x |
if (control$degree > 0) { |
119 | 5x |
form <- paste0(form, " * stats::poly(", variables$biomarker, ", degree = ", control$degree, ", raw = TRUE)") |
120 |
} |
|
121 | 10x |
if (!is.null(variables$covariates)) { |
122 | 6x |
form <- paste(form, "+", paste(variables$covariates, collapse = "+")) |
123 |
} |
|
124 | 10x |
if (!is.null(variables$strata)) { |
125 | 2x |
form <- paste0(form, " + strata(", paste0(variables$strata, collapse = ", "), ")") |
126 |
} |
|
127 | 10x |
stats::as.formula(form) |
128 |
} |
|
129 | ||
130 |
#' @describeIn h_step estimates the model with `formula` built based on |
|
131 |
#' `variables` in `data` for a given `subset` and `control` parameters for the |
|
132 |
#' Cox regression. |
|
133 |
#' |
|
134 |
#' @param formula (`formula`)\cr the regression model formula. |
|
135 |
#' @param subset (`logical`)\cr subset vector. |
|
136 |
#' |
|
137 |
#' @return |
|
138 |
#' * `h_step_survival_est()` returns a matrix of number of observations `n`, |
|
139 |
#' `events`, log hazard ratio estimates `loghr`, standard error `se`, |
|
140 |
#' and Wald confidence interval bounds `ci_lower` and `ci_upper`. One row is |
|
141 |
#' included for each biomarker value in `x`. |
|
142 |
#' |
|
143 |
#' @export |
|
144 |
h_step_survival_est <- function(formula, |
|
145 |
data, |
|
146 |
variables, |
|
147 |
x, |
|
148 |
subset = rep(TRUE, nrow(data)), |
|
149 |
control = control_coxph()) { |
|
150 | 55x |
checkmate::assert_formula(formula) |
151 | 55x |
assert_df_with_variables(data, variables) |
152 | 55x |
checkmate::assert_logical(subset, min.len = 1, any.missing = FALSE) |
153 | 55x |
checkmate::assert_numeric(x, min.len = 1, any.missing = FALSE) |
154 | 55x |
checkmate::assert_list(control, names = "named") |
155 | ||
156 |
# Note: `subset` in `coxph` needs to be an expression referring to `data` variables. |
|
157 | 55x |
data$.subset <- subset |
158 | 55x |
coxph_warnings <- NULL |
159 | 55x |
tryCatch( |
160 | 55x |
withCallingHandlers( |
161 | 55x |
expr = { |
162 | 55x |
fit <- survival::coxph( |
163 | 55x |
formula = formula, |
164 | 55x |
data = data, |
165 | 55x |
subset = .subset, |
166 | 55x |
ties = control$ties |
167 |
) |
|
168 |
}, |
|
169 | 55x |
warning = function(w) { |
170 | 1x |
coxph_warnings <<- c(coxph_warnings, w) |
171 | 1x |
invokeRestart("muffleWarning") |
172 |
} |
|
173 |
), |
|
174 | 55x |
finally = { |
175 |
} |
|
176 |
) |
|
177 | 55x |
if (!is.null(coxph_warnings)) { |
178 | 1x |
warning(paste( |
179 | 1x |
"Fit warnings occurred, please consider using a simpler model, or", |
180 | 1x |
"larger `bandwidth`, less `num_points` in `control_step()` settings" |
181 |
)) |
|
182 |
} |
|
183 |
# Produce a matrix with one row per `x` and columns `est` and `se`. |
|
184 | 55x |
estimates <- t(vapply( |
185 | 55x |
X = x, |
186 | 55x |
FUN = h_step_trt_effect, |
187 | 55x |
FUN.VALUE = c(1, 2), |
188 | 55x |
data = data, |
189 | 55x |
model = fit, |
190 | 55x |
variables = variables |
191 |
)) |
|
192 | 55x |
q_norm <- stats::qnorm((1 + control$conf_level) / 2) |
193 | 55x |
cbind( |
194 | 55x |
n = fit$n, |
195 | 55x |
events = fit$nevent, |
196 | 55x |
loghr = estimates[, "est"], |
197 | 55x |
se = estimates[, "se"], |
198 | 55x |
ci_lower = estimates[, "est"] - q_norm * estimates[, "se"], |
199 | 55x |
ci_upper = estimates[, "est"] + q_norm * estimates[, "se"] |
200 |
) |
|
201 |
} |
|
202 | ||
203 |
#' @describeIn h_step builds the model formula used in response STEP calculations. |
|
204 |
#' |
|
205 |
#' @return |
|
206 |
#' * `h_step_rsp_formula()` returns a model formula. |
|
207 |
#' |
|
208 |
#' @export |
|
209 |
h_step_rsp_formula <- function(variables, |
|
210 |
control = c(control_step(), control_logistic())) { |
|
211 | 14x |
checkmate::assert_character(variables$covariates, null.ok = TRUE) |
212 | 14x |
assert_list_of_variables(variables[c("arm", "biomarker", "response")]) |
213 | 14x |
response_definition <- sub( |
214 | 14x |
pattern = "response", |
215 | 14x |
replacement = variables$response, |
216 | 14x |
x = control$response_definition, |
217 | 14x |
fixed = TRUE |
218 |
) |
|
219 | 14x |
form <- paste0(response_definition, " ~ ", variables$arm) |
220 | 14x |
if (control$degree > 0) { |
221 | 8x |
form <- paste0(form, " * stats::poly(", variables$biomarker, ", degree = ", control$degree, ", raw = TRUE)") |
222 |
} |
|
223 | 14x |
if (!is.null(variables$covariates)) { |
224 | 8x |
form <- paste(form, "+", paste(variables$covariates, collapse = "+")) |
225 |
} |
|
226 | 14x |
if (!is.null(variables$strata)) { |
227 | 5x |
strata_arg <- if (length(variables$strata) > 1) { |
228 | 2x |
paste0("I(interaction(", paste0(variables$strata, collapse = ", "), "))") |
229 |
} else { |
|
230 | 3x |
variables$strata |
231 |
} |
|
232 | 5x |
form <- paste0(form, "+ strata(", strata_arg, ")") |
233 |
} |
|
234 | 14x |
stats::as.formula(form) |
235 |
} |
|
236 | ||
237 |
#' @describeIn h_step estimates the model with `formula` built based on |
|
238 |
#' `variables` in `data` for a given `subset` and `control` parameters for the |
|
239 |
#' logistic regression. |
|
240 |
#' |
|
241 |
#' @param formula (`formula`)\cr the regression model formula. |
|
242 |
#' @param subset (`logical`)\cr subset vector. |
|
243 |
#' |
|
244 |
#' @return |
|
245 |
#' * `h_step_rsp_est()` returns a matrix of number of observations `n`, log odds |
|
246 |
#' ratio estimates `logor`, standard error `se`, and Wald confidence interval bounds |
|
247 |
#' `ci_lower` and `ci_upper`. One row is included for each biomarker value in `x`. |
|
248 |
#' |
|
249 |
#' @export |
|
250 |
h_step_rsp_est <- function(formula, |
|
251 |
data, |
|
252 |
variables, |
|
253 |
x, |
|
254 |
subset = rep(TRUE, nrow(data)), |
|
255 |
control = control_logistic()) { |
|
256 | 58x |
checkmate::assert_formula(formula) |
257 | 58x |
assert_df_with_variables(data, variables) |
258 | 58x |
checkmate::assert_logical(subset, min.len = 1, any.missing = FALSE) |
259 | 58x |
checkmate::assert_numeric(x, min.len = 1, any.missing = FALSE) |
260 | 58x |
checkmate::assert_list(control, names = "named") |
261 |
# Note: `subset` in `glm` needs to be an expression referring to `data` variables. |
|
262 | 58x |
data$.subset <- subset |
263 | 58x |
fit_warnings <- NULL |
264 | 58x |
tryCatch( |
265 | 58x |
withCallingHandlers( |
266 | 58x |
expr = { |
267 | 58x |
fit <- if (is.null(variables$strata)) { |
268 | 54x |
stats::glm( |
269 | 54x |
formula = formula, |
270 | 54x |
data = data, |
271 | 54x |
subset = .subset, |
272 | 54x |
family = stats::binomial("logit") |
273 |
) |
|
274 |
} else { |
|
275 |
# clogit needs coxph and strata imported |
|
276 | 4x |
survival::clogit( |
277 | 4x |
formula = formula, |
278 | 4x |
data = data, |
279 | 4x |
subset = .subset |
280 |
) |
|
281 |
} |
|
282 |
}, |
|
283 | 58x |
warning = function(w) { |
284 | 19x |
fit_warnings <<- c(fit_warnings, w) |
285 | 19x |
invokeRestart("muffleWarning") |
286 |
} |
|
287 |
), |
|
288 | 58x |
finally = { |
289 |
} |
|
290 |
) |
|
291 | 58x |
if (!is.null(fit_warnings)) { |
292 | 13x |
warning(paste( |
293 | 13x |
"Fit warnings occurred, please consider using a simpler model, or", |
294 | 13x |
"larger `bandwidth`, less `num_points` in `control_step()` settings" |
295 |
)) |
|
296 |
} |
|
297 |
# Produce a matrix with one row per `x` and columns `est` and `se`. |
|
298 | 58x |
estimates <- t(vapply( |
299 | 58x |
X = x, |
300 | 58x |
FUN = h_step_trt_effect, |
301 | 58x |
FUN.VALUE = c(1, 2), |
302 | 58x |
data = data, |
303 | 58x |
model = fit, |
304 | 58x |
variables = variables |
305 |
)) |
|
306 | 58x |
q_norm <- stats::qnorm((1 + control$conf_level) / 2) |
307 | 58x |
cbind( |
308 | 58x |
n = length(fit$y), |
309 | 58x |
logor = estimates[, "est"], |
310 | 58x |
se = estimates[, "se"], |
311 | 58x |
ci_lower = estimates[, "est"] - q_norm * estimates[, "se"], |
312 | 58x |
ci_upper = estimates[, "est"] + q_norm * estimates[, "se"] |
313 |
) |
|
314 |
} |
1 |
#' Convert List of Groups to Data Frame |
|
2 |
#' |
|
3 |
#' This converts a list of group levels into a data frame format which is expected by [rtables::add_combo_levels()]. |
|
4 |
#' |
|
5 |
#' @param groups_list (named `list` of `character`)\cr specifies the new group levels via the names and the |
|
6 |
#' levels that belong to it in the character vectors that are elements of the list. |
|
7 |
#' |
|
8 |
#' @return [tibble::tibble()] in the required format. |
|
9 |
#' |
|
10 |
#' @examples |
|
11 |
#' grade_groups <- list( |
|
12 |
#' "Any Grade (%)" = c("1", "2", "3", "4", "5"), |
|
13 |
#' "Grade 3-4 (%)" = c("3", "4"), |
|
14 |
#' "Grade 5 (%)" = "5" |
|
15 |
#' ) |
|
16 |
#' groups_list_to_df(grade_groups) |
|
17 |
#' |
|
18 |
#' @export |
|
19 |
groups_list_to_df <- function(groups_list) { |
|
20 | 5x |
checkmate::assert_list(groups_list, names = "named") |
21 | 5x |
lapply(groups_list, checkmate::assert_character) |
22 | 5x |
tibble::tibble( |
23 | 5x |
valname = make_names(names(groups_list)), |
24 | 5x |
label = names(groups_list), |
25 | 5x |
levelcombo = unname(groups_list), |
26 | 5x |
exargs = replicate(length(groups_list), list()) |
27 |
) |
|
28 |
} |
|
29 | ||
30 |
#' Reference and Treatment Group Combination |
|
31 |
#' |
|
32 |
#' @description `r lifecycle::badge("stable")` |
|
33 |
#' |
|
34 |
#' Facilitate the re-combination of groups divided as reference and treatment groups; it helps in arranging groups of |
|
35 |
#' columns in the `rtables` framework and teal modules. |
|
36 |
#' |
|
37 |
#' @param fct (`factor`)\cr the variable with levels which needs to be grouped. |
|
38 |
#' @param ref (`string`)\cr the reference level(s). |
|
39 |
#' @param collapse (`string`)\cr a character string to separate `fct` and `ref`. |
|
40 |
#' |
|
41 |
#' @return A `list` with first item `ref` (reference) and second item `trt` (treatment). |
|
42 |
#' |
|
43 |
#' @examples |
|
44 |
#' groups <- combine_groups( |
|
45 |
#' fct = DM$ARM, |
|
46 |
#' ref = c("B: Placebo") |
|
47 |
#' ) |
|
48 |
#' |
|
49 |
#' basic_table() %>% |
|
50 |
#' split_cols_by_groups("ARM", groups) %>% |
|
51 |
#' add_colcounts() %>% |
|
52 |
#' analyze_vars("AGE") %>% |
|
53 |
#' build_table(DM) |
|
54 |
#' |
|
55 |
#' @export |
|
56 |
combine_groups <- function(fct, |
|
57 |
ref = NULL, |
|
58 |
collapse = "/") { |
|
59 | 10x |
checkmate::assert_string(collapse) |
60 | 10x |
checkmate::assert_character(ref, min.chars = 1, any.missing = FALSE, null.ok = TRUE) |
61 | 10x |
checkmate::assert_multi_class(fct, classes = c("factor", "character")) |
62 | ||
63 | 10x |
fct <- as_factor_keep_attributes(fct) |
64 | ||
65 | 10x |
group_levels <- levels(fct) |
66 | 10x |
if (is.null(ref)) { |
67 | 6x |
ref <- group_levels[1] |
68 |
} else { |
|
69 | 4x |
checkmate::assert_subset(ref, group_levels) |
70 |
} |
|
71 | ||
72 | 10x |
groups <- list( |
73 | 10x |
ref = group_levels[group_levels %in% ref], |
74 | 10x |
trt = group_levels[!group_levels %in% ref] |
75 |
) |
|
76 | 10x |
stats::setNames(groups, nm = lapply(groups, paste, collapse = collapse)) |
77 |
} |
|
78 | ||
79 |
#' Split Columns by Groups of Levels |
|
80 |
#' |
|
81 |
#' @description `r lifecycle::badge("stable")` |
|
82 |
#' |
|
83 |
#' @inheritParams argument_convention |
|
84 |
#' @inheritParams groups_list_to_df |
|
85 |
#' @param ... additional arguments to [rtables::split_cols_by()] in order. For instance, to |
|
86 |
#' control formats (`format`), add a joint column for all groups (`incl_all`). |
|
87 |
#' |
|
88 |
#' @return A layout object suitable for passing to further layouting functions. Adding |
|
89 |
#' this function to an `rtable` layout will add a column split including the given |
|
90 |
#' groups to the table layout. |
|
91 |
#' |
|
92 |
#' @seealso [rtables::split_cols_by()] |
|
93 |
#' |
|
94 |
#' @examples |
|
95 |
#' # 1 - Basic use |
|
96 |
#' |
|
97 |
#' # Without group combination `split_cols_by_groups` is |
|
98 |
#' # equivalent to [rtables::split_cols_by()]. |
|
99 |
#' basic_table() %>% |
|
100 |
#' split_cols_by_groups("ARM") %>% |
|
101 |
#' add_colcounts() %>% |
|
102 |
#' analyze("AGE") %>% |
|
103 |
#' build_table(DM) |
|
104 |
#' |
|
105 |
#' # Add a reference column. |
|
106 |
#' basic_table() %>% |
|
107 |
#' split_cols_by_groups("ARM", ref_group = "B: Placebo") %>% |
|
108 |
#' add_colcounts() %>% |
|
109 |
#' analyze( |
|
110 |
#' "AGE", |
|
111 |
#' afun = function(x, .ref_group, .in_ref_col) { |
|
112 |
#' if (.in_ref_col) { |
|
113 |
#' in_rows("Diff Mean" = rcell(NULL)) |
|
114 |
#' } else { |
|
115 |
#' in_rows("Diff Mean" = rcell(mean(x) - mean(.ref_group), format = "xx.xx")) |
|
116 |
#' } |
|
117 |
#' } |
|
118 |
#' ) %>% |
|
119 |
#' build_table(DM) |
|
120 |
#' |
|
121 |
#' # 2 - Adding group specification |
|
122 |
#' |
|
123 |
#' # Manual preparation of the groups. |
|
124 |
#' groups <- list( |
|
125 |
#' "Arms A+B" = c("A: Drug X", "B: Placebo"), |
|
126 |
#' "Arms A+C" = c("A: Drug X", "C: Combination") |
|
127 |
#' ) |
|
128 |
#' |
|
129 |
#' # Use of split_cols_by_groups without reference column. |
|
130 |
#' basic_table() %>% |
|
131 |
#' split_cols_by_groups("ARM", groups) %>% |
|
132 |
#' add_colcounts() %>% |
|
133 |
#' analyze("AGE") %>% |
|
134 |
#' build_table(DM) |
|
135 |
#' |
|
136 |
#' # Including differentiated output in the reference column. |
|
137 |
#' basic_table() %>% |
|
138 |
#' split_cols_by_groups("ARM", groups_list = groups, ref_group = "Arms A+B") %>% |
|
139 |
#' analyze( |
|
140 |
#' "AGE", |
|
141 |
#' afun = function(x, .ref_group, .in_ref_col) { |
|
142 |
#' if (.in_ref_col) { |
|
143 |
#' in_rows("Diff. of Averages" = rcell(NULL)) |
|
144 |
#' } else { |
|
145 |
#' in_rows("Diff. of Averages" = rcell(mean(x) - mean(.ref_group), format = "xx.xx")) |
|
146 |
#' } |
|
147 |
#' } |
|
148 |
#' ) %>% |
|
149 |
#' build_table(DM) |
|
150 |
#' |
|
151 |
#' # 3 - Binary list dividing factor levels into reference and treatment |
|
152 |
#' |
|
153 |
#' # `combine_groups` defines reference and treatment. |
|
154 |
#' groups <- combine_groups( |
|
155 |
#' fct = DM$ARM, |
|
156 |
#' ref = c("A: Drug X", "B: Placebo") |
|
157 |
#' ) |
|
158 |
#' groups |
|
159 |
#' |
|
160 |
#' # Use group definition without reference column. |
|
161 |
#' basic_table() %>% |
|
162 |
#' split_cols_by_groups("ARM", groups_list = groups) %>% |
|
163 |
#' add_colcounts() %>% |
|
164 |
#' analyze("AGE") %>% |
|
165 |
#' build_table(DM) |
|
166 |
#' |
|
167 |
#' # Use group definition with reference column (first item of groups). |
|
168 |
#' basic_table() %>% |
|
169 |
#' split_cols_by_groups("ARM", groups, ref_group = names(groups)[1]) %>% |
|
170 |
#' add_colcounts() %>% |
|
171 |
#' analyze( |
|
172 |
#' "AGE", |
|
173 |
#' afun = function(x, .ref_group, .in_ref_col) { |
|
174 |
#' if (.in_ref_col) { |
|
175 |
#' in_rows("Diff Mean" = rcell(NULL)) |
|
176 |
#' } else { |
|
177 |
#' in_rows("Diff Mean" = rcell(mean(x) - mean(.ref_group), format = "xx.xx")) |
|
178 |
#' } |
|
179 |
#' } |
|
180 |
#' ) %>% |
|
181 |
#' build_table(DM) |
|
182 |
#' |
|
183 |
#' @export |
|
184 |
split_cols_by_groups <- function(lyt, |
|
185 |
var, |
|
186 |
groups_list = NULL, |
|
187 |
ref_group = NULL, |
|
188 |
...) { |
|
189 | 6x |
if (is.null(groups_list)) { |
190 | 2x |
split_cols_by( |
191 | 2x |
lyt = lyt, |
192 | 2x |
var = var, |
193 | 2x |
ref_group = ref_group, |
194 |
... |
|
195 |
) |
|
196 |
} else { |
|
197 | 4x |
groups_df <- groups_list_to_df(groups_list) |
198 | 4x |
if (!is.null(ref_group)) { |
199 | 3x |
ref_group <- groups_df$valname[groups_df$label == ref_group] |
200 |
} |
|
201 | 4x |
split_cols_by( |
202 | 4x |
lyt = lyt, |
203 | 4x |
var = var, |
204 | 4x |
split_fun = add_combo_levels(groups_df, keep_levels = groups_df$valname), |
205 | 4x |
ref_group = ref_group, |
206 |
... |
|
207 |
) |
|
208 |
} |
|
209 |
} |
|
210 | ||
211 |
#' Combine Counts |
|
212 |
#' |
|
213 |
#' Simplifies the estimation of column counts, especially when group combination is required. |
|
214 |
#' |
|
215 |
#' @inheritParams combine_groups |
|
216 |
#' @inheritParams groups_list_to_df |
|
217 |
#' |
|
218 |
#' @return A `vector` of column counts. |
|
219 |
#' |
|
220 |
#' @seealso [combine_groups()] |
|
221 |
#' |
|
222 |
#' @examples |
|
223 |
#' ref <- c("A: Drug X", "B: Placebo") |
|
224 |
#' groups <- combine_groups(fct = DM$ARM, ref = ref) |
|
225 |
#' |
|
226 |
#' col_counts <- combine_counts( |
|
227 |
#' fct = DM$ARM, |
|
228 |
#' groups_list = groups |
|
229 |
#' ) |
|
230 |
#' |
|
231 |
#' basic_table() %>% |
|
232 |
#' split_cols_by_groups("ARM", groups) %>% |
|
233 |
#' add_colcounts() %>% |
|
234 |
#' analyze_vars("AGE") %>% |
|
235 |
#' build_table(DM, col_counts = col_counts) |
|
236 |
#' |
|
237 |
#' ref <- "A: Drug X" |
|
238 |
#' groups <- combine_groups(fct = DM$ARM, ref = ref) |
|
239 |
#' col_counts <- combine_counts( |
|
240 |
#' fct = DM$ARM, |
|
241 |
#' groups_list = groups |
|
242 |
#' ) |
|
243 |
#' |
|
244 |
#' basic_table() %>% |
|
245 |
#' split_cols_by_groups("ARM", groups) %>% |
|
246 |
#' add_colcounts() %>% |
|
247 |
#' analyze_vars("AGE") %>% |
|
248 |
#' build_table(DM, col_counts = col_counts) |
|
249 |
#' |
|
250 |
#' @export |
|
251 |
combine_counts <- function(fct, groups_list = NULL) { |
|
252 | 4x |
checkmate::assert_multi_class(fct, classes = c("factor", "character")) |
253 | ||
254 | 4x |
fct <- as_factor_keep_attributes(fct) |
255 | ||
256 | 4x |
if (is.null(groups_list)) { |
257 | 1x |
y <- table(fct) |
258 | 1x |
y <- stats::setNames(as.numeric(y), nm = dimnames(y)[[1]]) |
259 |
} else { |
|
260 | 3x |
y <- vapply( |
261 | 3x |
X = groups_list, |
262 | 3x |
FUN = function(x) sum(table(fct)[x]), |
263 | 3x |
FUN.VALUE = 1 |
264 |
) |
|
265 |
} |
|
266 | 4x |
y |
267 |
} |
1 |
#' Count Patients with Marked Laboratory Abnormalities |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Primary analysis variable `.var` indicates whether single, replicated or last marked laboratory |
|
6 |
#' abnormality was observed (`factor`). Additional analysis variables are `id` (`character` or `factor`) |
|
7 |
#' and `direction` (`factor`) indicating the direction of the abnormality. Denominator is number of |
|
8 |
#' patients with at least one valid measurement during the analysis. |
|
9 |
#' * For `Single, not last` and `Last or replicated`: Numerator is number of patients |
|
10 |
#' with `Single, not last` and `Last or replicated` levels, respectively. |
|
11 |
#' * For `Any`: Numerator is the number of patients with either single or |
|
12 |
#' replicated marked abnormalities. |
|
13 |
#' |
|
14 |
#' @inheritParams argument_convention |
|
15 |
#' @param category (`list`)\cr with different marked category names for single |
|
16 |
#' and last or replicated. |
|
17 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("abnormal_by_marked")` |
|
18 |
#' to see available statistics for this function. |
|
19 |
#' |
|
20 |
#' @note `Single, not last` and `Last or replicated` levels are mutually exclusive. If a patient has |
|
21 |
#' abnormalities that meet both the `Single, not last` and `Last or replicated` criteria, then the |
|
22 |
#' patient will be counted only under the `Last or replicated` category. |
|
23 |
#' |
|
24 |
#' @name abnormal_by_marked |
|
25 |
#' @order 1 |
|
26 |
NULL |
|
27 | ||
28 |
#' @describeIn abnormal_by_marked Statistics function for patients with marked lab abnormalities. |
|
29 |
#' |
|
30 |
#' @return |
|
31 |
#' * `s_count_abnormal_by_marked()` returns statistic `count_fraction` with `Single, not last`, |
|
32 |
#' `Last or replicated`, and `Any` results. |
|
33 |
#' |
|
34 |
#' @keywords internal |
|
35 |
s_count_abnormal_by_marked <- function(df, |
|
36 |
.var = "AVALCAT1", |
|
37 |
.spl_context, |
|
38 |
category = list(single = "SINGLE", last_replicated = c("LAST", "REPLICATED")), |
|
39 |
variables = list(id = "USUBJID", param = "PARAM", direction = "abn_dir")) { |
|
40 | 3x |
checkmate::assert_string(.var) |
41 | 3x |
checkmate::assert_list(variables) |
42 | 3x |
checkmate::assert_list(category) |
43 | 3x |
checkmate::assert_subset(names(category), c("single", "last_replicated")) |
44 | 3x |
checkmate::assert_subset(names(variables), c("id", "param", "direction")) |
45 | 3x |
checkmate::assert_vector(unique(df[[variables$direction]]), max.len = 1) |
46 | ||
47 | 2x |
assert_df_with_variables(df, c(aval = .var, variables)) |
48 | 2x |
checkmate::assert_multi_class(df[[.var]], classes = c("factor", "character")) |
49 | 2x |
checkmate::assert_multi_class(df[[variables$id]], classes = c("factor", "character")) |
50 | ||
51 | ||
52 | 2x |
first_row <- .spl_context[.spl_context$split == variables[["param"]], ] |
53 |
# Patients in the denominator have at least one post-baseline visit. |
|
54 | 2x |
subj <- first_row$full_parent_df[[1]][[variables[["id"]]]] |
55 | 2x |
subj_cur_col <- subj[first_row$cur_col_subset[[1]]] |
56 |
# Some subjects may have a record for high and low directions but |
|
57 |
# should be counted only once. |
|
58 | 2x |
denom <- length(unique(subj_cur_col)) |
59 | ||
60 | 2x |
if (denom != 0) { |
61 | 2x |
subjects_last_replicated <- unique( |
62 | 2x |
df[df[[.var]] %in% category[["last_replicated"]], variables$id, drop = TRUE] |
63 |
) |
|
64 | 2x |
subjects_single <- unique( |
65 | 2x |
df[df[[.var]] %in% category[["single"]], variables$id, drop = TRUE] |
66 |
) |
|
67 |
# Subjects who have both single and last/replicated abnormalities are counted in only the last/replicated group. |
|
68 | 2x |
subjects_single <- setdiff(subjects_single, subjects_last_replicated) |
69 | 2x |
n_single <- length(subjects_single) |
70 | 2x |
n_last_replicated <- length(subjects_last_replicated) |
71 | 2x |
n_any <- n_single + n_last_replicated |
72 | 2x |
result <- list(count_fraction = list( |
73 | 2x |
"Single, not last" = c(n_single, n_single / denom), |
74 | 2x |
"Last or replicated" = c(n_last_replicated, n_last_replicated / denom), |
75 | 2x |
"Any Abnormality" = c(n_any, n_any / denom) |
76 |
)) |
|
77 |
} else { |
|
78 | ! |
result <- list(count_fraction = list( |
79 | ! |
"Single, not last" = c(0, 0), |
80 | ! |
"Last or replicated" = c(0, 0), |
81 | ! |
"Any Abnormality" = c(0, 0) |
82 |
)) |
|
83 |
} |
|
84 | ||
85 | 2x |
result |
86 |
} |
|
87 | ||
88 |
#' @describeIn abnormal_by_marked Formatted analysis function which is used as `afun` |
|
89 |
#' in `count_abnormal_by_marked()`. |
|
90 |
#' |
|
91 |
#' @return |
|
92 |
#' * `a_count_abnormal_by_marked()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
93 |
#' |
|
94 |
#' @keywords internal |
|
95 |
a_count_abnormal_by_marked <- make_afun( |
|
96 |
s_count_abnormal_by_marked, |
|
97 |
.formats = c(count_fraction = format_count_fraction) |
|
98 |
) |
|
99 | ||
100 |
#' @describeIn abnormal_by_marked Layout-creating function which can take statistics function arguments |
|
101 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
102 |
#' |
|
103 |
#' @return |
|
104 |
#' * `count_abnormal_by_marked()` returns a layout object suitable for passing to further layouting functions, |
|
105 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
106 |
#' the statistics from `s_count_abnormal_by_marked()` to the table layout. |
|
107 |
#' |
|
108 |
#' @examples |
|
109 |
#' library(dplyr) |
|
110 |
#' |
|
111 |
#' df <- data.frame( |
|
112 |
#' USUBJID = as.character(c(rep(1, 5), rep(2, 5), rep(1, 5), rep(2, 5))), |
|
113 |
#' ARMCD = factor(c(rep("ARM A", 5), rep("ARM B", 5), rep("ARM A", 5), rep("ARM B", 5))), |
|
114 |
#' ANRIND = factor(c( |
|
115 |
#' "NORMAL", "HIGH", "HIGH", "HIGH HIGH", "HIGH", |
|
116 |
#' "HIGH", "HIGH", "HIGH HIGH", "NORMAL", "HIGH HIGH", "NORMAL", "LOW", "LOW", "LOW LOW", "LOW", |
|
117 |
#' "LOW", "LOW", "LOW LOW", "NORMAL", "LOW LOW" |
|
118 |
#' )), |
|
119 |
#' ONTRTFL = rep(c("", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y"), 2), |
|
120 |
#' PARAMCD = factor(c(rep("CRP", 10), rep("ALT", 10))), |
|
121 |
#' AVALCAT1 = factor(rep(c("", "", "", "SINGLE", "REPLICATED", "", "", "LAST", "", "SINGLE"), 2)), |
|
122 |
#' stringsAsFactors = FALSE |
|
123 |
#' ) |
|
124 |
#' |
|
125 |
#' df <- df %>% |
|
126 |
#' mutate(abn_dir = factor( |
|
127 |
#' case_when( |
|
128 |
#' ANRIND == "LOW LOW" ~ "Low", |
|
129 |
#' ANRIND == "HIGH HIGH" ~ "High", |
|
130 |
#' TRUE ~ "" |
|
131 |
#' ), |
|
132 |
#' levels = c("Low", "High") |
|
133 |
#' )) |
|
134 |
#' |
|
135 |
#' # Select only post-baseline records. |
|
136 |
#' df <- df %>% filter(ONTRTFL == "Y") |
|
137 |
#' df_crp <- df %>% |
|
138 |
#' filter(PARAMCD == "CRP") %>% |
|
139 |
#' droplevels() |
|
140 |
#' full_parent_df <- list(df_crp, "not_needed") |
|
141 |
#' cur_col_subset <- list(rep(TRUE, nrow(df_crp)), "not_needed") |
|
142 |
#' spl_context <- data.frame( |
|
143 |
#' split = c("PARAMCD", "GRADE_DIR"), |
|
144 |
#' full_parent_df = I(full_parent_df), |
|
145 |
#' cur_col_subset = I(cur_col_subset) |
|
146 |
#' ) |
|
147 |
#' |
|
148 |
#' map <- unique( |
|
149 |
#' df[df$abn_dir %in% c("Low", "High") & df$AVALCAT1 != "", c("PARAMCD", "abn_dir")] |
|
150 |
#' ) %>% |
|
151 |
#' lapply(as.character) %>% |
|
152 |
#' as.data.frame() %>% |
|
153 |
#' arrange(PARAMCD, abn_dir) |
|
154 |
#' |
|
155 |
#' basic_table() %>% |
|
156 |
#' split_cols_by("ARMCD") %>% |
|
157 |
#' split_rows_by("PARAMCD") %>% |
|
158 |
#' summarize_num_patients( |
|
159 |
#' var = "USUBJID", |
|
160 |
#' .stats = "unique_count" |
|
161 |
#' ) %>% |
|
162 |
#' split_rows_by( |
|
163 |
#' "abn_dir", |
|
164 |
#' split_fun = trim_levels_to_map(map) |
|
165 |
#' ) %>% |
|
166 |
#' count_abnormal_by_marked( |
|
167 |
#' var = "AVALCAT1", |
|
168 |
#' variables = list( |
|
169 |
#' id = "USUBJID", |
|
170 |
#' param = "PARAMCD", |
|
171 |
#' direction = "abn_dir" |
|
172 |
#' ) |
|
173 |
#' ) %>% |
|
174 |
#' build_table(df = df) |
|
175 |
#' |
|
176 |
#' basic_table() %>% |
|
177 |
#' split_cols_by("ARMCD") %>% |
|
178 |
#' split_rows_by("PARAMCD") %>% |
|
179 |
#' summarize_num_patients( |
|
180 |
#' var = "USUBJID", |
|
181 |
#' .stats = "unique_count" |
|
182 |
#' ) %>% |
|
183 |
#' split_rows_by( |
|
184 |
#' "abn_dir", |
|
185 |
#' split_fun = trim_levels_in_group("abn_dir") |
|
186 |
#' ) %>% |
|
187 |
#' count_abnormal_by_marked( |
|
188 |
#' var = "AVALCAT1", |
|
189 |
#' variables = list( |
|
190 |
#' id = "USUBJID", |
|
191 |
#' param = "PARAMCD", |
|
192 |
#' direction = "abn_dir" |
|
193 |
#' ) |
|
194 |
#' ) %>% |
|
195 |
#' build_table(df = df) |
|
196 |
#' |
|
197 |
#' @export |
|
198 |
#' @order 2 |
|
199 |
count_abnormal_by_marked <- function(lyt, |
|
200 |
var, |
|
201 |
category = list(single = "SINGLE", last_replicated = c("LAST", "REPLICATED")), |
|
202 |
variables = list(id = "USUBJID", param = "PARAM", direction = "abn_dir"), |
|
203 |
na_str = default_na_str(), |
|
204 |
nested = TRUE, |
|
205 |
..., |
|
206 |
.stats = NULL, |
|
207 |
.formats = NULL, |
|
208 |
.labels = NULL, |
|
209 |
.indent_mods = NULL) { |
|
210 | 1x |
checkmate::assert_string(var) |
211 | ||
212 | 1x |
extra_args <- list(category = category, variables = variables, ...) |
213 | ||
214 | 1x |
afun <- make_afun( |
215 | 1x |
a_count_abnormal_by_marked, |
216 | 1x |
.stats = .stats, |
217 | 1x |
.formats = .formats, |
218 | 1x |
.labels = .labels, |
219 | 1x |
.indent_mods = .indent_mods, |
220 | 1x |
.ungroup_stats = "count_fraction" |
221 |
) |
|
222 | ||
223 | 1x |
lyt <- analyze( |
224 | 1x |
lyt = lyt, |
225 | 1x |
vars = var, |
226 | 1x |
afun = afun, |
227 | 1x |
na_str = na_str, |
228 | 1x |
nested = nested, |
229 | 1x |
show_labels = "hidden", |
230 | 1x |
extra_args = extra_args |
231 |
) |
|
232 | 1x |
lyt |
233 |
} |
1 |
#' Stack Multiple Grobs |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Stack grobs as a new grob with 1 column and multiple rows layout. |
|
6 |
#' |
|
7 |
#' @param ... grobs. |
|
8 |
#' @param grobs list of grobs. |
|
9 |
#' @param padding unit of length 1, space between each grob. |
|
10 |
#' @param vp a [viewport()] object (or `NULL`). |
|
11 |
#' @param name a character identifier for the grob. |
|
12 |
#' @param gp A [gpar()] object. |
|
13 |
#' |
|
14 |
#' @return A `grob`. |
|
15 |
#' |
|
16 |
#' @examples |
|
17 |
#' library(grid) |
|
18 |
#' |
|
19 |
#' g1 <- circleGrob(gp = gpar(col = "blue")) |
|
20 |
#' g2 <- circleGrob(gp = gpar(col = "red")) |
|
21 |
#' g3 <- textGrob("TEST TEXT") |
|
22 |
#' grid.newpage() |
|
23 |
#' grid.draw(stack_grobs(g1, g2, g3)) |
|
24 |
#' |
|
25 |
#' showViewport() |
|
26 |
#' |
|
27 |
#' grid.newpage() |
|
28 |
#' pushViewport(viewport(layout = grid.layout(1, 2))) |
|
29 |
#' vp1 <- viewport(layout.pos.row = 1, layout.pos.col = 2) |
|
30 |
#' grid.draw(stack_grobs(g1, g2, g3, vp = vp1, name = "test")) |
|
31 |
#' |
|
32 |
#' showViewport() |
|
33 |
#' grid.ls(grobs = TRUE, viewports = TRUE, print = FALSE) |
|
34 |
#' |
|
35 |
#' @export |
|
36 |
stack_grobs <- function(..., |
|
37 |
grobs = list(...), |
|
38 |
padding = grid::unit(2, "line"), |
|
39 |
vp = NULL, |
|
40 |
gp = NULL, |
|
41 |
name = NULL) { |
|
42 | 4x |
checkmate::assert_true( |
43 | 4x |
all(vapply(grobs, grid::is.grob, logical(1))) |
44 |
) |
|
45 | ||
46 | 4x |
if (length(grobs) == 1) { |
47 | 1x |
return(grobs[[1]]) |
48 |
} |
|
49 | ||
50 | 3x |
n_layout <- 2 * length(grobs) - 1 |
51 | 3x |
hts <- lapply( |
52 | 3x |
seq(1, n_layout), |
53 | 3x |
function(i) { |
54 | 39x |
if (i %% 2 != 0) { |
55 | 21x |
grid::unit(1, "null") |
56 |
} else { |
|
57 | 18x |
padding |
58 |
} |
|
59 |
} |
|
60 |
) |
|
61 | 3x |
hts <- do.call(grid::unit.c, hts) |
62 | ||
63 | 3x |
main_vp <- grid::viewport( |
64 | 3x |
layout = grid::grid.layout(nrow = n_layout, ncol = 1, heights = hts) |
65 |
) |
|
66 | ||
67 | 3x |
nested_grobs <- Map(function(g, i) { |
68 | 21x |
grid::gTree( |
69 | 21x |
children = grid::gList(g), |
70 | 21x |
vp = grid::viewport(layout.pos.row = i, layout.pos.col = 1) |
71 |
) |
|
72 | 3x |
}, grobs, seq_along(grobs) * 2 - 1) |
73 | ||
74 | 3x |
grobs_mainvp <- grid::gTree( |
75 | 3x |
children = do.call(grid::gList, nested_grobs), |
76 | 3x |
vp = main_vp |
77 |
) |
|
78 | ||
79 | 3x |
grid::gTree( |
80 | 3x |
children = grid::gList(grobs_mainvp), |
81 | 3x |
vp = vp, |
82 | 3x |
gp = gp, |
83 | 3x |
name = name |
84 |
) |
|
85 |
} |
|
86 | ||
87 |
#' Arrange Multiple Grobs |
|
88 |
#' |
|
89 |
#' Arrange grobs as a new grob with \verb{n*m (rows*cols)} layout. |
|
90 |
#' |
|
91 |
#' @inheritParams stack_grobs |
|
92 |
#' @param ncol number of columns in layout. |
|
93 |
#' @param nrow number of rows in layout. |
|
94 |
#' @param padding_ht unit of length 1, vertical space between each grob. |
|
95 |
#' @param padding_wt unit of length 1, horizontal space between each grob. |
|
96 |
#' |
|
97 |
#' @return A `grob`. |
|
98 |
#' @examples |
|
99 |
#' library(grid) |
|
100 |
#' |
|
101 |
#' \donttest{ |
|
102 |
#' num <- lapply(1:9, textGrob) |
|
103 |
#' grid::grid.newpage() |
|
104 |
#' grid.draw(arrange_grobs(grobs = num, ncol = 2)) |
|
105 |
#' |
|
106 |
#' showViewport() |
|
107 |
#' |
|
108 |
#' g1 <- circleGrob(gp = gpar(col = "blue")) |
|
109 |
#' g2 <- circleGrob(gp = gpar(col = "red")) |
|
110 |
#' g3 <- textGrob("TEST TEXT") |
|
111 |
#' grid::grid.newpage() |
|
112 |
#' grid.draw(arrange_grobs(g1, g2, g3, nrow = 2)) |
|
113 |
#' |
|
114 |
#' showViewport() |
|
115 |
#' |
|
116 |
#' grid::grid.newpage() |
|
117 |
#' grid.draw(arrange_grobs(g1, g2, g3, ncol = 3)) |
|
118 |
#' |
|
119 |
#' grid::grid.newpage() |
|
120 |
#' grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2))) |
|
121 |
#' vp1 <- grid::viewport(layout.pos.row = 1, layout.pos.col = 2) |
|
122 |
#' grid.draw(arrange_grobs(g1, g2, g3, ncol = 2, vp = vp1)) |
|
123 |
#' |
|
124 |
#' showViewport() |
|
125 |
#' } |
|
126 |
#' @export |
|
127 |
arrange_grobs <- function(..., |
|
128 |
grobs = list(...), |
|
129 |
ncol = NULL, nrow = NULL, |
|
130 |
padding_ht = grid::unit(2, "line"), |
|
131 |
padding_wt = grid::unit(2, "line"), |
|
132 |
vp = NULL, |
|
133 |
gp = NULL, |
|
134 |
name = NULL) { |
|
135 | 5x |
checkmate::assert_true( |
136 | 5x |
all(vapply(grobs, grid::is.grob, logical(1))) |
137 |
) |
|
138 | ||
139 | 5x |
if (length(grobs) == 1) { |
140 | 1x |
return(grobs[[1]]) |
141 |
} |
|
142 | ||
143 | 4x |
if (is.null(ncol) && is.null(nrow)) { |
144 | 1x |
ncol <- 1 |
145 | 1x |
nrow <- ceiling(length(grobs) / ncol) |
146 | 3x |
} else if (!is.null(ncol) && is.null(nrow)) { |
147 | 1x |
nrow <- ceiling(length(grobs) / ncol) |
148 | 2x |
} else if (is.null(ncol) && !is.null(nrow)) { |
149 | ! |
ncol <- ceiling(length(grobs) / nrow) |
150 |
} |
|
151 | ||
152 | 4x |
if (ncol * nrow < length(grobs)) { |
153 | 1x |
stop("specififed ncol and nrow are not enough for arranging the grobs ") |
154 |
} |
|
155 | ||
156 | 3x |
if (ncol == 1) { |
157 | 2x |
return(stack_grobs(grobs = grobs, padding = padding_ht, vp = vp, gp = gp, name = name)) |
158 |
} |
|
159 | ||
160 | 1x |
n_col <- 2 * ncol - 1 |
161 | 1x |
n_row <- 2 * nrow - 1 |
162 | 1x |
hts <- lapply( |
163 | 1x |
seq(1, n_row), |
164 | 1x |
function(i) { |
165 | 5x |
if (i %% 2 != 0) { |
166 | 3x |
grid::unit(1, "null") |
167 |
} else { |
|
168 | 2x |
padding_ht |
169 |
} |
|
170 |
} |
|
171 |
) |
|
172 | 1x |
hts <- do.call(grid::unit.c, hts) |
173 | ||
174 | 1x |
wts <- lapply( |
175 | 1x |
seq(1, n_col), |
176 | 1x |
function(i) { |
177 | 5x |
if (i %% 2 != 0) { |
178 | 3x |
grid::unit(1, "null") |
179 |
} else { |
|
180 | 2x |
padding_wt |
181 |
} |
|
182 |
} |
|
183 |
) |
|
184 | 1x |
wts <- do.call(grid::unit.c, wts) |
185 | ||
186 | 1x |
main_vp <- grid::viewport( |
187 | 1x |
layout = grid::grid.layout(nrow = n_row, ncol = n_col, widths = wts, heights = hts) |
188 |
) |
|
189 | ||
190 | 1x |
nested_grobs <- list() |
191 | 1x |
k <- 0 |
192 | 1x |
for (i in seq(nrow) * 2 - 1) { |
193 | 3x |
for (j in seq(ncol) * 2 - 1) { |
194 | 9x |
k <- k + 1 |
195 | 9x |
if (k <= length(grobs)) { |
196 | 9x |
nested_grobs <- c( |
197 | 9x |
nested_grobs, |
198 | 9x |
list(grid::gTree( |
199 | 9x |
children = grid::gList(grobs[[k]]), |
200 | 9x |
vp = grid::viewport(layout.pos.row = i, layout.pos.col = j) |
201 |
)) |
|
202 |
) |
|
203 |
} |
|
204 |
} |
|
205 |
} |
|
206 | 1x |
grobs_mainvp <- grid::gTree( |
207 | 1x |
children = do.call(grid::gList, nested_grobs), |
208 | 1x |
vp = main_vp |
209 |
) |
|
210 | ||
211 | 1x |
grid::gTree( |
212 | 1x |
children = grid::gList(grobs_mainvp), |
213 | 1x |
vp = vp, |
214 | 1x |
gp = gp, |
215 | 1x |
name = name |
216 |
) |
|
217 |
} |
|
218 | ||
219 |
#' Draw `grob` |
|
220 |
#' |
|
221 |
#' @description `r lifecycle::badge("stable")` |
|
222 |
#' |
|
223 |
#' Draw grob on device page. |
|
224 |
#' |
|
225 |
#' @param grob grid object |
|
226 |
#' @param newpage draw on a new page |
|
227 |
#' @param vp a [viewport()] object (or `NULL`). |
|
228 |
#' |
|
229 |
#' @return A `grob`. |
|
230 |
#' |
|
231 |
#' @examples |
|
232 |
#' library(dplyr) |
|
233 |
#' library(grid) |
|
234 |
#' |
|
235 |
#' \donttest{ |
|
236 |
#' rect <- rectGrob(width = grid::unit(0.5, "npc"), height = grid::unit(0.5, "npc")) |
|
237 |
#' rect %>% draw_grob(vp = grid::viewport(angle = 45)) |
|
238 |
#' |
|
239 |
#' num <- lapply(1:10, textGrob) |
|
240 |
#' num %>% |
|
241 |
#' arrange_grobs(grobs = .) %>% |
|
242 |
#' draw_grob() |
|
243 |
#' showViewport() |
|
244 |
#' } |
|
245 |
#' |
|
246 |
#' @export |
|
247 |
draw_grob <- function(grob, newpage = TRUE, vp = NULL) { |
|
248 | 3x |
if (newpage) { |
249 | 3x |
grid::grid.newpage() |
250 |
} |
|
251 | 3x |
if (!is.null(vp)) { |
252 | 1x |
grid::pushViewport(vp) |
253 |
} |
|
254 | 3x |
grid::grid.draw(grob) |
255 |
} |
|
256 | ||
257 |
tern_grob <- function(x) { |
|
258 | ! |
class(x) <- unique(c("ternGrob", class(x))) |
259 | ! |
x |
260 |
} |
|
261 | ||
262 |
print.ternGrob <- function(x, ...) { |
|
263 | ! |
grid::grid.newpage() |
264 | ! |
grid::grid.draw(x) |
265 |
} |
1 |
#' Cox Regression Helper: Interactions |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Test and estimate the effect of a treatment in interaction with a covariate. |
|
6 |
#' The effect is estimated as the HR of the tested treatment for a given level |
|
7 |
#' of the covariate, in comparison to the treatment control. |
|
8 |
#' |
|
9 |
#' @inheritParams argument_convention |
|
10 |
#' @param x (`numeric` or `factor`)\cr the values of the covariate to be tested. |
|
11 |
#' @param effect (`string`)\cr the name of the effect to be tested and estimated. |
|
12 |
#' @param covar (`string`)\cr the name of the covariate in the model. |
|
13 |
#' @param mod (`coxph`)\cr the Cox regression model. |
|
14 |
#' @param label (`string`)\cr the label to be returned as `term_label`. |
|
15 |
#' @param control (`list`)\cr a list of controls as returned by [control_coxreg()]. |
|
16 |
#' @param ... see methods. |
|
17 |
#' |
|
18 |
#' @examples |
|
19 |
#' library(survival) |
|
20 |
#' |
|
21 |
#' set.seed(1, kind = "Mersenne-Twister") |
|
22 |
#' |
|
23 |
#' # Testing dataset [survival::bladder]. |
|
24 |
#' dta_bladder <- with( |
|
25 |
#' data = bladder[bladder$enum < 5, ], |
|
26 |
#' data.frame( |
|
27 |
#' time = stop, |
|
28 |
#' status = event, |
|
29 |
#' armcd = as.factor(rx), |
|
30 |
#' covar1 = as.factor(enum), |
|
31 |
#' covar2 = factor( |
|
32 |
#' sample(as.factor(enum)), |
|
33 |
#' levels = 1:4, |
|
34 |
#' labels = c("F", "F", "M", "M") |
|
35 |
#' ) |
|
36 |
#' ) |
|
37 |
#' ) |
|
38 |
#' labels <- c("armcd" = "ARM", "covar1" = "A Covariate Label", "covar2" = "Sex (F/M)") |
|
39 |
#' formatters::var_labels(dta_bladder)[names(labels)] <- labels |
|
40 |
#' dta_bladder$age <- sample(20:60, size = nrow(dta_bladder), replace = TRUE) |
|
41 |
#' |
|
42 |
#' plot( |
|
43 |
#' survfit(Surv(time, status) ~ armcd + covar1, data = dta_bladder), |
|
44 |
#' lty = 2:4, |
|
45 |
#' xlab = "Months", |
|
46 |
#' col = c("blue1", "blue2", "blue3", "blue4", "red1", "red2", "red3", "red4") |
|
47 |
#' ) |
|
48 |
#' |
|
49 |
#' @name cox_regression_inter |
|
50 |
NULL |
|
51 | ||
52 |
#' @describeIn cox_regression_inter S3 generic helper function to determine interaction effect. |
|
53 |
#' |
|
54 |
#' @return |
|
55 |
#' * `h_coxreg_inter_effect()` returns a `data.frame` of covariate interaction effects consisting of the following |
|
56 |
#' variables: `effect`, `term`, `term_label`, `level`, `n`, `hr`, `lcl`, `ucl`, `pval`, and `pval_inter`. |
|
57 |
#' |
|
58 |
#' @export |
|
59 |
h_coxreg_inter_effect <- function(x, |
|
60 |
effect, |
|
61 |
covar, |
|
62 |
mod, |
|
63 |
label, |
|
64 |
control, |
|
65 |
...) { |
|
66 | 26x |
UseMethod("h_coxreg_inter_effect", x) |
67 |
} |
|
68 | ||
69 |
#' @describeIn cox_regression_inter Method for `numeric` class. Estimates the interaction with a `numeric` covariate. |
|
70 |
#' |
|
71 |
#' @method h_coxreg_inter_effect numeric |
|
72 |
#' |
|
73 |
#' @param at (`list`)\cr a list with items named after the covariate, every |
|
74 |
#' item is a vector of levels at which the interaction should be estimated. |
|
75 |
#' |
|
76 |
#' @export |
|
77 |
h_coxreg_inter_effect.numeric <- function(x, |
|
78 |
effect, |
|
79 |
covar, |
|
80 |
mod, |
|
81 |
label, |
|
82 |
control, |
|
83 |
at, |
|
84 |
...) { |
|
85 | 7x |
betas <- stats::coef(mod) |
86 | 7x |
attrs <- attr(stats::terms(mod), "term.labels") |
87 | 7x |
term_indices <- grep( |
88 | 7x |
pattern = effect, |
89 | 7x |
x = attrs[!grepl("strata\\(", attrs)] |
90 |
) |
|
91 | 7x |
checkmate::assert_vector(term_indices, len = 2) |
92 | 7x |
betas <- betas[term_indices] |
93 | 7x |
betas_var <- diag(stats::vcov(mod))[term_indices] |
94 | 7x |
betas_cov <- stats::vcov(mod)[term_indices[1], term_indices[2]] |
95 | 7x |
xval <- if (is.null(at[[covar]])) { |
96 | 6x |
stats::median(x) |
97 |
} else { |
|
98 | 1x |
at[[covar]] |
99 |
} |
|
100 | 7x |
effect_index <- !grepl(covar, names(betas)) |
101 | 7x |
coef_hat <- betas[effect_index] + xval * betas[!effect_index] |
102 | 7x |
coef_se <- sqrt( |
103 | 7x |
betas_var[effect_index] + |
104 | 7x |
xval ^ 2 * betas_var[!effect_index] + # styler: off |
105 | 7x |
2 * xval * betas_cov |
106 |
) |
|
107 | 7x |
q_norm <- stats::qnorm((1 + control$conf_level) / 2) |
108 | 7x |
data.frame( |
109 | 7x |
effect = "Covariate:", |
110 | 7x |
term = rep(covar, length(xval)), |
111 | 7x |
term_label = paste0(" ", xval), |
112 | 7x |
level = as.character(xval), |
113 | 7x |
n = NA, |
114 | 7x |
hr = exp(coef_hat), |
115 | 7x |
lcl = exp(coef_hat - q_norm * coef_se), |
116 | 7x |
ucl = exp(coef_hat + q_norm * coef_se), |
117 | 7x |
pval = NA, |
118 | 7x |
pval_inter = NA, |
119 | 7x |
stringsAsFactors = FALSE |
120 |
) |
|
121 |
} |
|
122 | ||
123 |
#' @describeIn cox_regression_inter Method for `factor` class. Estimate the interaction with a `factor` covariate. |
|
124 |
#' |
|
125 |
#' @method h_coxreg_inter_effect factor |
|
126 |
#' |
|
127 |
#' @param data (`data.frame`)\cr the data frame on which the model was fit. |
|
128 |
#' |
|
129 |
#' @export |
|
130 |
h_coxreg_inter_effect.factor <- function(x, |
|
131 |
effect, |
|
132 |
covar, |
|
133 |
mod, |
|
134 |
label, |
|
135 |
control, |
|
136 |
data, |
|
137 |
...) { |
|
138 | 15x |
lvl_given <- levels(x) |
139 | 15x |
y <- h_coxreg_inter_estimations( |
140 | 15x |
variable = effect, given = covar, |
141 | 15x |
lvl_var = levels(data[[effect]]), |
142 | 15x |
lvl_given = lvl_given, |
143 | 15x |
mod = mod, |
144 | 15x |
conf_level = 0.95 |
145 | 15x |
)[[1]] |
146 | ||
147 | 15x |
data.frame( |
148 | 15x |
effect = "Covariate:", |
149 | 15x |
term = rep(covar, nrow(y)), |
150 | 15x |
term_label = paste0(" ", lvl_given), |
151 | 15x |
level = lvl_given, |
152 | 15x |
n = NA, |
153 | 15x |
hr = y[, "hr"], |
154 | 15x |
lcl = y[, "lcl"], |
155 | 15x |
ucl = y[, "ucl"], |
156 | 15x |
pval = NA, |
157 | 15x |
pval_inter = NA, |
158 | 15x |
stringsAsFactors = FALSE |
159 |
) |
|
160 |
} |
|
161 | ||
162 |
#' @describeIn cox_regression_inter Method for `character` class. Estimate the interaction with a `character` covariate. |
|
163 |
#' This makes an automatic conversion to `factor` and then forwards to the method for factors. |
|
164 |
#' |
|
165 |
#' @method h_coxreg_inter_effect character |
|
166 |
#' |
|
167 |
#' @note |
|
168 |
#' * Automatic conversion of character to factor does not guarantee results can be generated correctly. It is |
|
169 |
#' therefore better to always pre-process the dataset such that factors are manually created from character |
|
170 |
#' variables before passing the dataset to [rtables::build_table()]. |
|
171 |
#' |
|
172 |
#' @export |
|
173 |
h_coxreg_inter_effect.character <- function(x, |
|
174 |
effect, |
|
175 |
covar, |
|
176 |
mod, |
|
177 |
label, |
|
178 |
control, |
|
179 |
data, |
|
180 |
...) { |
|
181 | 4x |
y <- as.factor(x) |
182 | ||
183 | 4x |
h_coxreg_inter_effect( |
184 | 4x |
x = y, |
185 | 4x |
effect = effect, |
186 | 4x |
covar = covar, |
187 | 4x |
mod = mod, |
188 | 4x |
label = label, |
189 | 4x |
control = control, |
190 | 4x |
data = data, |
191 |
... |
|
192 |
) |
|
193 |
} |
|
194 | ||
195 |
#' @describeIn cox_regression_inter A higher level function to get |
|
196 |
#' the results of the interaction test and the estimated values. |
|
197 |
#' |
|
198 |
#' @return |
|
199 |
#' * `h_coxreg_extract_interaction()` returns the result of an interaction test and the estimated values. If |
|
200 |
#' no interaction, [h_coxreg_univar_extract()] is applied instead. |
|
201 |
#' |
|
202 |
#' @examples |
|
203 |
#' mod <- coxph(Surv(time, status) ~ armcd * covar1, data = dta_bladder) |
|
204 |
#' h_coxreg_extract_interaction( |
|
205 |
#' mod = mod, effect = "armcd", covar = "covar1", data = dta_bladder, |
|
206 |
#' control = control_coxreg() |
|
207 |
#' ) |
|
208 |
#' |
|
209 |
#' @export |
|
210 |
h_coxreg_extract_interaction <- function(effect, |
|
211 |
covar, |
|
212 |
mod, |
|
213 |
data, |
|
214 |
at, |
|
215 |
control) { |
|
216 | 27x |
if (!any(attr(stats::terms(mod), "order") == 2)) { |
217 | 10x |
y <- h_coxreg_univar_extract( |
218 | 10x |
effect = effect, covar = covar, mod = mod, data = data, control = control |
219 |
) |
|
220 | 10x |
y$pval_inter <- NA |
221 | 10x |
y |
222 |
} else { |
|
223 | 17x |
test_statistic <- c(wald = "Wald", likelihood = "LR")[control$pval_method] |
224 | ||
225 |
# Test the main treatment effect. |
|
226 | 17x |
mod_aov <- muffled_car_anova(mod, test_statistic) |
227 | 17x |
sum_anova <- broom::tidy(mod_aov) |
228 | 17x |
pval <- sum_anova[sum_anova$term == effect, ][["p.value"]] |
229 | ||
230 |
# Test the interaction effect. |
|
231 | 17x |
pval_inter <- sum_anova[grep(":", sum_anova$term), ][["p.value"]] |
232 | 17x |
covar_test <- data.frame( |
233 | 17x |
effect = "Covariate:", |
234 | 17x |
term = covar, |
235 | 17x |
term_label = unname(labels_or_names(data[covar])), |
236 | 17x |
level = "", |
237 | 17x |
n = mod$n, hr = NA, lcl = NA, ucl = NA, pval = pval, |
238 | 17x |
pval_inter = pval_inter, |
239 | 17x |
stringsAsFactors = FALSE |
240 |
) |
|
241 |
# Estimate the interaction. |
|
242 | 17x |
y <- h_coxreg_inter_effect( |
243 | 17x |
data[[covar]], |
244 | 17x |
covar = covar, |
245 | 17x |
effect = effect, |
246 | 17x |
mod = mod, |
247 | 17x |
label = unname(labels_or_names(data[covar])), |
248 | 17x |
at = at, |
249 | 17x |
control = control, |
250 | 17x |
data = data |
251 |
) |
|
252 | 17x |
rbind(covar_test, y) |
253 |
} |
|
254 |
} |
|
255 | ||
256 |
#' @describeIn cox_regression_inter Hazard ratio estimation in interactions. |
|
257 |
#' |
|
258 |
#' @param variable,given (`string`)\cr the name of variables in interaction. We seek the estimation |
|
259 |
#' of the levels of `variable` given the levels of `given`. |
|
260 |
#' @param lvl_var,lvl_given (`character`)\cr corresponding levels has given by [levels()]. |
|
261 |
#' @param mod (`coxph`)\cr a fitted Cox regression model (see [survival::coxph()]). |
|
262 |
#' |
|
263 |
#' @details Given the cox regression investigating the effect of Arm (A, B, C; reference A) |
|
264 |
#' and Sex (F, M; reference Female) and the model being abbreviated: y ~ Arm + Sex + Arm:Sex. |
|
265 |
#' The cox regression estimates the coefficients along with a variance-covariance matrix for: |
|
266 |
#' |
|
267 |
#' - b1 (arm b), b2 (arm c) |
|
268 |
#' - b3 (sex m) |
|
269 |
#' - b4 (arm b: sex m), b5 (arm c: sex m) |
|
270 |
#' |
|
271 |
#' The estimation of the Hazard Ratio for arm C/sex M is given in reference |
|
272 |
#' to arm A/Sex M by exp(b2 + b3 + b5)/ exp(b3) = exp(b2 + b5). |
|
273 |
#' The interaction coefficient is deduced by b2 + b5 while the standard error |
|
274 |
#' is obtained as $sqrt(Var b2 + Var b5 + 2 * covariance (b2,b5))$. |
|
275 |
#' |
|
276 |
#' @return |
|
277 |
#' * `h_coxreg_inter_estimations()` returns a list of matrices (one per level of variable) with rows corresponding |
|
278 |
#' to the combinations of `variable` and `given`, with columns: |
|
279 |
#' * `coef_hat`: Estimation of the coefficient. |
|
280 |
#' * `coef_se`: Standard error of the estimation. |
|
281 |
#' * `hr`: Hazard ratio. |
|
282 |
#' * `lcl, ucl`: Lower/upper confidence limit of the hazard ratio. |
|
283 |
#' |
|
284 |
#' @examples |
|
285 |
#' mod <- coxph(Surv(time, status) ~ armcd * covar1, data = dta_bladder) |
|
286 |
#' result <- h_coxreg_inter_estimations( |
|
287 |
#' variable = "armcd", given = "covar1", |
|
288 |
#' lvl_var = levels(dta_bladder$armcd), |
|
289 |
#' lvl_given = levels(dta_bladder$covar1), |
|
290 |
#' mod = mod, conf_level = .95 |
|
291 |
#' ) |
|
292 |
#' result |
|
293 |
#' |
|
294 |
#' @export |
|
295 |
h_coxreg_inter_estimations <- function(variable, |
|
296 |
given, |
|
297 |
lvl_var, |
|
298 |
lvl_given, |
|
299 |
mod, |
|
300 |
conf_level = 0.95) { |
|
301 | 16x |
var_lvl <- paste0(variable, lvl_var[-1]) # [-1]: reference level |
302 | 16x |
giv_lvl <- paste0(given, lvl_given) |
303 | 16x |
design_mat <- expand.grid(variable = var_lvl, given = giv_lvl) |
304 | 16x |
design_mat <- design_mat[order(design_mat$variable, design_mat$given), ] |
305 | 16x |
design_mat <- within( |
306 | 16x |
data = design_mat, |
307 | 16x |
expr = { |
308 | 16x |
inter <- paste0(variable, ":", given) |
309 | 16x |
rev_inter <- paste0(given, ":", variable) |
310 |
} |
|
311 |
) |
|
312 | 16x |
split_by_variable <- design_mat$variable |
313 | 16x |
interaction_names <- paste(design_mat$variable, design_mat$given, sep = "/") |
314 | ||
315 | 16x |
mmat <- stats::model.matrix(mod)[1, ] |
316 | 16x |
mmat[!mmat == 0] <- 0 |
317 | ||
318 | 16x |
design_mat <- apply( |
319 | 16x |
X = design_mat, MARGIN = 1, FUN = function(x) { |
320 | 46x |
mmat[names(mmat) %in% x[-which(names(x) == "given")]] <- 1 |
321 | 46x |
mmat |
322 |
} |
|
323 |
) |
|
324 | 16x |
colnames(design_mat) <- interaction_names |
325 | ||
326 | 16x |
coef <- stats::coef(mod) |
327 | 16x |
vcov <- stats::vcov(mod) |
328 | 16x |
betas <- as.matrix(coef) |
329 | 16x |
coef_hat <- t(design_mat) %*% betas |
330 | 16x |
dimnames(coef_hat)[2] <- "coef" |
331 | 16x |
coef_se <- apply( |
332 | 16x |
design_mat, 2, |
333 | 16x |
function(x) { |
334 | 46x |
vcov_el <- as.logical(x) |
335 | 46x |
y <- vcov[vcov_el, vcov_el] |
336 | 46x |
y <- sum(y) |
337 | 46x |
y <- sqrt(y) |
338 | 46x |
return(y) |
339 |
} |
|
340 |
) |
|
341 | 16x |
q_norm <- stats::qnorm((1 + conf_level) / 2) |
342 | 16x |
y <- cbind(coef_hat, `se(coef)` = coef_se) |
343 | 16x |
y <- apply(y, 1, function(x) { |
344 | 46x |
x["hr"] <- exp(x["coef"]) |
345 | 46x |
x["lcl"] <- exp(x["coef"] - q_norm * x["se(coef)"]) |
346 | 46x |
x["ucl"] <- exp(x["coef"] + q_norm * x["se(coef)"]) |
347 | 46x |
x |
348 |
}) |
|
349 | 16x |
y <- t(y) |
350 | 16x |
y <- by(y, split_by_variable, identity) |
351 | 16x |
y <- lapply(y, as.matrix) |
352 | 16x |
attr(y, "details") <- paste0( |
353 | 16x |
"Estimations of ", variable, |
354 | 16x |
" hazard ratio given the level of ", given, " compared to ", |
355 | 16x |
variable, " level ", lvl_var[1], "." |
356 |
) |
|
357 | 16x |
y |
358 |
} |
1 |
#' Controls for Cox Regression |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Sets a list of parameters for Cox regression fit. Used internally. |
|
6 |
#' |
|
7 |
#' @inheritParams argument_convention |
|
8 |
#' @param pval_method (`string`)\cr the method used for estimation of p.values; `wald` (default) or `likelihood`. |
|
9 |
#' @param interaction (`flag`)\cr if `TRUE`, the model includes the interaction between the studied |
|
10 |
#' treatment and candidate covariate. Note that for univariate models without treatment arm, and |
|
11 |
#' multivariate models, no interaction can be used so that this needs to be `FALSE`. |
|
12 |
#' @param ties (`string`)\cr among `exact` (equivalent to `DISCRETE` in SAS), `efron` and `breslow`, |
|
13 |
#' see [survival::coxph()]. Note: there is no equivalent of SAS `EXACT` method in R. |
|
14 |
#' |
|
15 |
#' @return A `list` of items with names corresponding to the arguments. |
|
16 |
#' |
|
17 |
#' @seealso [fit_coxreg_univar()] and [fit_coxreg_multivar()]. |
|
18 |
#' |
|
19 |
#' @examples |
|
20 |
#' control_coxreg() |
|
21 |
#' |
|
22 |
#' @export |
|
23 |
control_coxreg <- function(pval_method = c("wald", "likelihood"), |
|
24 |
ties = c("exact", "efron", "breslow"), |
|
25 |
conf_level = 0.95, |
|
26 |
interaction = FALSE) { |
|
27 | 48x |
pval_method <- match.arg(pval_method) |
28 | 48x |
ties <- match.arg(ties) |
29 | 48x |
checkmate::assert_flag(interaction) |
30 | 48x |
assert_proportion_value(conf_level) |
31 | 48x |
list( |
32 | 48x |
pval_method = pval_method, |
33 | 48x |
ties = ties, |
34 | 48x |
conf_level = conf_level, |
35 | 48x |
interaction = interaction |
36 |
) |
|
37 |
} |
|
38 | ||
39 |
#' Custom Tidy Methods for Cox Regression |
|
40 |
#' |
|
41 |
#' @description `r lifecycle::badge("stable")` |
|
42 |
#' |
|
43 |
#' @inheritParams argument_convention |
|
44 |
#' @param x (`list`)\cr Result of the Cox regression model fitted by [fit_coxreg_univar()] (for univariate models) |
|
45 |
#' or [fit_coxreg_multivar()] (for multivariate models). |
|
46 |
#' |
|
47 |
#' @return [tidy()] returns: |
|
48 |
#' * For `summary.coxph` objects, a `data.frame` with columns: `Pr(>|z|)`, `exp(coef)`, `exp(-coef)`, `lower .95`, |
|
49 |
#' `upper .95`, `level`, and `n`. |
|
50 |
#' * For `coxreg.univar` objects, a `data.frame` with columns: `effect`, `term`, `term_label`, `level`, `n`, `hr`, |
|
51 |
#' `lcl`, `ucl`, `pval`, and `ci`. |
|
52 |
#' * For `coxreg.multivar` objects, a `data.frame` with columns: `term`, `pval`, `term_label`, `hr`, `lcl`, `ucl`, |
|
53 |
#' `level`, and `ci`. |
|
54 |
#' |
|
55 |
#' @seealso [cox_regression] |
|
56 |
#' |
|
57 |
#' @name tidy_coxreg |
|
58 |
NULL |
|
59 | ||
60 |
#' @describeIn tidy_coxreg Custom tidy method for [survival::coxph()] summary results. |
|
61 |
#' |
|
62 |
#' Tidy the [survival::coxph()] results into a `data.frame` to extract model results. |
|
63 |
#' |
|
64 |
#' @method tidy summary.coxph |
|
65 |
#' |
|
66 |
#' @examples |
|
67 |
#' library(survival) |
|
68 |
#' library(broom) |
|
69 |
#' |
|
70 |
#' set.seed(1, kind = "Mersenne-Twister") |
|
71 |
#' |
|
72 |
#' dta_bladder <- with( |
|
73 |
#' data = bladder[bladder$enum < 5, ], |
|
74 |
#' data.frame( |
|
75 |
#' time = stop, |
|
76 |
#' status = event, |
|
77 |
#' armcd = as.factor(rx), |
|
78 |
#' covar1 = as.factor(enum), |
|
79 |
#' covar2 = factor( |
|
80 |
#' sample(as.factor(enum)), |
|
81 |
#' levels = 1:4, labels = c("F", "F", "M", "M") |
|
82 |
#' ) |
|
83 |
#' ) |
|
84 |
#' ) |
|
85 |
#' labels <- c("armcd" = "ARM", "covar1" = "A Covariate Label", "covar2" = "Sex (F/M)") |
|
86 |
#' formatters::var_labels(dta_bladder)[names(labels)] <- labels |
|
87 |
#' dta_bladder$age <- sample(20:60, size = nrow(dta_bladder), replace = TRUE) |
|
88 |
#' |
|
89 |
#' formula <- "survival::Surv(time, status) ~ armcd + covar1" |
|
90 |
#' msum <- summary(coxph(stats::as.formula(formula), data = dta_bladder)) |
|
91 |
#' tidy(msum) |
|
92 |
#' |
|
93 |
#' @export |
|
94 |
tidy.summary.coxph <- function(x, # nolint |
|
95 |
...) { |
|
96 | 136x |
checkmate::assert_class(x, "summary.coxph") |
97 | 136x |
pval <- x$coefficients |
98 | 136x |
confint <- x$conf.int |
99 | 136x |
levels <- rownames(pval) |
100 | ||
101 | 136x |
pval <- tibble::as_tibble(pval) |
102 | 136x |
confint <- tibble::as_tibble(confint) |
103 | ||
104 | 136x |
ret <- cbind(pval[, grepl("Pr", names(pval))], confint) |
105 | 136x |
ret$level <- levels |
106 | 136x |
ret$n <- x[["n"]] |
107 | 136x |
ret |
108 |
} |
|
109 | ||
110 |
#' @describeIn tidy_coxreg Custom tidy method for a univariate Cox regression. |
|
111 |
#' |
|
112 |
#' Tidy up the result of a Cox regression model fitted by [fit_coxreg_univar()]. |
|
113 |
#' |
|
114 |
#' @method tidy coxreg.univar |
|
115 |
#' |
|
116 |
#' @examples |
|
117 |
#' ## Cox regression: arm + 1 covariate. |
|
118 |
#' mod1 <- fit_coxreg_univar( |
|
119 |
#' variables = list( |
|
120 |
#' time = "time", event = "status", arm = "armcd", |
|
121 |
#' covariates = "covar1" |
|
122 |
#' ), |
|
123 |
#' data = dta_bladder, |
|
124 |
#' control = control_coxreg(conf_level = 0.91) |
|
125 |
#' ) |
|
126 |
#' |
|
127 |
#' ## Cox regression: arm + 1 covariate + interaction, 2 candidate covariates. |
|
128 |
#' mod2 <- fit_coxreg_univar( |
|
129 |
#' variables = list( |
|
130 |
#' time = "time", event = "status", arm = "armcd", |
|
131 |
#' covariates = c("covar1", "covar2") |
|
132 |
#' ), |
|
133 |
#' data = dta_bladder, |
|
134 |
#' control = control_coxreg(conf_level = 0.91, interaction = TRUE) |
|
135 |
#' ) |
|
136 |
#' |
|
137 |
#' tidy(mod1) |
|
138 |
#' tidy(mod2) |
|
139 |
#' |
|
140 |
#' @export |
|
141 |
tidy.coxreg.univar <- function(x, # nolint |
|
142 |
...) { |
|
143 | 29x |
checkmate::assert_class(x, "coxreg.univar") |
144 | 29x |
mod <- x$mod |
145 | 29x |
vars <- c(x$vars$arm, x$vars$covariates) |
146 | 29x |
has_arm <- "arm" %in% names(x$vars) |
147 | ||
148 | 29x |
result <- if (!has_arm) { |
149 | 5x |
Map( |
150 | 5x |
mod = mod, vars = vars, |
151 | 5x |
f = function(mod, vars) { |
152 | 6x |
h_coxreg_multivar_extract( |
153 | 6x |
var = vars, |
154 | 6x |
data = x$data, |
155 | 6x |
mod = mod, |
156 | 6x |
control = x$control |
157 |
) |
|
158 |
} |
|
159 |
) |
|
160 | 29x |
} else if (x$control$interaction) { |
161 | 10x |
Map( |
162 | 10x |
mod = mod, covar = vars, |
163 | 10x |
f = function(mod, covar) { |
164 | 22x |
h_coxreg_extract_interaction( |
165 | 22x |
effect = x$vars$arm, covar = covar, mod = mod, data = x$data, |
166 | 22x |
at = x$at, control = x$control |
167 |
) |
|
168 |
} |
|
169 |
) |
|
170 |
} else { |
|
171 | 14x |
Map( |
172 | 14x |
mod = mod, vars = vars, |
173 | 14x |
f = function(mod, vars) { |
174 | 36x |
h_coxreg_univar_extract( |
175 | 36x |
effect = x$vars$arm, covar = vars, data = x$data, mod = mod, |
176 | 36x |
control = x$control |
177 |
) |
|
178 |
} |
|
179 |
) |
|
180 |
} |
|
181 | 29x |
result <- do.call(rbind, result) |
182 | ||
183 | 29x |
result$ci <- Map(lcl = result$lcl, ucl = result$ucl, f = function(lcl, ucl) c(lcl, ucl)) |
184 | 29x |
result$n <- lapply(result$n, empty_vector_if_na) |
185 | 29x |
result$ci <- lapply(result$ci, empty_vector_if_na) |
186 | 29x |
result$hr <- lapply(result$hr, empty_vector_if_na) |
187 | 29x |
if (x$control$interaction) { |
188 | 10x |
result$pval_inter <- lapply(result$pval_inter, empty_vector_if_na) |
189 |
# Remove interaction p-values due to change in specifications. |
|
190 | 10x |
result$pval[result$effect != "Treatment:"] <- NA |
191 |
} |
|
192 | 29x |
result$pval <- lapply(result$pval, empty_vector_if_na) |
193 | 29x |
attr(result, "conf_level") <- x$control$conf_level |
194 | 29x |
result |
195 |
} |
|
196 | ||
197 |
#' @describeIn tidy_coxreg Custom tidy method for a multivariate Cox regression. |
|
198 |
#' |
|
199 |
#' Tidy up the result of a Cox regression model fitted by [fit_coxreg_multivar()]. |
|
200 |
#' |
|
201 |
#' @method tidy coxreg.multivar |
|
202 |
#' |
|
203 |
#' @examples |
|
204 |
#' multivar_model <- fit_coxreg_multivar( |
|
205 |
#' variables = list( |
|
206 |
#' time = "time", event = "status", arm = "armcd", |
|
207 |
#' covariates = c("covar1", "covar2") |
|
208 |
#' ), |
|
209 |
#' data = dta_bladder |
|
210 |
#' ) |
|
211 |
#' broom::tidy(multivar_model) |
|
212 |
#' |
|
213 |
#' @export |
|
214 |
tidy.coxreg.multivar <- function(x, # nolint |
|
215 |
...) { |
|
216 | 8x |
checkmate::assert_class(x, "coxreg.multivar") |
217 | 8x |
vars <- c(x$vars$arm, x$vars$covariates) |
218 | ||
219 |
# Convert the model summaries to data. |
|
220 | 8x |
result <- Map( |
221 | 8x |
vars = vars, |
222 | 8x |
f = function(vars) { |
223 | 28x |
h_coxreg_multivar_extract( |
224 | 28x |
var = vars, data = x$data, |
225 | 28x |
mod = x$mod, control = x$control |
226 |
) |
|
227 |
} |
|
228 |
) |
|
229 | 8x |
result <- do.call(rbind, result) |
230 | ||
231 | 8x |
result$ci <- Map(lcl = result$lcl, ucl = result$ucl, f = function(lcl, ucl) c(lcl, ucl)) |
232 | 8x |
result$ci <- lapply(result$ci, empty_vector_if_na) |
233 | 8x |
result$hr <- lapply(result$hr, empty_vector_if_na) |
234 | 8x |
result$pval <- lapply(result$pval, empty_vector_if_na) |
235 | 8x |
result <- result[, names(result) != "n"] |
236 | 8x |
attr(result, "conf_level") <- x$control$conf_level |
237 | ||
238 | 8x |
result |
239 |
} |
|
240 | ||
241 |
#' Fits for Cox Proportional Hazards Regression |
|
242 |
#' |
|
243 |
#' @description `r lifecycle::badge("stable")` |
|
244 |
#' |
|
245 |
#' Fitting functions for univariate and multivariate Cox regression models. |
|
246 |
#' |
|
247 |
#' @param variables (`list`)\cr a named list corresponds to the names of variables found in `data`, passed as a named |
|
248 |
#' list and corresponding to `time`, `event`, `arm`, `strata`, and `covariates` terms. If `arm` is missing from |
|
249 |
#' `variables`, then only Cox model(s) including the `covariates` will be fitted and the corresponding effect |
|
250 |
#' estimates will be tabulated later. |
|
251 |
#' @param data (`data.frame`)\cr the dataset containing the variables to fit the models. |
|
252 |
#' @param at (`list` of `numeric`)\cr when the candidate covariate is a `numeric`, use `at` to specify |
|
253 |
#' the value of the covariate at which the effect should be estimated. |
|
254 |
#' @param control (`list`)\cr a list of parameters as returned by the helper function [control_coxreg()]. |
|
255 |
#' |
|
256 |
#' @seealso [h_cox_regression] for relevant helper functions, [cox_regression]. |
|
257 |
#' |
|
258 |
#' @examples |
|
259 |
#' library(survival) |
|
260 |
#' |
|
261 |
#' set.seed(1, kind = "Mersenne-Twister") |
|
262 |
#' |
|
263 |
#' # Testing dataset [survival::bladder]. |
|
264 |
#' dta_bladder <- with( |
|
265 |
#' data = bladder[bladder$enum < 5, ], |
|
266 |
#' data.frame( |
|
267 |
#' time = stop, |
|
268 |
#' status = event, |
|
269 |
#' armcd = as.factor(rx), |
|
270 |
#' covar1 = as.factor(enum), |
|
271 |
#' covar2 = factor( |
|
272 |
#' sample(as.factor(enum)), |
|
273 |
#' levels = 1:4, labels = c("F", "F", "M", "M") |
|
274 |
#' ) |
|
275 |
#' ) |
|
276 |
#' ) |
|
277 |
#' labels <- c("armcd" = "ARM", "covar1" = "A Covariate Label", "covar2" = "Sex (F/M)") |
|
278 |
#' formatters::var_labels(dta_bladder)[names(labels)] <- labels |
|
279 |
#' dta_bladder$age <- sample(20:60, size = nrow(dta_bladder), replace = TRUE) |
|
280 |
#' |
|
281 |
#' plot( |
|
282 |
#' survfit(Surv(time, status) ~ armcd + covar1, data = dta_bladder), |
|
283 |
#' lty = 2:4, |
|
284 |
#' xlab = "Months", |
|
285 |
#' col = c("blue1", "blue2", "blue3", "blue4", "red1", "red2", "red3", "red4") |
|
286 |
#' ) |
|
287 |
#' |
|
288 |
#' @name fit_coxreg |
|
289 |
NULL |
|
290 | ||
291 |
#' @describeIn fit_coxreg Fit a series of univariate Cox regression models given the inputs. |
|
292 |
#' |
|
293 |
#' @return |
|
294 |
#' * `fit_coxreg_univar()` returns a `coxreg.univar` class object which is a named `list` |
|
295 |
#' with 5 elements: |
|
296 |
#' * `mod`: Cox regression models fitted by [survival::coxph()]. |
|
297 |
#' * `data`: The original data frame input. |
|
298 |
#' * `control`: The original control input. |
|
299 |
#' * `vars`: The variables used in the model. |
|
300 |
#' * `at`: Value of the covariate at which the effect should be estimated. |
|
301 |
#' |
|
302 |
#' @note When using `fit_coxreg_univar` there should be two study arms. |
|
303 |
#' |
|
304 |
#' @examples |
|
305 |
#' # fit_coxreg_univar |
|
306 |
#' |
|
307 |
#' ## Cox regression: arm + 1 covariate. |
|
308 |
#' mod1 <- fit_coxreg_univar( |
|
309 |
#' variables = list( |
|
310 |
#' time = "time", event = "status", arm = "armcd", |
|
311 |
#' covariates = "covar1" |
|
312 |
#' ), |
|
313 |
#' data = dta_bladder, |
|
314 |
#' control = control_coxreg(conf_level = 0.91) |
|
315 |
#' ) |
|
316 |
#' |
|
317 |
#' ## Cox regression: arm + 1 covariate + interaction, 2 candidate covariates. |
|
318 |
#' mod2 <- fit_coxreg_univar( |
|
319 |
#' variables = list( |
|
320 |
#' time = "time", event = "status", arm = "armcd", |
|
321 |
#' covariates = c("covar1", "covar2") |
|
322 |
#' ), |
|
323 |
#' data = dta_bladder, |
|
324 |
#' control = control_coxreg(conf_level = 0.91, interaction = TRUE) |
|
325 |
#' ) |
|
326 |
#' |
|
327 |
#' ## Cox regression: arm + 1 covariate, stratified analysis. |
|
328 |
#' mod3 <- fit_coxreg_univar( |
|
329 |
#' variables = list( |
|
330 |
#' time = "time", event = "status", arm = "armcd", strata = "covar2", |
|
331 |
#' covariates = c("covar1") |
|
332 |
#' ), |
|
333 |
#' data = dta_bladder, |
|
334 |
#' control = control_coxreg(conf_level = 0.91) |
|
335 |
#' ) |
|
336 |
#' |
|
337 |
#' ## Cox regression: no arm, only covariates. |
|
338 |
#' mod4 <- fit_coxreg_univar( |
|
339 |
#' variables = list( |
|
340 |
#' time = "time", event = "status", |
|
341 |
#' covariates = c("covar1", "covar2") |
|
342 |
#' ), |
|
343 |
#' data = dta_bladder |
|
344 |
#' ) |
|
345 |
#' |
|
346 |
#' @export |
|
347 |
fit_coxreg_univar <- function(variables, |
|
348 |
data, |
|
349 |
at = list(), |
|
350 |
control = control_coxreg()) { |
|
351 | 34x |
checkmate::assert_list(variables, names = "named") |
352 | 34x |
has_arm <- "arm" %in% names(variables) |
353 | 34x |
arm_name <- if (has_arm) "arm" else NULL |
354 | ||
355 | 34x |
checkmate::assert_character(variables$covariates, null.ok = TRUE) |
356 | ||
357 | 34x |
assert_df_with_variables(data, variables) |
358 | 34x |
assert_list_of_variables(variables[c(arm_name, "event", "time")]) |
359 | ||
360 | 34x |
if (!is.null(variables$strata)) { |
361 | 4x |
checkmate::assert_disjunct(control$pval_method, "likelihood") |
362 |
} |
|
363 | 33x |
if (has_arm) { |
364 | 27x |
assert_df_with_factors(data, list(val = variables$arm), min.levels = 2, max.levels = 2) |
365 |
} |
|
366 | 32x |
vars <- unlist(variables[c(arm_name, "covariates", "strata")], use.names = FALSE) |
367 | 32x |
for (i in vars) { |
368 | 73x |
if (is.factor(data[[i]])) { |
369 | 63x |
attr(data[[i]], "levels") <- levels(droplevels(data[[i]])) |
370 |
} |
|
371 |
} |
|
372 | 32x |
forms <- h_coxreg_univar_formulas(variables, interaction = control$interaction) |
373 | 32x |
mod <- lapply( |
374 | 32x |
forms, function(x) { |
375 | 69x |
survival::coxph(formula = stats::as.formula(x), data = data, ties = control$ties) |
376 |
} |
|
377 |
) |
|
378 | 32x |
structure( |
379 | 32x |
list( |
380 | 32x |
mod = mod, |
381 | 32x |
data = data, |
382 | 32x |
control = control, |
383 | 32x |
vars = variables, |
384 | 32x |
at = at |
385 |
), |
|
386 | 32x |
class = "coxreg.univar" |
387 |
) |
|
388 |
} |
|
389 | ||
390 |
#' @describeIn fit_coxreg Fit a multivariate Cox regression model. |
|
391 |
#' |
|
392 |
#' @return |
|
393 |
#' * `fit_coxreg_multivar()` returns a `coxreg.multivar` class object which is a named list |
|
394 |
#' with 4 elements: |
|
395 |
#' * `mod`: Cox regression model fitted by [survival::coxph()]. |
|
396 |
#' * `data`: The original data frame input. |
|
397 |
#' * `control`: The original control input. |
|
398 |
#' * `vars`: The variables used in the model. |
|
399 |
#' |
|
400 |
#' @examples |
|
401 |
#' # fit_coxreg_multivar |
|
402 |
#' |
|
403 |
#' ## Cox regression: multivariate Cox regression. |
|
404 |
#' multivar_model <- fit_coxreg_multivar( |
|
405 |
#' variables = list( |
|
406 |
#' time = "time", event = "status", arm = "armcd", |
|
407 |
#' covariates = c("covar1", "covar2") |
|
408 |
#' ), |
|
409 |
#' data = dta_bladder |
|
410 |
#' ) |
|
411 |
#' |
|
412 |
#' # Example without treatment arm. |
|
413 |
#' multivar_covs_model <- fit_coxreg_multivar( |
|
414 |
#' variables = list( |
|
415 |
#' time = "time", event = "status", |
|
416 |
#' covariates = c("covar1", "covar2") |
|
417 |
#' ), |
|
418 |
#' data = dta_bladder |
|
419 |
#' ) |
|
420 |
#' |
|
421 |
#' @export |
|
422 |
fit_coxreg_multivar <- function(variables, |
|
423 |
data, |
|
424 |
control = control_coxreg()) { |
|
425 | 63x |
checkmate::assert_list(variables, names = "named") |
426 | 63x |
has_arm <- "arm" %in% names(variables) |
427 | 63x |
arm_name <- if (has_arm) "arm" else NULL |
428 | ||
429 | 63x |
if (!is.null(variables$covariates)) { |
430 | 13x |
checkmate::assert_character(variables$covariates) |
431 |
} |
|
432 | ||
433 | 63x |
checkmate::assert_false(control$interaction) |
434 | 63x |
assert_df_with_variables(data, variables) |
435 | 63x |
assert_list_of_variables(variables[c(arm_name, "event", "time")]) |
436 | ||
437 | 63x |
if (!is.null(variables$strata)) { |
438 | 3x |
checkmate::assert_disjunct(control$pval_method, "likelihood") |
439 |
} |
|
440 | ||
441 | 62x |
form <- h_coxreg_multivar_formula(variables) |
442 | 62x |
mod <- survival::coxph( |
443 | 62x |
formula = stats::as.formula(form), |
444 | 62x |
data = data, |
445 | 62x |
ties = control$ties |
446 |
) |
|
447 | 62x |
structure( |
448 | 62x |
list( |
449 | 62x |
mod = mod, |
450 | 62x |
data = data, |
451 | 62x |
control = control, |
452 | 62x |
vars = variables |
453 |
), |
|
454 | 62x |
class = "coxreg.multivar" |
455 |
) |
|
456 |
} |
|
457 | ||
458 |
#' Muffled `car::Anova` |
|
459 |
#' |
|
460 |
#' Applied on survival models, [car::Anova()] signal that the `strata` terms is dropped from the model formula when |
|
461 |
#' present, this function deliberately muffles this message. |
|
462 |
#' |
|
463 |
#' @param mod (`coxph`)\cr Cox regression model fitted by [survival::coxph()]. |
|
464 |
#' @param test_statistic (`string`)\cr the method used for estimation of p.values; `wald` (default) or `likelihood`. |
|
465 |
#' |
|
466 |
#' @return Returns the output of [car::Anova()], with convergence message muffled. |
|
467 |
#' |
|
468 |
#' @keywords internal |
|
469 |
muffled_car_anova <- function(mod, test_statistic) { |
|
470 | 154x |
tryCatch( |
471 | 154x |
withCallingHandlers( |
472 | 154x |
expr = { |
473 | 154x |
car::Anova( |
474 | 154x |
mod, |
475 | 154x |
test.statistic = test_statistic, |
476 | 154x |
type = "III" |
477 |
) |
|
478 |
}, |
|
479 | 154x |
message = function(m) invokeRestart("muffleMessage"), |
480 | 154x |
error = function(e) { |
481 | 1x |
stop(paste( |
482 | 1x |
"the model seems to have convergence problems, please try to change", |
483 | 1x |
"the configuration of covariates or strata variables, e.g.", |
484 | 1x |
"- original error:", e |
485 |
)) |
|
486 |
} |
|
487 |
) |
|
488 |
) |
|
489 |
} |
1 |
#' Counting Specific Values |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' We can count the occurrence of specific values in a variable of interest. |
|
6 |
#' |
|
7 |
#' @inheritParams argument_convention |
|
8 |
#' @param values (`character`)\cr specific values that should be counted. |
|
9 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("count_values")` |
|
10 |
#' to see available statistics for this function. |
|
11 |
#' |
|
12 |
#' @note |
|
13 |
#' * For `factor` variables, `s_count_values` checks whether `values` are all included in the levels of `x` |
|
14 |
#' and fails otherwise. |
|
15 |
#' * For `count_values()`, variable labels are shown when there is more than one element in `vars`, |
|
16 |
#' otherwise they are hidden. |
|
17 |
#' |
|
18 |
#' @name count_values_funs |
|
19 |
#' @order 1 |
|
20 |
NULL |
|
21 | ||
22 |
#' @describeIn count_values_funs S3 generic function to count values. |
|
23 |
#' |
|
24 |
#' @inheritParams s_summary.logical |
|
25 |
#' |
|
26 |
#' @return |
|
27 |
#' * `s_count_values()` returns output of [s_summary()] for specified values of a non-numeric variable. |
|
28 |
#' |
|
29 |
#' @export |
|
30 |
s_count_values <- function(x, |
|
31 |
values, |
|
32 |
na.rm = TRUE, # nolint |
|
33 |
.N_col, # nolint |
|
34 |
.N_row, # nolint |
|
35 |
denom = c("n", "N_row", "N_col")) { |
|
36 | 110x |
UseMethod("s_count_values", x) |
37 |
} |
|
38 | ||
39 |
#' @describeIn count_values_funs Method for `character` class. |
|
40 |
#' |
|
41 |
#' @method s_count_values character |
|
42 |
#' |
|
43 |
#' @examples |
|
44 |
#' # `s_count_values.character` |
|
45 |
#' s_count_values(x = c("a", "b", "a"), values = "a") |
|
46 |
#' s_count_values(x = c("a", "b", "a", NA, NA), values = "b", na.rm = FALSE) |
|
47 |
#' |
|
48 |
#' @export |
|
49 |
s_count_values.character <- function(x, |
|
50 |
values = "Y", |
|
51 |
na.rm = TRUE, # nolint |
|
52 |
...) { |
|
53 | 108x |
checkmate::assert_character(values) |
54 | ||
55 | 108x |
if (na.rm) { |
56 | 108x |
x <- x[!is.na(x)] |
57 |
} |
|
58 | ||
59 | 108x |
is_in_values <- x %in% values |
60 | ||
61 | 108x |
s_summary(is_in_values, ...) |
62 |
} |
|
63 | ||
64 |
#' @describeIn count_values_funs Method for `factor` class. This makes an automatic |
|
65 |
#' conversion to `character` and then forwards to the method for characters. |
|
66 |
#' |
|
67 |
#' @method s_count_values factor |
|
68 |
#' |
|
69 |
#' @examples |
|
70 |
#' # `s_count_values.factor` |
|
71 |
#' s_count_values(x = factor(c("a", "b", "a")), values = "a") |
|
72 |
#' |
|
73 |
#' @export |
|
74 |
s_count_values.factor <- function(x, |
|
75 |
values = "Y", |
|
76 |
...) { |
|
77 | 3x |
s_count_values(as.character(x), values = as.character(values), ...) |
78 |
} |
|
79 | ||
80 |
#' @describeIn count_values_funs Method for `logical` class. |
|
81 |
#' |
|
82 |
#' @method s_count_values logical |
|
83 |
#' |
|
84 |
#' @examples |
|
85 |
#' # `s_count_values.logical` |
|
86 |
#' s_count_values(x = c(TRUE, FALSE, TRUE)) |
|
87 |
#' |
|
88 |
#' @export |
|
89 |
s_count_values.logical <- function(x, values = TRUE, ...) { |
|
90 | 3x |
checkmate::assert_logical(values) |
91 | 3x |
s_count_values(as.character(x), values = as.character(values), ...) |
92 |
} |
|
93 | ||
94 |
#' @describeIn count_values_funs Formatted analysis function which is used as `afun` |
|
95 |
#' in `count_values()`. |
|
96 |
#' |
|
97 |
#' @return |
|
98 |
#' * `a_count_values()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
99 |
#' |
|
100 |
#' @examples |
|
101 |
#' # `a_count_values` |
|
102 |
#' a_count_values(x = factor(c("a", "b", "a")), values = "a", .N_col = 10, .N_row = 10) |
|
103 |
#' |
|
104 |
#' @export |
|
105 |
a_count_values <- make_afun( |
|
106 |
s_count_values, |
|
107 |
.formats = c(count_fraction = "xx (xx.xx%)", count = "xx") |
|
108 |
) |
|
109 | ||
110 |
#' @describeIn count_values_funs Layout-creating function which can take statistics function arguments |
|
111 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
112 |
#' |
|
113 |
#' @return |
|
114 |
#' * `count_values()` returns a layout object suitable for passing to further layouting functions, |
|
115 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
116 |
#' the statistics from `s_count_values()` to the table layout. |
|
117 |
#' |
|
118 |
#' @examples |
|
119 |
#' # `count_values` |
|
120 |
#' basic_table() %>% |
|
121 |
#' count_values("Species", values = "setosa") %>% |
|
122 |
#' build_table(iris) |
|
123 |
#' |
|
124 |
#' @export |
|
125 |
#' @order 2 |
|
126 |
count_values <- function(lyt, |
|
127 |
vars, |
|
128 |
values, |
|
129 |
na_str = default_na_str(), |
|
130 |
nested = TRUE, |
|
131 |
..., |
|
132 |
table_names = vars, |
|
133 |
.stats = "count_fraction", |
|
134 |
.formats = NULL, |
|
135 |
.labels = c(count_fraction = paste(values, collapse = ", ")), |
|
136 |
.indent_mods = NULL) { |
|
137 | 3x |
extra_args <- list(values = values, ...) |
138 | ||
139 | 3x |
afun <- make_afun( |
140 | 3x |
a_count_values, |
141 | 3x |
.stats = .stats, |
142 | 3x |
.formats = .formats, |
143 | 3x |
.labels = .labels, |
144 | 3x |
.indent_mods = .indent_mods |
145 |
) |
|
146 | 3x |
analyze( |
147 | 3x |
lyt, |
148 | 3x |
vars, |
149 | 3x |
afun = afun, |
150 | 3x |
na_str = na_str, |
151 | 3x |
nested = nested, |
152 | 3x |
extra_args = extra_args, |
153 | 3x |
show_labels = ifelse(length(vars) > 1, "visible", "hidden"), |
154 | 3x |
table_names = table_names |
155 |
) |
|
156 |
} |
1 |
#' Summary for Poisson Negative Binomial. |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("experimental")` |
|
4 |
#' |
|
5 |
#' Summarize results of a Poisson Negative Binomial Regression. |
|
6 |
#' This can be used to analyze count and/or frequency data using a linear model. |
|
7 |
#' |
|
8 |
#' @inheritParams h_glm_count |
|
9 |
#' @inheritParams argument_convention |
|
10 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("summarize_glm_count")` |
|
11 |
#' to see available statistics for this function. |
|
12 |
#' |
|
13 |
#' @name summarize_glm_count |
|
14 |
#' @order 1 |
|
15 |
NULL |
|
16 | ||
17 |
#' Helper Functions for Poisson Models. |
|
18 |
#' |
|
19 |
#' @description `r lifecycle::badge("experimental")` |
|
20 |
#' |
|
21 |
#' Helper functions that can be used to return the results of various Poisson models. |
|
22 |
#' |
|
23 |
#' @inheritParams argument_convention |
|
24 |
#' |
|
25 |
#' @seealso [summarize_glm_count] |
|
26 |
#' |
|
27 |
#' @name h_glm_count |
|
28 |
NULL |
|
29 | ||
30 |
#' @describeIn h_glm_count Helper function to return results of a poisson model. |
|
31 |
#' |
|
32 |
#' @param .df_row (`data.frame`)\cr data set that includes all the variables that are called |
|
33 |
#' in `.var` and `variables`. |
|
34 |
#' @param variables (named `list` of `strings`)\cr list of additional analysis variables, with |
|
35 |
#' expected elements: |
|
36 |
#' * `arm` (`string`)\cr group variable, for which the covariate adjusted means of multiple |
|
37 |
#' groups will be summarized. Specifically, the first level of `arm` variable is taken as the |
|
38 |
#' reference group. |
|
39 |
#' * `covariates` (`character`)\cr a vector that can contain single variable names (such as |
|
40 |
#' `"X1"`), and/or interaction terms indicated by `"X1 * X2"`. |
|
41 |
#' * `offset` (`numeric`)\cr a numeric vector or scalar adding an offset. |
|
42 |
#' @param weights (`character`)\cr a character vector specifying weights used |
|
43 |
#' in averaging predictions. Number of weights must equal the number of levels included in the covariates. |
|
44 |
#' Weights option passed to [emmeans::emmeans()]. |
|
45 |
#' |
|
46 |
#' @return |
|
47 |
#' * `h_glm_poisson()` returns the results of a Poisson model. |
|
48 |
#' |
|
49 |
#' @keywords internal |
|
50 |
h_glm_poisson <- function(.var, |
|
51 |
.df_row, |
|
52 |
variables, |
|
53 |
weights) { |
|
54 | 15x |
arm <- variables$arm |
55 | 15x |
covariates <- variables$covariates |
56 | 15x |
offset <- .df_row[[variables$offset]] |
57 | ||
58 | 13x |
formula <- stats::as.formula(paste0( |
59 | 13x |
.var, " ~ ", |
60 |
" + ", |
|
61 | 13x |
paste(covariates, collapse = " + "), |
62 |
" + ", |
|
63 | 13x |
arm |
64 |
)) |
|
65 | ||
66 | 13x |
glm_fit <- stats::glm( |
67 | 13x |
formula = formula, |
68 | 13x |
offset = offset, |
69 | 13x |
data = .df_row, |
70 | 13x |
family = stats::poisson(link = "log") |
71 |
) |
|
72 | ||
73 | 13x |
emmeans_fit <- emmeans::emmeans( |
74 | 13x |
glm_fit, |
75 | 13x |
specs = arm, |
76 | 13x |
data = .df_row, |
77 | 13x |
type = "response", |
78 | 13x |
offset = 0, |
79 | 13x |
weights = weights |
80 |
) |
|
81 | ||
82 | 13x |
list( |
83 | 13x |
glm_fit = glm_fit, |
84 | 13x |
emmeans_fit = emmeans_fit |
85 |
) |
|
86 |
} |
|
87 | ||
88 |
#' @describeIn h_glm_count Helper function to return results of a quasipoisson model. |
|
89 |
#' |
|
90 |
#' @inheritParams summarize_glm_count |
|
91 |
#' |
|
92 |
#' @return |
|
93 |
#' * `h_glm_quasipoisson()` returns the results of a Quasi-Poisson model. |
|
94 |
#' |
|
95 |
#' @keywords internal |
|
96 |
h_glm_quasipoisson <- function(.var, |
|
97 |
.df_row, |
|
98 |
variables, |
|
99 |
weights) { |
|
100 | 4x |
arm <- variables$arm |
101 | 4x |
covariates <- variables$covariates |
102 | 4x |
offset <- .df_row[[variables$offset]] |
103 | ||
104 | 2x |
formula <- stats::as.formula(paste0( |
105 | 2x |
.var, " ~ ", |
106 |
" + ", |
|
107 | 2x |
paste(covariates, collapse = " + "), |
108 |
" + ", |
|
109 | 2x |
arm |
110 |
)) |
|
111 | ||
112 | 2x |
glm_fit <- stats::glm( |
113 | 2x |
formula = formula, |
114 | 2x |
offset = offset, |
115 | 2x |
data = .df_row, |
116 | 2x |
family = stats::quasipoisson(link = "log") |
117 |
) |
|
118 | ||
119 | 2x |
emmeans_fit <- emmeans::emmeans( |
120 | 2x |
glm_fit, |
121 | 2x |
specs = arm, |
122 | 2x |
data = .df_row, |
123 | 2x |
type = "response", |
124 | 2x |
offset = 0, |
125 | 2x |
weights = weights |
126 |
) |
|
127 | ||
128 | 2x |
list( |
129 | 2x |
glm_fit = glm_fit, |
130 | 2x |
emmeans_fit = emmeans_fit |
131 |
) |
|
132 |
} |
|
133 | ||
134 |
#' @describeIn h_glm_count Helper function to return the results of the |
|
135 |
#' selected model (poisson, quasipoisson, negative binomial). |
|
136 |
#' |
|
137 |
#' @param .df_row (`data.frame`)\cr data set that includes all the variables that are called |
|
138 |
#' in `.var` and `variables`. |
|
139 |
#' @param variables (named `list` of `strings`)\cr list of additional analysis variables, with |
|
140 |
#' expected elements: |
|
141 |
#' * `arm` (`string`)\cr group variable, for which the covariate adjusted means of multiple |
|
142 |
#' groups will be summarized. Specifically, the first level of `arm` variable is taken as the |
|
143 |
#' reference group. |
|
144 |
#' * `covariates` (`character`)\cr a vector that can contain single variable names (such as |
|
145 |
#' `"X1"`), and/or interaction terms indicated by `"X1 * X2"`. |
|
146 |
#' * `offset` (`numeric`)\cr a numeric vector or scalar adding an offset. |
|
147 |
#' @param distribution (`character`)\cr a character value specifying the distribution |
|
148 |
#' used in the regression (poisson, quasipoisson). |
|
149 |
#' |
|
150 |
#' @return |
|
151 |
#' * `h_glm_count()` returns the results of the selected model. |
|
152 |
#' |
|
153 |
#' @keywords internal |
|
154 |
h_glm_count <- function(.var, |
|
155 |
.df_row, |
|
156 |
variables, |
|
157 |
distribution, |
|
158 |
weights) { |
|
159 | 14x |
if (distribution == "negbin") { |
160 | ! |
stop("negative binomial distribution is not currently available.") |
161 |
} |
|
162 | 12x |
switch(distribution, |
163 | 12x |
poisson = h_glm_poisson(.var, .df_row, variables, weights), |
164 | ! |
quasipoisson = h_glm_quasipoisson(.var, .df_row, variables, weights), |
165 | ! |
negbin = list() # h_glm_negbin(.var, .df_row, variables, weights) # nolint |
166 |
) |
|
167 |
} |
|
168 | ||
169 |
#' @describeIn h_glm_count Helper function to return the estimated means. |
|
170 |
#' |
|
171 |
#' @param .df_row (`data.frame`)\cr data set that includes all the variables that are called in `.var` and `variables`. |
|
172 |
#' @param conf_level (`numeric`)\cr value used to derive the confidence interval for the rate. |
|
173 |
#' @param obj (`glm.fit`)\cr fitted model object used to derive the mean rate estimates in each treatment arm. |
|
174 |
#' @param arm (`string`)\cr group variable, for which the covariate adjusted means of multiple groups will be |
|
175 |
#' summarized. Specifically, the first level of `arm` variable is taken as the reference group. |
|
176 |
#' |
|
177 |
#' @return |
|
178 |
#' * `h_ppmeans()` returns the estimated means. |
|
179 |
#' |
|
180 |
#' @keywords internal |
|
181 |
h_ppmeans <- function(obj, .df_row, arm, conf_level) { |
|
182 | ! |
alpha <- 1 - conf_level |
183 | ! |
p <- 1 - alpha / 2 |
184 | ||
185 | ! |
arm_levels <- levels(.df_row[[arm]]) |
186 | ||
187 | ! |
out <- lapply(arm_levels, function(lev) { |
188 | ! |
temp <- .df_row |
189 | ! |
temp[[arm]] <- factor(lev, levels = arm_levels) |
190 | ||
191 | ! |
mf <- stats::model.frame(obj$formula, data = temp) |
192 | ! |
X <- stats::model.matrix(obj$formula, data = mf) # nolint |
193 | ||
194 | ! |
rate <- stats::predict(obj, newdata = mf, type = "response") |
195 | ! |
rate_hat <- mean(rate) |
196 | ||
197 | ! |
zz <- colMeans(rate * X) |
198 | ! |
se <- sqrt(as.numeric(t(zz) %*% stats::vcov(obj) %*% zz)) |
199 | ! |
rate_lwr <- rate_hat * exp(-stats::qnorm(p) * se / rate_hat) |
200 | ! |
rate_upr <- rate_hat * exp(stats::qnorm(p) * se / rate_hat) |
201 | ||
202 | ! |
c(rate_hat, rate_lwr, rate_upr) |
203 |
}) |
|
204 | ||
205 | ! |
names(out) <- arm_levels |
206 | ! |
out <- do.call(rbind, out) |
207 | ! |
if ("negbin" %in% class(obj)) { |
208 | ! |
colnames(out) <- c("response", "asymp.LCL", "asymp.UCL") |
209 |
} else { |
|
210 | ! |
colnames(out) <- c("rate", "asymp.LCL", "asymp.UCL") |
211 |
} |
|
212 | ! |
out <- as.data.frame(out) |
213 | ! |
out[[arm]] <- rownames(out) |
214 | ! |
out |
215 |
} |
|
216 | ||
217 |
#' @describeIn summarize_glm_count Statistics function that produces a named list of results |
|
218 |
#' of the investigated Poisson model. |
|
219 |
#' |
|
220 |
#' @return |
|
221 |
#' * `s_glm_count()` returns a named `list` of 5 statistics: |
|
222 |
#' * `n`: Count of complete sample size for the group. |
|
223 |
#' * `rate`: Estimated event rate per follow-up time. |
|
224 |
#' * `rate_ci`: Confidence level for estimated rate per follow-up time. |
|
225 |
#' * `rate_ratio`: Ratio of event rates in each treatment arm to the reference arm. |
|
226 |
#' * `rate_ratio_ci`: Confidence level for the rate ratio. |
|
227 |
#' * `pval`: p-value. |
|
228 |
#' |
|
229 |
#' @keywords internal |
|
230 |
s_glm_count <- function(df, |
|
231 |
.var, |
|
232 |
.df_row, |
|
233 |
variables, |
|
234 |
.ref_group, |
|
235 |
.in_ref_col, |
|
236 |
distribution, |
|
237 |
conf_level, |
|
238 |
rate_mean_method, |
|
239 |
weights, |
|
240 |
scale = 1) { |
|
241 | 3x |
arm <- variables$arm |
242 | ||
243 | 3x |
y <- df[[.var]] |
244 | 2x |
smry_level <- as.character(unique(df[[arm]])) |
245 | ||
246 |
# ensure there is only 1 value |
|
247 | 2x |
checkmate::assert_scalar(smry_level) |
248 | ||
249 | 2x |
results <- h_glm_count( |
250 | 2x |
.var = .var, |
251 | 2x |
.df_row = .df_row, |
252 | 2x |
variables = variables, |
253 | 2x |
distribution = distribution, |
254 | 2x |
weights |
255 |
) |
|
256 | ||
257 | 2x |
if (rate_mean_method == "emmeans") { |
258 | 2x |
emmeans_smry <- summary(results$emmeans_fit, level = conf_level) |
259 | ! |
} else if (rate_mean_method == "ppmeans") { |
260 | ! |
emmeans_smry <- h_ppmeans(results$glm_fit, .df_row, arm, conf_level) |
261 |
} |
|
262 | ||
263 | 2x |
emmeans_smry_level <- emmeans_smry[emmeans_smry[[arm]] == smry_level, ] |
264 | ||
265 | 2x |
if (.in_ref_col) { |
266 | 1x |
list( |
267 | 1x |
n = length(y[!is.na(y)]), |
268 | 1x |
rate = formatters::with_label( |
269 | 1x |
ifelse(distribution == "negbin", emmeans_smry_level$response * scale, emmeans_smry_level$rate), |
270 | 1x |
"Adjusted Rate" |
271 |
), |
|
272 | 1x |
rate_ci = formatters::with_label( |
273 | 1x |
c(emmeans_smry_level$asymp.LCL * scale, emmeans_smry_level$asymp.UCL * scale), |
274 | 1x |
f_conf_level(conf_level) |
275 |
), |
|
276 | 1x |
rate_ratio = formatters::with_label(character(), "Adjusted Rate Ratio"), |
277 | 1x |
rate_ratio_ci = formatters::with_label(character(), f_conf_level(conf_level)), |
278 | 1x |
pval = formatters::with_label(character(), "p-value") |
279 |
) |
|
280 |
} else { |
|
281 | 1x |
emmeans_contrasts <- emmeans::contrast( |
282 | 1x |
results$emmeans_fit, |
283 | 1x |
method = "trt.vs.ctrl", |
284 | 1x |
ref = grep( |
285 | 1x |
as.character(unique(.ref_group[[arm]])), |
286 | 1x |
as.data.frame(results$emmeans_fit)[[arm]] |
287 |
) |
|
288 |
) |
|
289 | ||
290 | 1x |
contrasts_smry <- summary( |
291 | 1x |
emmeans_contrasts, |
292 | 1x |
infer = TRUE, |
293 | 1x |
adjust = "none" |
294 |
) |
|
295 | ||
296 | 1x |
smry_contrasts_level <- contrasts_smry[grepl(smry_level, contrasts_smry$contrast), ] |
297 | ||
298 | 1x |
list( |
299 | 1x |
n = length(y[!is.na(y)]), |
300 | 1x |
rate = formatters::with_label( |
301 | 1x |
ifelse(distribution == "negbin", emmeans_smry_level$response * scale, emmeans_smry_level$rate), |
302 | 1x |
"Adjusted Rate" |
303 |
), |
|
304 | 1x |
rate_ci = formatters::with_label( |
305 | 1x |
c(emmeans_smry_level$asymp.LCL * scale, emmeans_smry_level$asymp.UCL * scale), |
306 | 1x |
f_conf_level(conf_level) |
307 |
), |
|
308 | 1x |
rate_ratio = formatters::with_label(smry_contrasts_level$ratio, "Adjusted Rate Ratio"), |
309 | 1x |
rate_ratio_ci = formatters::with_label( |
310 | 1x |
c(smry_contrasts_level$asymp.LCL, smry_contrasts_level$asymp.UCL), |
311 | 1x |
f_conf_level(conf_level) |
312 |
), |
|
313 | 1x |
pval = formatters::with_label(smry_contrasts_level$p.value, "p-value") |
314 |
) |
|
315 |
} |
|
316 |
} |
|
317 | ||
318 |
#' @describeIn summarize_glm_count Formatted analysis function which is used as `afun` in `summarize_glm_count()`. |
|
319 |
#' |
|
320 |
#' @return |
|
321 |
#' * `a_glm_count()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
322 |
#' |
|
323 |
#' @keywords internal |
|
324 |
a_glm_count <- make_afun( |
|
325 |
s_glm_count, |
|
326 |
.indent_mods = c( |
|
327 |
"n" = 0L, |
|
328 |
"rate" = 0L, |
|
329 |
"rate_ci" = 1L, |
|
330 |
"rate_ratio" = 0L, |
|
331 |
"rate_ratio_ci" = 1L, |
|
332 |
"pval" = 1L |
|
333 |
), |
|
334 |
.formats = c( |
|
335 |
"n" = "xx", |
|
336 |
"rate" = "xx.xxxx", |
|
337 |
"rate_ci" = "(xx.xxxx, xx.xxxx)", |
|
338 |
"rate_ratio" = "xx.xxxx", |
|
339 |
"rate_ratio_ci" = "(xx.xxxx, xx.xxxx)", |
|
340 |
"pval" = "x.xxxx | (<0.0001)" |
|
341 |
), |
|
342 |
.null_ref_cells = FALSE |
|
343 |
) |
|
344 | ||
345 |
#' @describeIn summarize_glm_count Layout-creating function which can take statistics function arguments |
|
346 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
347 |
#' |
|
348 |
#' @return |
|
349 |
#' * `summarize_glm_count()` returns a layout object suitable for passing to further layouting functions, |
|
350 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
351 |
#' the statistics from `s_glm_count()` to the table layout. |
|
352 |
#' |
|
353 |
#' @examples |
|
354 |
#' library(dplyr) |
|
355 |
#' |
|
356 |
#' anl <- tern_ex_adtte %>% filter(PARAMCD == "TNE") |
|
357 |
#' anl$AVAL_f <- as.factor(anl$AVAL) |
|
358 |
#' |
|
359 |
#' lyt <- basic_table() %>% |
|
360 |
#' split_cols_by("ARM", ref_group = "B: Placebo") %>% |
|
361 |
#' add_colcounts() %>% |
|
362 |
#' analyze_vars( |
|
363 |
#' "AVAL_f", |
|
364 |
#' var_labels = "Number of exacerbations per patient", |
|
365 |
#' .stats = c("count_fraction"), |
|
366 |
#' .formats = c("count_fraction" = "xx (xx.xx%)"), |
|
367 |
#' .label = c("Number of exacerbations per patient") |
|
368 |
#' ) %>% |
|
369 |
#' summarize_glm_count( |
|
370 |
#' vars = "AVAL", |
|
371 |
#' variables = list(arm = "ARM", offset = "lgTMATRSK", covariates = NULL), |
|
372 |
#' conf_level = 0.95, |
|
373 |
#' distribution = "poisson", |
|
374 |
#' rate_mean_method = "emmeans", |
|
375 |
#' var_labels = "Unadjusted exacerbation rate (per year)", |
|
376 |
#' table_names = "unadj", |
|
377 |
#' .stats = c("rate"), |
|
378 |
#' .labels = c(rate = "Rate") |
|
379 |
#' ) %>% |
|
380 |
#' summarize_glm_count( |
|
381 |
#' vars = "AVAL", |
|
382 |
#' variables = list(arm = "ARM", offset = "lgTMATRSK", covariates = c("REGION1")), |
|
383 |
#' conf_level = 0.95, |
|
384 |
#' distribution = "quasipoisson", |
|
385 |
#' rate_mean_method = "ppmeans", |
|
386 |
#' var_labels = "Adjusted (QP) exacerbation rate (per year)", |
|
387 |
#' table_names = "adj", |
|
388 |
#' .stats = c("rate", "rate_ci", "rate_ratio", "rate_ratio_ci", "pval"), |
|
389 |
#' .labels = c( |
|
390 |
#' rate = "Rate", rate_ci = "Rate CI", rate_ratio = "Rate Ratio", |
|
391 |
#' rate_ratio_ci = "Rate Ratio CI", pval = "p value" |
|
392 |
#' ) |
|
393 |
#' ) |
|
394 |
#' |
|
395 |
#' build_table(lyt = lyt, df = anl) |
|
396 |
#' |
|
397 |
#' @export |
|
398 |
#' @order 2 |
|
399 |
summarize_glm_count <- function(lyt, |
|
400 |
vars, |
|
401 |
variables, |
|
402 |
distribution, |
|
403 |
conf_level, |
|
404 |
rate_mean_method, |
|
405 |
weights = stats::weights, |
|
406 |
scale = 1, |
|
407 |
var_labels, |
|
408 |
na_str = default_na_str(), |
|
409 |
nested = TRUE, |
|
410 |
..., |
|
411 |
show_labels = "visible", |
|
412 |
table_names = vars, |
|
413 |
.stats = NULL, |
|
414 |
.formats = NULL, |
|
415 |
.labels = NULL, |
|
416 |
.indent_mods = NULL) { |
|
417 | 2x |
extra_args <- list( |
418 | 2x |
variables = variables, distribution = distribution, conf_level = conf_level, |
419 | 2x |
rate_mean_method = rate_mean_method, weights = weights, scale = scale, ... |
420 |
) |
|
421 | ||
422 | 2x |
afun <- make_afun( |
423 | 2x |
a_glm_count, |
424 | 2x |
.stats = .stats, |
425 | 2x |
.formats = .formats, |
426 | 2x |
.labels = .labels, |
427 | 2x |
.indent_mods = .indent_mods |
428 |
) |
|
429 | ||
430 | 2x |
analyze( |
431 | 2x |
lyt, |
432 | 2x |
vars, |
433 | 2x |
var_labels = var_labels, |
434 | 2x |
show_labels = show_labels, |
435 | 2x |
table_names = table_names, |
436 | 2x |
afun = afun, |
437 | 2x |
na_str = na_str, |
438 | 2x |
nested = nested, |
439 | 2x |
extra_args = extra_args |
440 |
) |
|
441 |
} |
1 |
#' Pairwise `CoxPH` model |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Summarize p-value, HR and CIs from stratified or unstratified `CoxPH` model. |
|
6 |
#' |
|
7 |
#' @inheritParams argument_convention |
|
8 |
#' @inheritParams s_surv_time |
|
9 |
#' @param strat (`character` or `NULL`)\cr variable names indicating stratification factors. |
|
10 |
#' @param control (`list`)\cr parameters for comparison details, specified by using the helper function |
|
11 |
#' [control_coxph()]. Some possible parameter options are: |
|
12 |
#' * `pval_method` (`string`)\cr p-value method for testing hazard ratio = 1. Default method is `"log-rank"` which |
|
13 |
#' comes from [survival::survdiff()], can also be set to `"wald"` or `"likelihood"` (from [survival::coxph()]). |
|
14 |
#' * `ties` (`string`)\cr specifying the method for tie handling. Default is `"efron"`, |
|
15 |
#' can also be set to `"breslow"` or `"exact"`. See more in [survival::coxph()] |
|
16 |
#' * `conf_level` (`proportion`)\cr confidence level of the interval for HR. |
|
17 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("coxph_pairwise")` |
|
18 |
#' to see available statistics for this function. |
|
19 |
#' |
|
20 |
#' @name survival_coxph_pairwise |
|
21 |
#' @order 1 |
|
22 |
NULL |
|
23 | ||
24 |
#' @describeIn survival_coxph_pairwise Statistics function which analyzes HR, CIs of HR and p-value of a `coxph` model. |
|
25 |
#' |
|
26 |
#' @return |
|
27 |
#' * `s_coxph_pairwise()` returns the statistics: |
|
28 |
#' * `pvalue`: p-value to test HR = 1. |
|
29 |
#' * `hr`: Hazard ratio. |
|
30 |
#' * `hr_ci`: Confidence interval for hazard ratio. |
|
31 |
#' * `n_tot`: Total number of observations. |
|
32 |
#' * `n_tot_events`: Total number of events. |
|
33 |
#' |
|
34 |
#' @keywords internal |
|
35 |
s_coxph_pairwise <- function(df, |
|
36 |
.ref_group, |
|
37 |
.in_ref_col, |
|
38 |
.var, |
|
39 |
is_event, |
|
40 |
strat = NULL, |
|
41 |
control = control_coxph()) { |
|
42 | 73x |
checkmate::assert_string(.var) |
43 | 73x |
checkmate::assert_numeric(df[[.var]]) |
44 | 73x |
checkmate::assert_logical(df[[is_event]]) |
45 | 73x |
assert_df_with_variables(df, list(tte = .var, is_event = is_event)) |
46 | 73x |
pval_method <- control$pval_method |
47 | 73x |
ties <- control$ties |
48 | 73x |
conf_level <- control$conf_level |
49 | ||
50 | 73x |
if (.in_ref_col) { |
51 | ! |
return( |
52 | ! |
list( |
53 | ! |
pvalue = formatters::with_label("", paste0("p-value (", pval_method, ")")), |
54 | ! |
hr = formatters::with_label("", "Hazard Ratio"), |
55 | ! |
hr_ci = formatters::with_label("", f_conf_level(conf_level)), |
56 | ! |
n_tot = formatters::with_label("", "Total n"), |
57 | ! |
n_tot_events = formatters::with_label("", "Total events") |
58 |
) |
|
59 |
) |
|
60 |
} |
|
61 | 73x |
data <- rbind(.ref_group, df) |
62 | 73x |
group <- factor(rep(c("ref", "x"), c(nrow(.ref_group), nrow(df))), levels = c("ref", "x")) |
63 | ||
64 | 73x |
df_cox <- data.frame( |
65 | 73x |
tte = data[[.var]], |
66 | 73x |
is_event = data[[is_event]], |
67 | 73x |
arm = group |
68 |
) |
|
69 | 73x |
if (is.null(strat)) { |
70 | 66x |
formula_cox <- survival::Surv(tte, is_event) ~ arm |
71 |
} else { |
|
72 | 7x |
formula_cox <- stats::as.formula( |
73 | 7x |
paste0( |
74 | 7x |
"survival::Surv(tte, is_event) ~ arm + strata(", |
75 | 7x |
paste(strat, collapse = ","), |
76 |
")" |
|
77 |
) |
|
78 |
) |
|
79 | 7x |
df_cox <- cbind(df_cox, data[strat]) |
80 |
} |
|
81 | 73x |
cox_fit <- survival::coxph( |
82 | 73x |
formula = formula_cox, |
83 | 73x |
data = df_cox, |
84 | 73x |
ties = ties |
85 |
) |
|
86 | 73x |
sum_cox <- summary(cox_fit, conf.int = conf_level, extend = TRUE) |
87 | 73x |
orginal_survdiff <- survival::survdiff( |
88 | 73x |
formula_cox, |
89 | 73x |
data = df_cox |
90 |
) |
|
91 | 73x |
log_rank_pvalue <- 1 - pchisq(orginal_survdiff$chisq, length(orginal_survdiff$n) - 1) |
92 | ||
93 | 73x |
pval <- switch(pval_method, |
94 | 73x |
"wald" = sum_cox$waldtest["pvalue"], |
95 | 73x |
"log-rank" = log_rank_pvalue, # pvalue from original log-rank test survival::survdiff() |
96 | 73x |
"likelihood" = sum_cox$logtest["pvalue"] |
97 |
) |
|
98 | 73x |
list( |
99 | 73x |
pvalue = formatters::with_label(unname(pval), paste0("p-value (", pval_method, ")")), |
100 | 73x |
hr = formatters::with_label(sum_cox$conf.int[1, 1], "Hazard Ratio"), |
101 | 73x |
hr_ci = formatters::with_label(unname(sum_cox$conf.int[1, 3:4]), f_conf_level(conf_level)), |
102 | 73x |
n_tot = formatters::with_label(sum_cox$n, "Total n"), |
103 | 73x |
n_tot_events = formatters::with_label(sum_cox$nevent, "Total events") |
104 |
) |
|
105 |
} |
|
106 | ||
107 |
#' @describeIn survival_coxph_pairwise Formatted analysis function which is used as `afun` in `coxph_pairwise()`. |
|
108 |
#' |
|
109 |
#' @return |
|
110 |
#' * `a_coxph_pairwise()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
111 |
#' |
|
112 |
#' @keywords internal |
|
113 |
a_coxph_pairwise <- make_afun( |
|
114 |
s_coxph_pairwise, |
|
115 |
.indent_mods = c(pvalue = 0L, hr = 0L, hr_ci = 1L, n_tot = 0L, n_tot_events = 0L), |
|
116 |
.formats = c( |
|
117 |
pvalue = "x.xxxx | (<0.0001)", |
|
118 |
hr = "xx.xx", |
|
119 |
hr_ci = "(xx.xx, xx.xx)", |
|
120 |
n_tot = "xx.xx", |
|
121 |
n_tot_events = "xx.xx" |
|
122 |
) |
|
123 |
) |
|
124 | ||
125 |
#' @describeIn survival_coxph_pairwise Layout-creating function which can take statistics function arguments |
|
126 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
127 |
#' |
|
128 |
#' @return |
|
129 |
#' * `coxph_pairwise()` returns a layout object suitable for passing to further layouting functions, |
|
130 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
131 |
#' the statistics from `s_coxph_pairwise()` to the table layout. |
|
132 |
#' |
|
133 |
#' @examples |
|
134 |
#' library(dplyr) |
|
135 |
#' |
|
136 |
#' adtte_f <- tern_ex_adtte %>% |
|
137 |
#' filter(PARAMCD == "OS") %>% |
|
138 |
#' mutate(is_event = CNSR == 0) |
|
139 |
#' |
|
140 |
#' df <- adtte_f %>% filter(ARMCD == "ARM A") |
|
141 |
#' df_ref_group <- adtte_f %>% filter(ARMCD == "ARM B") |
|
142 |
#' |
|
143 |
#' basic_table() %>% |
|
144 |
#' split_cols_by(var = "ARMCD", ref_group = "ARM A") %>% |
|
145 |
#' add_colcounts() %>% |
|
146 |
#' coxph_pairwise( |
|
147 |
#' vars = "AVAL", |
|
148 |
#' is_event = "is_event", |
|
149 |
#' var_labels = "Unstratified Analysis" |
|
150 |
#' ) %>% |
|
151 |
#' build_table(df = adtte_f) |
|
152 |
#' |
|
153 |
#' basic_table() %>% |
|
154 |
#' split_cols_by(var = "ARMCD", ref_group = "ARM A") %>% |
|
155 |
#' add_colcounts() %>% |
|
156 |
#' coxph_pairwise( |
|
157 |
#' vars = "AVAL", |
|
158 |
#' is_event = "is_event", |
|
159 |
#' var_labels = "Stratified Analysis", |
|
160 |
#' strat = "SEX", |
|
161 |
#' control = control_coxph(pval_method = "wald") |
|
162 |
#' ) %>% |
|
163 |
#' build_table(df = adtte_f) |
|
164 |
#' |
|
165 |
#' @export |
|
166 |
#' @order 2 |
|
167 |
coxph_pairwise <- function(lyt, |
|
168 |
vars, |
|
169 |
na_str = default_na_str(), |
|
170 |
nested = TRUE, |
|
171 |
..., |
|
172 |
var_labels = "CoxPH", |
|
173 |
show_labels = "visible", |
|
174 |
table_names = vars, |
|
175 |
.stats = c("pvalue", "hr", "hr_ci"), |
|
176 |
.formats = NULL, |
|
177 |
.labels = NULL, |
|
178 |
.indent_mods = NULL) { |
|
179 | 5x |
extra_args <- list(...) |
180 | ||
181 | 5x |
afun <- make_afun( |
182 | 5x |
a_coxph_pairwise, |
183 | 5x |
.stats = .stats, |
184 | 5x |
.formats = .formats, |
185 | 5x |
.labels = .labels, |
186 | 5x |
.indent_mods = .indent_mods |
187 |
) |
|
188 | 5x |
analyze( |
189 | 5x |
lyt, |
190 | 5x |
vars, |
191 | 5x |
var_labels = var_labels, |
192 | 5x |
show_labels = show_labels, |
193 | 5x |
table_names = table_names, |
194 | 5x |
afun = afun, |
195 | 5x |
na_str = na_str, |
196 | 5x |
nested = nested, |
197 | 5x |
extra_args = extra_args |
198 |
) |
|
199 |
} |
1 |
#' Missing Data |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Substitute missing data with a string or factor level. |
|
6 |
#' |
|
7 |
#' @param x (`factor` or `character` vector)\cr values for which any missing values should be substituted. |
|
8 |
#' @param label (`character`)\cr string that missing data should be replaced with. |
|
9 |
#' |
|
10 |
#' @return `x` with any `NA` values substituted by `label`. |
|
11 |
#' |
|
12 |
#' @examples |
|
13 |
#' explicit_na(c(NA, "a", "b")) |
|
14 |
#' is.na(explicit_na(c(NA, "a", "b"))) |
|
15 |
#' |
|
16 |
#' explicit_na(factor(c(NA, "a", "b"))) |
|
17 |
#' is.na(explicit_na(factor(c(NA, "a", "b")))) |
|
18 |
#' |
|
19 |
#' explicit_na(sas_na(c("a", ""))) |
|
20 |
#' |
|
21 |
#' @export |
|
22 |
explicit_na <- function(x, label = "<Missing>") { |
|
23 | 239x |
checkmate::assert_string(label) |
24 | ||
25 | 239x |
if (is.factor(x)) { |
26 | 140x |
x <- forcats::fct_na_value_to_level(x, label) |
27 | 140x |
forcats::fct_drop(x, only = label) |
28 | 99x |
} else if (is.character(x)) { |
29 | 99x |
x[is.na(x)] <- label |
30 | 99x |
x |
31 |
} else { |
|
32 | ! |
stop("only factors and character vectors allowed") |
33 |
} |
|
34 |
} |
|
35 | ||
36 |
#' Convert Strings to `NA` |
|
37 |
#' |
|
38 |
#' @description `r lifecycle::badge("stable")` |
|
39 |
#' |
|
40 |
#' SAS imports missing data as empty strings or strings with whitespaces only. This helper function can be used to |
|
41 |
#' convert these values to `NA`s. |
|
42 |
#' |
|
43 |
#' @inheritParams explicit_na |
|
44 |
#' @param empty (`logical`)\cr if `TRUE` empty strings get replaced by `NA`. |
|
45 |
#' @param whitespaces (`logical`)\cr if `TRUE` then strings made from whitespaces only get replaced with `NA`. |
|
46 |
#' |
|
47 |
#' @return `x` with `""` and/or whitespace-only values substituted by `NA`, depending on the values of |
|
48 |
#' `empty` and `whitespaces`. |
|
49 |
#' |
|
50 |
#' @examples |
|
51 |
#' sas_na(c("1", "", " ", " ", "b")) |
|
52 |
#' sas_na(factor(c("", " ", "b"))) |
|
53 |
#' |
|
54 |
#' is.na(sas_na(c("1", "", " ", " ", "b"))) |
|
55 |
#' |
|
56 |
#' @export |
|
57 |
sas_na <- function(x, empty = TRUE, whitespaces = TRUE) { |
|
58 | 236x |
checkmate::assert_flag(empty) |
59 | 236x |
checkmate::assert_flag(whitespaces) |
60 | ||
61 | 236x |
if (is.factor(x)) { |
62 | 133x |
empty_levels <- levels(x) == "" |
63 | 11x |
if (empty && any(empty_levels)) levels(x)[empty_levels] <- NA |
64 | ||
65 | 133x |
ws_levels <- grepl("^\\s+$", levels(x)) |
66 | ! |
if (whitespaces && any(ws_levels)) levels(x)[ws_levels] <- NA |
67 | ||
68 | 133x |
x |
69 | 103x |
} else if (is.character(x)) { |
70 | 103x |
if (empty) x[x == ""] <- NA_character_ |
71 | ||
72 | 103x |
if (whitespaces) x[grepl("^\\s+$", x)] <- NA_character_ |
73 | ||
74 | 103x |
x |
75 |
} else { |
|
76 | ! |
stop("only factors and character vectors allowed") |
77 |
} |
|
78 |
} |
1 |
#' Count the Number of Patients with Particular Flags |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' The primary analysis variable `.var` denotes the unique patient identifier. |
|
6 |
#' |
|
7 |
#' @inheritParams argument_convention |
|
8 |
#' @param flag_variables (`character`)\cr a character vector specifying the names of `logical` |
|
9 |
#' variables from analysis dataset used for counting the number of unique identifiers. |
|
10 |
#' @param flag_labels (`character`)\cr vector of labels to use for flag variables. |
|
11 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("count_patients_with_flags")` |
|
12 |
#' to see available statistics for this function. |
|
13 |
#' |
|
14 |
#' @seealso [count_patients_with_event] |
|
15 |
#' |
|
16 |
#' @name count_patients_with_flags |
|
17 |
#' @order 1 |
|
18 |
NULL |
|
19 | ||
20 |
#' @describeIn count_patients_with_flags Statistics function which counts the number of patients for which |
|
21 |
#' a particular flag variable is `TRUE`. |
|
22 |
#' |
|
23 |
#' @inheritParams analyze_variables |
|
24 |
#' @param .var (`character`)\cr name of the column that contains the unique identifier. |
|
25 |
#' |
|
26 |
#' @note If `flag_labels` is not specified, variables labels will be extracted from `df`. If variables are not |
|
27 |
#' labeled, variable names will be used instead. Alternatively, a named `vector` can be supplied to |
|
28 |
#' `flag_variables` such that within each name-value pair the name corresponds to the variable name and the value is |
|
29 |
#' the label to use for this variable. |
|
30 |
#' |
|
31 |
#' @return |
|
32 |
#' * `s_count_patients_with_flags()` returns the count and the fraction of unique identifiers with each particular |
|
33 |
#' flag as a list of statistics `n`, `count`, `count_fraction`, and `n_blq`, with one element per flag. |
|
34 |
#' |
|
35 |
#' @examples |
|
36 |
#' # `s_count_patients_with_flags()` |
|
37 |
#' |
|
38 |
#' s_count_patients_with_flags( |
|
39 |
#' adae, |
|
40 |
#' "SUBJID", |
|
41 |
#' flag_variables = c("fl1", "fl2", "fl3", "fl4"), |
|
42 |
#' denom = "N_col", |
|
43 |
#' .N_col = 1000 |
|
44 |
#' ) |
|
45 |
#' |
|
46 |
#' @export |
|
47 |
s_count_patients_with_flags <- function(df, |
|
48 |
.var, |
|
49 |
flag_variables, |
|
50 |
flag_labels = NULL, |
|
51 |
.N_col, # nolint |
|
52 |
.N_row, # nolint |
|
53 |
denom = c("n", "N_row", "N_col")) { |
|
54 | 5x |
checkmate::assert_character(flag_variables) |
55 | 5x |
if (!is.null(flag_labels)) { |
56 | ! |
checkmate::assert_character(flag_labels, len = length(flag_variables), any.missing = FALSE) |
57 | ! |
flag_names <- flag_labels |
58 |
} else { |
|
59 | 5x |
if (is.null(names(flag_variables))) { |
60 | 5x |
flag_names <- formatters::var_labels(df[flag_variables], fill = TRUE) |
61 |
} else { |
|
62 | ! |
flag_names <- unname(flag_variables) |
63 | ! |
flag_variables <- names(flag_variables) |
64 |
} |
|
65 |
} |
|
66 | ||
67 | 5x |
checkmate::assert_subset(flag_variables, colnames(df)) |
68 | 5x |
temp <- sapply(flag_variables, function(x) { |
69 | 11x |
tmp <- Map(function(y) which(df[[y]]), x) |
70 | 11x |
position_satisfy_flags <- Reduce(intersect, tmp) |
71 | 11x |
id_satisfy_flags <- as.character(unique(df[position_satisfy_flags, ][[.var]])) |
72 | 11x |
s_count_values( |
73 | 11x |
as.character(unique(df[[.var]])), |
74 | 11x |
id_satisfy_flags, |
75 | 11x |
denom = denom, |
76 | 11x |
.N_col = .N_col, |
77 | 11x |
.N_row = .N_row |
78 |
) |
|
79 |
}) |
|
80 | 5x |
colnames(temp) <- flag_names |
81 | 5x |
temp <- data.frame(t(temp)) |
82 | 5x |
result <- temp %>% as.list() |
83 | 5x |
if (length(flag_variables) == 1) { |
84 | 1x |
for (i in 1:3) names(result[[i]]) <- flag_names[1] |
85 |
} |
|
86 | 5x |
result |
87 |
} |
|
88 | ||
89 |
#' @describeIn count_patients_with_flags Formatted analysis function which is used as `afun` |
|
90 |
#' in `count_patients_with_flags()`. |
|
91 |
#' |
|
92 |
#' @return |
|
93 |
#' * `a_count_patients_with_flags()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
94 |
#' |
|
95 |
#' @examples |
|
96 |
#' # We need to ungroup `count_fraction` first so that the `rtables` formatting |
|
97 |
#' # function `format_count_fraction()` can be applied correctly. |
|
98 |
#' |
|
99 |
#' # `a_count_patients_with_flags()` |
|
100 |
#' |
|
101 |
#' afun <- make_afun(a_count_patients_with_flags, |
|
102 |
#' .stats = "count_fraction", |
|
103 |
#' .ungroup_stats = "count_fraction" |
|
104 |
#' ) |
|
105 |
#' afun( |
|
106 |
#' adae, |
|
107 |
#' .N_col = 10L, |
|
108 |
#' .N_row = 10L, |
|
109 |
#' .var = "USUBJID", |
|
110 |
#' flag_variables = c("fl1", "fl2", "fl3", "fl4") |
|
111 |
#' ) |
|
112 |
#' |
|
113 |
#' @export |
|
114 |
a_count_patients_with_flags <- make_afun( |
|
115 |
s_count_patients_with_flags, |
|
116 |
.formats = c("count_fraction" = format_count_fraction_fixed_dp) |
|
117 |
) |
|
118 | ||
119 |
#' @describeIn count_patients_with_flags Layout-creating function which can take statistics function |
|
120 |
#' arguments and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
121 |
#' |
|
122 |
#' @return |
|
123 |
#' * `count_patients_with_flags()` returns a layout object suitable for passing to further layouting functions, |
|
124 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
125 |
#' the statistics from `s_count_patients_with_flags()` to the table layout. |
|
126 |
#' |
|
127 |
#' @examples |
|
128 |
#' library(dplyr) |
|
129 |
#' |
|
130 |
#' # Add labelled flag variables to analysis dataset. |
|
131 |
#' adae <- tern_ex_adae %>% |
|
132 |
#' mutate( |
|
133 |
#' fl1 = TRUE %>% with_label("Total AEs"), |
|
134 |
#' fl2 = (TRTEMFL == "Y") %>% |
|
135 |
#' with_label("Total number of patients with at least one adverse event"), |
|
136 |
#' fl3 = (TRTEMFL == "Y" & AEOUT == "FATAL") %>% |
|
137 |
#' with_label("Total number of patients with fatal AEs"), |
|
138 |
#' fl4 = (TRTEMFL == "Y" & AEOUT == "FATAL" & AEREL == "Y") %>% |
|
139 |
#' with_label("Total number of patients with related fatal AEs") |
|
140 |
#' ) |
|
141 |
#' |
|
142 |
#' # `count_patients_with_flags()` |
|
143 |
#' |
|
144 |
#' lyt2 <- basic_table() %>% |
|
145 |
#' split_cols_by("ARM") %>% |
|
146 |
#' add_colcounts() %>% |
|
147 |
#' count_patients_with_flags( |
|
148 |
#' "SUBJID", |
|
149 |
#' flag_variables = c("fl1", "fl2", "fl3", "fl4"), |
|
150 |
#' denom = "N_col" |
|
151 |
#' ) |
|
152 |
#' |
|
153 |
#' build_table(lyt2, adae, alt_counts_df = tern_ex_adsl) |
|
154 |
#' |
|
155 |
#' @export |
|
156 |
#' @order 2 |
|
157 |
count_patients_with_flags <- function(lyt, |
|
158 |
var, |
|
159 |
flag_variables, |
|
160 |
flag_labels = NULL, |
|
161 |
var_labels = var, |
|
162 |
show_labels = "hidden", |
|
163 |
riskdiff = FALSE, |
|
164 |
na_str = default_na_str(), |
|
165 |
nested = TRUE, |
|
166 |
..., |
|
167 |
table_names = paste0("tbl_flags_", var), |
|
168 |
.stats = "count_fraction", |
|
169 |
.formats = NULL, |
|
170 |
.indent_mods = NULL) { |
|
171 | 6x |
checkmate::assert_flag(riskdiff) |
172 | ||
173 | 6x |
s_args <- list(flag_variables = flag_variables, flag_labels = flag_labels, ...) |
174 | ||
175 | 6x |
afun <- make_afun( |
176 | 6x |
a_count_patients_with_flags, |
177 | 6x |
.stats = .stats, |
178 | 6x |
.formats = .formats, |
179 | 6x |
.indent_mods = .indent_mods, |
180 | 6x |
.ungroup_stats = .stats |
181 |
) |
|
182 | ||
183 | 6x |
extra_args <- if (isFALSE(riskdiff)) { |
184 | 5x |
s_args |
185 |
} else { |
|
186 | 1x |
list( |
187 | 1x |
afun = list("s_count_patients_with_flags" = afun), |
188 | 1x |
.stats = .stats, |
189 | 1x |
.indent_mods = .indent_mods, |
190 | 1x |
s_args = s_args |
191 |
) |
|
192 |
} |
|
193 | ||
194 | 6x |
lyt <- analyze( |
195 | 6x |
lyt = lyt, |
196 | 6x |
vars = var, |
197 | 6x |
var_labels = var_labels, |
198 | 6x |
show_labels = show_labels, |
199 | 6x |
afun = ifelse(isFALSE(riskdiff), afun, afun_riskdiff), |
200 | 6x |
table_names = table_names, |
201 | 6x |
na_str = na_str, |
202 | 6x |
nested = nested, |
203 | 6x |
extra_args = extra_args |
204 |
) |
|
205 | ||
206 | 6x |
lyt |
207 |
} |
1 |
#' Occurrence Counts |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Functions for analyzing frequencies and fractions of occurrences for patients with occurrence |
|
6 |
#' data. Primary analysis variables are the dictionary terms. All occurrences are counted for total |
|
7 |
#' counts. Multiple occurrences within patient at the lowest term level displayed in the table are |
|
8 |
#' counted only once. |
|
9 |
#' |
|
10 |
#' @inheritParams argument_convention |
|
11 |
#' @param drop (`flag`)\cr should non appearing occurrence levels be dropped from the resulting table. |
|
12 |
#' Note that in that case the remaining occurrence levels in the table are sorted alphabetically. |
|
13 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("count_occurrences")` |
|
14 |
#' to see available statistics for this function. |
|
15 |
#' |
|
16 |
#' @note By default, occurrences which don't appear in a given row split are dropped from the table and |
|
17 |
#' the occurrences in the table are sorted alphabetically per row split. Therefore, the corresponding layout |
|
18 |
#' needs to use `split_fun = drop_split_levels` in the `split_rows_by` calls. Use `drop = FALSE` if you would |
|
19 |
#' like to show all occurrences. |
|
20 |
#' |
|
21 |
#' @examples |
|
22 |
#' library(dplyr) |
|
23 |
#' df <- data.frame( |
|
24 |
#' USUBJID = as.character(c( |
|
25 |
#' 1, 1, 2, 4, 4, 4, |
|
26 |
#' 6, 6, 6, 7, 7, 8 |
|
27 |
#' )), |
|
28 |
#' MHDECOD = c( |
|
29 |
#' "MH1", "MH2", "MH1", "MH1", "MH1", "MH3", |
|
30 |
#' "MH2", "MH2", "MH3", "MH1", "MH2", "MH4" |
|
31 |
#' ), |
|
32 |
#' ARM = rep(c("A", "B"), each = 6), |
|
33 |
#' SEX = c("F", "F", "M", "M", "M", "M", "F", "F", "F", "M", "M", "F") |
|
34 |
#' ) |
|
35 |
#' df_adsl <- df %>% |
|
36 |
#' select(USUBJID, ARM) %>% |
|
37 |
#' unique() |
|
38 |
#' |
|
39 |
#' @name count_occurrences |
|
40 |
#' @order 1 |
|
41 |
NULL |
|
42 | ||
43 |
#' @describeIn count_occurrences Statistics function which counts number of patients that report an |
|
44 |
#' occurrence. |
|
45 |
#' |
|
46 |
#' @param denom (`string`)\cr choice of denominator for patient proportions. Can be: |
|
47 |
#' - `N_col`: total number of patients in this column across rows |
|
48 |
#' - `n`: number of patients with any occurrences |
|
49 |
#' |
|
50 |
#' @return |
|
51 |
#' * `s_count_occurrences()` returns a list with: |
|
52 |
#' * `count`: list of counts with one element per occurrence. |
|
53 |
#' * `count_fraction`: list of counts and fractions with one element per occurrence. |
|
54 |
#' * `fraction`: list of numerators and denominators with one element per occurrence. |
|
55 |
#' |
|
56 |
#' @examples |
|
57 |
#' # Count unique occurrences per subject. |
|
58 |
#' s_count_occurrences( |
|
59 |
#' df, |
|
60 |
#' .N_col = 4L, |
|
61 |
#' .df_row = df, |
|
62 |
#' .var = "MHDECOD", |
|
63 |
#' id = "USUBJID" |
|
64 |
#' ) |
|
65 |
#' |
|
66 |
#' @export |
|
67 |
s_count_occurrences <- function(df, |
|
68 |
denom = c("N_col", "n"), |
|
69 |
.N_col, # nolint |
|
70 |
.df_row, |
|
71 |
drop = TRUE, |
|
72 |
.var = "MHDECOD", |
|
73 |
id = "USUBJID") { |
|
74 | 57x |
checkmate::assert_flag(drop) |
75 | 57x |
assert_df_with_variables(df, list(range = .var, id = id)) |
76 | 57x |
checkmate::assert_count(.N_col) |
77 | 57x |
checkmate::assert_multi_class(df[[.var]], classes = c("factor", "character")) |
78 | 57x |
checkmate::assert_multi_class(df[[id]], classes = c("factor", "character")) |
79 | 57x |
denom <- match.arg(denom) |
80 | ||
81 | 57x |
occurrences <- if (drop) { |
82 |
# Note that we don't try to preserve original level order here since a) that would required |
|
83 |
# more time to look up in large original levels and b) that would fail for character input variable. |
|
84 | 46x |
occurrence_levels <- sort(unique(.df_row[[.var]])) |
85 | 46x |
if (length(occurrence_levels) == 0) { |
86 | 1x |
stop( |
87 | 1x |
"no empty `.df_row` input allowed when `drop = TRUE`,", |
88 | 1x |
" please use `split_fun = drop_split_levels` in the `rtables` `split_rows_by` calls" |
89 |
) |
|
90 |
} |
|
91 | 45x |
factor(df[[.var]], levels = occurrence_levels) |
92 |
} else { |
|
93 | 11x |
df[[.var]] |
94 |
} |
|
95 | 56x |
ids <- factor(df[[id]]) |
96 | 56x |
dn <- switch(denom, |
97 | 56x |
n = nlevels(ids), |
98 | 56x |
N_col = .N_col |
99 |
) |
|
100 | 56x |
has_occurrence_per_id <- table(occurrences, ids) > 0 |
101 | 56x |
n_ids_per_occurrence <- as.list(rowSums(has_occurrence_per_id)) |
102 | 56x |
list( |
103 | 56x |
count = n_ids_per_occurrence, |
104 | 56x |
count_fraction = lapply( |
105 | 56x |
n_ids_per_occurrence, |
106 | 56x |
function(i, denom) { |
107 | 202x |
if (i == 0 && denom == 0) { |
108 | ! |
c(0, 0) |
109 |
} else { |
|
110 | 202x |
c(i, i / denom) |
111 |
} |
|
112 |
}, |
|
113 | 56x |
denom = dn |
114 |
), |
|
115 | 56x |
fraction = lapply( |
116 | 56x |
n_ids_per_occurrence, |
117 | 56x |
function(i, denom) c("num" = i, "denom" = denom), |
118 | 56x |
denom = dn |
119 |
) |
|
120 |
) |
|
121 |
} |
|
122 | ||
123 |
#' @describeIn count_occurrences Formatted analysis function which is used as `afun` |
|
124 |
#' in `count_occurrences()`. |
|
125 |
#' |
|
126 |
#' @return |
|
127 |
#' * `a_count_occurrences()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
128 |
#' |
|
129 |
#' @examples |
|
130 |
#' a_count_occurrences( |
|
131 |
#' df, |
|
132 |
#' .N_col = 4L, |
|
133 |
#' .df_row = df, |
|
134 |
#' .var = "MHDECOD", |
|
135 |
#' id = "USUBJID" |
|
136 |
#' ) |
|
137 |
#' |
|
138 |
#' @export |
|
139 |
a_count_occurrences <- function(df, |
|
140 |
labelstr = "", |
|
141 |
id = "USUBJID", |
|
142 |
denom = c("N_col", "n"), |
|
143 |
drop = TRUE, |
|
144 |
.N_col, # nolint |
|
145 |
.var = NULL, |
|
146 |
.df_row = NULL, |
|
147 |
.stats = NULL, |
|
148 |
.formats = NULL, |
|
149 |
.labels = NULL, |
|
150 |
.indent_mods = NULL, |
|
151 |
na_str = default_na_str()) { |
|
152 | 46x |
denom <- match.arg(denom) |
153 | 46x |
x_stats <- s_count_occurrences( |
154 | 46x |
df = df, denom = denom, .N_col = .N_col, .df_row = .df_row, drop = drop, .var = .var, id = id |
155 |
) |
|
156 | 46x |
if (is.null(unlist(x_stats))) { |
157 | 3x |
return(NULL) |
158 |
} |
|
159 | 43x |
x_lvls <- names(x_stats[[1]]) |
160 | ||
161 |
# Fill in with formatting defaults if needed |
|
162 | 43x |
.stats <- get_stats("count_occurrences", stats_in = .stats) |
163 | 43x |
.formats <- get_formats_from_stats(.stats, .formats) |
164 | 43x |
.labels <- get_labels_from_stats(.stats, .labels, row_nms = x_lvls) |
165 | 43x |
.indent_mods <- get_indents_from_stats(.stats, .indent_mods, row_nms = x_lvls) |
166 | ||
167 | 42x |
if ("count_fraction_fixed_dp" %in% .stats) x_stats[["count_fraction_fixed_dp"]] <- x_stats[["count_fraction"]] |
168 | 43x |
x_stats <- x_stats[.stats] |
169 | ||
170 |
# Ungroup statistics with values for each level of x |
|
171 | 43x |
x_ungrp <- ungroup_stats(x_stats, .formats, list(), list()) |
172 | 43x |
x_stats <- x_ungrp[["x"]] |
173 | 43x |
.formats <- x_ungrp[[".formats"]] |
174 | ||
175 |
# Auto format handling |
|
176 | 43x |
.formats <- apply_auto_formatting(.formats, x_stats, .df_row, .var) |
177 | ||
178 | 43x |
in_rows( |
179 | 43x |
.list = x_stats, |
180 | 43x |
.formats = .formats, |
181 | 43x |
.names = .labels, |
182 | 43x |
.labels = .labels, |
183 | 43x |
.indent_mods = .indent_mods, |
184 | 43x |
.format_na_strs = na_str |
185 |
) |
|
186 |
} |
|
187 | ||
188 |
#' @describeIn count_occurrences Layout-creating function which can take statistics function arguments |
|
189 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
190 |
#' |
|
191 |
#' @return |
|
192 |
#' * `count_occurrences()` returns a layout object suitable for passing to further layouting functions, |
|
193 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
194 |
#' the statistics from `s_count_occurrences()` to the table layout. |
|
195 |
#' |
|
196 |
#' @examples |
|
197 |
#' # Create table layout |
|
198 |
#' lyt <- basic_table() %>% |
|
199 |
#' split_cols_by("ARM") %>% |
|
200 |
#' add_colcounts() %>% |
|
201 |
#' count_occurrences(vars = "MHDECOD", .stats = c("count_fraction")) |
|
202 |
#' |
|
203 |
#' # Apply table layout to data and produce `rtable` object |
|
204 |
#' tbl <- lyt %>% |
|
205 |
#' build_table(df, alt_counts_df = df_adsl) %>% |
|
206 |
#' prune_table() |
|
207 |
#' |
|
208 |
#' tbl |
|
209 |
#' |
|
210 |
#' @export |
|
211 |
#' @order 2 |
|
212 |
count_occurrences <- function(lyt, |
|
213 |
vars, |
|
214 |
id = "USUBJID", |
|
215 |
drop = TRUE, |
|
216 |
var_labels = vars, |
|
217 |
show_labels = "hidden", |
|
218 |
riskdiff = FALSE, |
|
219 |
na_str = default_na_str(), |
|
220 |
nested = TRUE, |
|
221 |
..., |
|
222 |
table_names = vars, |
|
223 |
.stats = "count_fraction_fixed_dp", |
|
224 |
.formats = NULL, |
|
225 |
.labels = NULL, |
|
226 |
.indent_mods = NULL) { |
|
227 | 7x |
checkmate::assert_flag(riskdiff) |
228 | ||
229 | 7x |
extra_args <- list( |
230 | 7x |
.stats = .stats, .formats = .formats, .labels = .labels, .indent_mods = .indent_mods, na_str = na_str |
231 |
) |
|
232 | 7x |
s_args <- list(id = id, drop = drop, ...) |
233 | ||
234 | 7x |
if (isFALSE(riskdiff)) { |
235 | 6x |
extra_args <- c(extra_args, s_args) |
236 |
} else { |
|
237 | 1x |
extra_args <- c( |
238 | 1x |
extra_args, |
239 | 1x |
list( |
240 | 1x |
afun = list("s_count_occurrences" = a_count_occurrences), |
241 | 1x |
s_args = s_args |
242 |
) |
|
243 |
) |
|
244 |
} |
|
245 | ||
246 | 7x |
analyze( |
247 | 7x |
lyt = lyt, |
248 | 7x |
vars = vars, |
249 | 7x |
afun = ifelse(isFALSE(riskdiff), a_count_occurrences, afun_riskdiff), |
250 | 7x |
var_labels = var_labels, |
251 | 7x |
show_labels = show_labels, |
252 | 7x |
table_names = table_names, |
253 | 7x |
na_str = na_str, |
254 | 7x |
nested = nested, |
255 | 7x |
extra_args = extra_args |
256 |
) |
|
257 |
} |
|
258 | ||
259 |
#' @describeIn count_occurrences Layout-creating function which can take content function arguments |
|
260 |
#' and additional format arguments. This function is a wrapper for [rtables::summarize_row_groups()]. |
|
261 |
#' |
|
262 |
#' @return |
|
263 |
#' * `summarize_occurrences()` returns a layout object suitable for passing to further layouting functions, |
|
264 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted content rows |
|
265 |
#' containing the statistics from `s_count_occurrences()` to the table layout. |
|
266 |
#' |
|
267 |
#' @examples |
|
268 |
#' # Layout creating function with custom format. |
|
269 |
#' basic_table() %>% |
|
270 |
#' add_colcounts() %>% |
|
271 |
#' split_rows_by("SEX", child_labels = "visible") %>% |
|
272 |
#' summarize_occurrences( |
|
273 |
#' var = "MHDECOD", |
|
274 |
#' .formats = c("count_fraction" = "xx.xx (xx.xx%)") |
|
275 |
#' ) %>% |
|
276 |
#' build_table(df, alt_counts_df = df_adsl) |
|
277 |
#' |
|
278 |
#' @export |
|
279 |
#' @order 3 |
|
280 |
summarize_occurrences <- function(lyt, |
|
281 |
var, |
|
282 |
id = "USUBJID", |
|
283 |
drop = TRUE, |
|
284 |
riskdiff = FALSE, |
|
285 |
na_str = default_na_str(), |
|
286 |
..., |
|
287 |
.stats = "count_fraction_fixed_dp", |
|
288 |
.formats = NULL, |
|
289 |
.indent_mods = NULL, |
|
290 |
.labels = NULL) { |
|
291 | 2x |
checkmate::assert_flag(riskdiff) |
292 | ||
293 | 2x |
extra_args <- list( |
294 | 2x |
.stats = .stats, .formats = .formats, .labels = .labels, .indent_mods = .indent_mods, na_str = na_str |
295 |
) |
|
296 | 2x |
s_args <- list(id = id, drop = drop, ...) |
297 | ||
298 | 2x |
if (isFALSE(riskdiff)) { |
299 | 1x |
extra_args <- c(extra_args, s_args) |
300 |
} else { |
|
301 | 1x |
extra_args <- c( |
302 | 1x |
extra_args, |
303 | 1x |
list( |
304 | 1x |
afun = list("s_count_occurrences" = a_count_occurrences), |
305 | 1x |
s_args = s_args |
306 |
) |
|
307 |
) |
|
308 |
} |
|
309 | ||
310 | 2x |
summarize_row_groups( |
311 | 2x |
lyt = lyt, |
312 | 2x |
var = var, |
313 | 2x |
cfun = ifelse(isFALSE(riskdiff), a_count_occurrences, afun_riskdiff), |
314 | 2x |
na_str = na_str, |
315 | 2x |
extra_args = extra_args |
316 |
) |
|
317 |
} |
1 |
#' Odds Ratio Estimation |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Compares bivariate responses between two groups in terms of odds ratios |
|
6 |
#' along with a confidence interval. |
|
7 |
#' |
|
8 |
#' @inheritParams split_cols_by_groups |
|
9 |
#' @inheritParams argument_convention |
|
10 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("estimate_odds_ratio")` |
|
11 |
#' to see available statistics for this function. |
|
12 |
#' |
|
13 |
#' @details This function uses either logistic regression for unstratified |
|
14 |
#' analyses, or conditional logistic regression for stratified analyses. |
|
15 |
#' The Wald confidence interval with the specified confidence level is |
|
16 |
#' calculated. |
|
17 |
#' |
|
18 |
#' @note For stratified analyses, there is currently no implementation for conditional |
|
19 |
#' likelihood confidence intervals, therefore the likelihood confidence interval is not |
|
20 |
#' yet available as an option. Besides, when `rsp` contains only responders or non-responders, |
|
21 |
#' then the result values will be `NA`, because no odds ratio estimation is possible. |
|
22 |
#' |
|
23 |
#' @seealso Relevant helper function [h_odds_ratio()]. |
|
24 |
#' |
|
25 |
#' @name odds_ratio |
|
26 |
#' @order 1 |
|
27 |
NULL |
|
28 | ||
29 |
#' @describeIn odds_ratio Statistics function which estimates the odds ratio |
|
30 |
#' between a treatment and a control. A `variables` list with `arm` and `strata` |
|
31 |
#' variable names must be passed if a stratified analysis is required. |
|
32 |
#' |
|
33 |
#' @return |
|
34 |
#' * `s_odds_ratio()` returns a named list with the statistics `or_ci` |
|
35 |
#' (containing `est`, `lcl`, and `ucl`) and `n_tot`. |
|
36 |
#' |
|
37 |
#' @examples |
|
38 |
#' # Unstratified analysis. |
|
39 |
#' s_odds_ratio( |
|
40 |
#' df = subset(dta, grp == "A"), |
|
41 |
#' .var = "rsp", |
|
42 |
#' .ref_group = subset(dta, grp == "B"), |
|
43 |
#' .in_ref_col = FALSE, |
|
44 |
#' .df_row = dta |
|
45 |
#' ) |
|
46 |
#' |
|
47 |
#' # Stratified analysis. |
|
48 |
#' s_odds_ratio( |
|
49 |
#' df = subset(dta, grp == "A"), |
|
50 |
#' .var = "rsp", |
|
51 |
#' .ref_group = subset(dta, grp == "B"), |
|
52 |
#' .in_ref_col = FALSE, |
|
53 |
#' .df_row = dta, |
|
54 |
#' variables = list(arm = "grp", strata = "strata") |
|
55 |
#' ) |
|
56 |
#' |
|
57 |
#' @export |
|
58 |
s_odds_ratio <- function(df, |
|
59 |
.var, |
|
60 |
.ref_group, |
|
61 |
.in_ref_col, |
|
62 |
.df_row, |
|
63 |
variables = list(arm = NULL, strata = NULL), |
|
64 |
conf_level = 0.95, |
|
65 |
groups_list = NULL) { |
|
66 | 70x |
y <- list(or_ci = "", n_tot = "") |
67 | ||
68 | 70x |
if (!.in_ref_col) { |
69 | 70x |
assert_proportion_value(conf_level) |
70 | 70x |
assert_df_with_variables(df, list(rsp = .var)) |
71 | 70x |
assert_df_with_variables(.ref_group, list(rsp = .var)) |
72 | ||
73 | 70x |
if (is.null(variables$strata)) { |
74 | 57x |
data <- data.frame( |
75 | 57x |
rsp = c(.ref_group[[.var]], df[[.var]]), |
76 | 57x |
grp = factor( |
77 | 57x |
rep(c("ref", "Not-ref"), c(nrow(.ref_group), nrow(df))), |
78 | 57x |
levels = c("ref", "Not-ref") |
79 |
) |
|
80 |
) |
|
81 | 57x |
y <- or_glm(data, conf_level = conf_level) |
82 |
} else { |
|
83 | 13x |
assert_df_with_variables(.df_row, c(list(rsp = .var), variables)) |
84 | ||
85 |
# The group variable prepared for clogit must be synchronised with combination groups definition. |
|
86 | 13x |
if (is.null(groups_list)) { |
87 | 12x |
ref_grp <- as.character(unique(.ref_group[[variables$arm]])) |
88 | 12x |
trt_grp <- as.character(unique(df[[variables$arm]])) |
89 | 12x |
grp <- stats::relevel(factor(.df_row[[variables$arm]]), ref = ref_grp) |
90 |
} else { |
|
91 |
# If more than one level in reference col. |
|
92 | 1x |
reference <- as.character(unique(.ref_group[[variables$arm]])) |
93 | 1x |
grp_ref_flag <- vapply( |
94 | 1x |
X = groups_list, |
95 | 1x |
FUN.VALUE = TRUE, |
96 | 1x |
FUN = function(x) all(reference %in% x) |
97 |
) |
|
98 | 1x |
ref_grp <- names(groups_list)[grp_ref_flag] |
99 | ||
100 |
# If more than one level in treatment col. |
|
101 | 1x |
treatment <- as.character(unique(df[[variables$arm]])) |
102 | 1x |
grp_trt_flag <- vapply( |
103 | 1x |
X = groups_list, |
104 | 1x |
FUN.VALUE = TRUE, |
105 | 1x |
FUN = function(x) all(treatment %in% x) |
106 |
) |
|
107 | 1x |
trt_grp <- names(groups_list)[grp_trt_flag] |
108 | ||
109 | 1x |
grp <- combine_levels(.df_row[[variables$arm]], levels = reference, new_level = ref_grp) |
110 | 1x |
grp <- combine_levels(grp, levels = treatment, new_level = trt_grp) |
111 |
} |
|
112 | ||
113 |
# The reference level in `grp` must be the same as in the `rtables` column split. |
|
114 | 13x |
data <- data.frame( |
115 | 13x |
rsp = .df_row[[.var]], |
116 | 13x |
grp = grp, |
117 | 13x |
strata = interaction(.df_row[variables$strata]) |
118 |
) |
|
119 | 13x |
y_all <- or_clogit(data, conf_level = conf_level) |
120 | 13x |
checkmate::assert_string(trt_grp) |
121 | 13x |
checkmate::assert_subset(trt_grp, names(y_all$or_ci)) |
122 | 12x |
y$or_ci <- y_all$or_ci[[trt_grp]] |
123 | 12x |
y$n_tot <- y_all$n_tot |
124 |
} |
|
125 |
} |
|
126 | ||
127 | 69x |
y$or_ci <- formatters::with_label( |
128 | 69x |
x = y$or_ci, |
129 | 69x |
label = paste0("Odds Ratio (", 100 * conf_level, "% CI)") |
130 |
) |
|
131 | ||
132 | 69x |
y$n_tot <- formatters::with_label( |
133 | 69x |
x = y$n_tot, |
134 | 69x |
label = "Total n" |
135 |
) |
|
136 | ||
137 | 69x |
y |
138 |
} |
|
139 | ||
140 |
#' @describeIn odds_ratio Formatted analysis function which is used as `afun` in `estimate_odds_ratio()`. |
|
141 |
#' |
|
142 |
#' @return |
|
143 |
#' * `a_odds_ratio()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
144 |
#' |
|
145 |
#' @examples |
|
146 |
#' a_odds_ratio( |
|
147 |
#' df = subset(dta, grp == "A"), |
|
148 |
#' .var = "rsp", |
|
149 |
#' .ref_group = subset(dta, grp == "B"), |
|
150 |
#' .in_ref_col = FALSE, |
|
151 |
#' .df_row = dta |
|
152 |
#' ) |
|
153 |
#' |
|
154 |
#' @export |
|
155 |
a_odds_ratio <- make_afun( |
|
156 |
s_odds_ratio, |
|
157 |
.formats = c(or_ci = "xx.xx (xx.xx - xx.xx)"), |
|
158 |
.indent_mods = c(or_ci = 1L) |
|
159 |
) |
|
160 | ||
161 |
#' @describeIn odds_ratio Layout-creating function which can take statistics function arguments |
|
162 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
163 |
#' |
|
164 |
#' @param ... arguments passed to `s_odds_ratio()`. |
|
165 |
#' |
|
166 |
#' @return |
|
167 |
#' * `estimate_odds_ratio()` returns a layout object suitable for passing to further layouting functions, |
|
168 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
169 |
#' the statistics from `s_odds_ratio()` to the table layout. |
|
170 |
#' |
|
171 |
#' @examples |
|
172 |
#' set.seed(12) |
|
173 |
#' dta <- data.frame( |
|
174 |
#' rsp = sample(c(TRUE, FALSE), 100, TRUE), |
|
175 |
#' grp = factor(rep(c("A", "B"), each = 50), levels = c("A", "B")), |
|
176 |
#' strata = factor(sample(c("C", "D"), 100, TRUE)) |
|
177 |
#' ) |
|
178 |
#' |
|
179 |
#' l <- basic_table() %>% |
|
180 |
#' split_cols_by(var = "grp", ref_group = "B") %>% |
|
181 |
#' estimate_odds_ratio(vars = "rsp") |
|
182 |
#' |
|
183 |
#' build_table(l, df = dta) |
|
184 |
#' |
|
185 |
#' @export |
|
186 |
#' @order 2 |
|
187 |
estimate_odds_ratio <- function(lyt, |
|
188 |
vars, |
|
189 |
variables = list(arm = NULL, strata = NULL), |
|
190 |
conf_level = 0.95, |
|
191 |
groups_list = NULL, |
|
192 |
na_str = default_na_str(), |
|
193 |
nested = TRUE, |
|
194 |
..., |
|
195 |
show_labels = "hidden", |
|
196 |
table_names = vars, |
|
197 |
.stats = "or_ci", |
|
198 |
.formats = NULL, |
|
199 |
.labels = NULL, |
|
200 |
.indent_mods = NULL) { |
|
201 | 4x |
extra_args <- list(variables = variables, conf_level = conf_level, groups_list = groups_list, ...) |
202 | ||
203 | 4x |
afun <- make_afun( |
204 | 4x |
a_odds_ratio, |
205 | 4x |
.stats = .stats, |
206 | 4x |
.formats = .formats, |
207 | 4x |
.labels = .labels, |
208 | 4x |
.indent_mods = .indent_mods |
209 |
) |
|
210 | ||
211 | 4x |
analyze( |
212 | 4x |
lyt, |
213 | 4x |
vars, |
214 | 4x |
afun = afun, |
215 | 4x |
na_str = na_str, |
216 | 4x |
nested = nested, |
217 | 4x |
extra_args = extra_args, |
218 | 4x |
show_labels = show_labels, |
219 | 4x |
table_names = table_names |
220 |
) |
|
221 |
} |
|
222 | ||
223 |
#' Helper Functions for Odds Ratio Estimation |
|
224 |
#' |
|
225 |
#' @description `r lifecycle::badge("stable")` |
|
226 |
#' |
|
227 |
#' Functions to calculate odds ratios in [estimate_odds_ratio()]. |
|
228 |
#' |
|
229 |
#' @inheritParams argument_convention |
|
230 |
#' @param data (`data.frame`)\cr data frame containing at least the variables `rsp` and `grp`, and optionally |
|
231 |
#' `strata` for [or_clogit()]. |
|
232 |
#' |
|
233 |
#' @return A named `list` of elements `or_ci` and `n_tot`. |
|
234 |
#' |
|
235 |
#' @seealso [odds_ratio] |
|
236 |
#' |
|
237 |
#' @name h_odds_ratio |
|
238 |
NULL |
|
239 | ||
240 |
#' @describeIn h_odds_ratio Estimates the odds ratio based on [stats::glm()]. Note that there must be |
|
241 |
#' exactly 2 groups in `data` as specified by the `grp` variable. |
|
242 |
#' |
|
243 |
#' @examples |
|
244 |
#' # Data with 2 groups. |
|
245 |
#' data <- data.frame( |
|
246 |
#' rsp = as.logical(c(1, 1, 0, 1, 0, 0, 1, 1)), |
|
247 |
#' grp = letters[c(1, 1, 1, 2, 2, 2, 1, 2)], |
|
248 |
#' strata = letters[c(1, 2, 1, 2, 2, 2, 1, 2)], |
|
249 |
#' stringsAsFactors = TRUE |
|
250 |
#' ) |
|
251 |
#' |
|
252 |
#' # Odds ratio based on glm. |
|
253 |
#' or_glm(data, conf_level = 0.95) |
|
254 |
#' |
|
255 |
#' @export |
|
256 |
or_glm <- function(data, conf_level) { |
|
257 | 62x |
checkmate::assert_logical(data$rsp) |
258 | 62x |
assert_proportion_value(conf_level) |
259 | 62x |
assert_df_with_variables(data, list(rsp = "rsp", grp = "grp")) |
260 | 62x |
checkmate::assert_multi_class(data$grp, classes = c("factor", "character")) |
261 | ||
262 | 62x |
data$grp <- as_factor_keep_attributes(data$grp) |
263 | 62x |
assert_df_with_factors(data, list(val = "grp"), min.levels = 2, max.levels = 2) |
264 | 62x |
formula <- stats::as.formula("rsp ~ grp") |
265 | 62x |
model_fit <- stats::glm( |
266 | 62x |
formula = formula, data = data, |
267 | 62x |
family = stats::binomial(link = "logit") |
268 |
) |
|
269 | ||
270 |
# Note that here we need to discard the intercept. |
|
271 | 62x |
or <- exp(stats::coef(model_fit)[-1]) |
272 | 62x |
or_ci <- exp( |
273 | 62x |
stats::confint.default(model_fit, level = conf_level)[-1, , drop = FALSE] |
274 |
) |
|
275 | ||
276 | 62x |
values <- stats::setNames(c(or, or_ci), c("est", "lcl", "ucl")) |
277 | 62x |
n_tot <- stats::setNames(nrow(model_fit$model), "n_tot") |
278 | ||
279 | 62x |
list(or_ci = values, n_tot = n_tot) |
280 |
} |
|
281 | ||
282 |
#' @describeIn h_odds_ratio estimates the odds ratio based on [survival::clogit()]. This is done for |
|
283 |
#' the whole data set including all groups, since the results are not the same as when doing |
|
284 |
#' pairwise comparisons between the groups. |
|
285 |
#' |
|
286 |
#' @examples |
|
287 |
#' # Data with 3 groups. |
|
288 |
#' data <- data.frame( |
|
289 |
#' rsp = as.logical(c(1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0)), |
|
290 |
#' grp = letters[c(1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3)], |
|
291 |
#' strata = LETTERS[c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)], |
|
292 |
#' stringsAsFactors = TRUE |
|
293 |
#' ) |
|
294 |
#' |
|
295 |
#' # Odds ratio based on stratified estimation by conditional logistic regression. |
|
296 |
#' or_clogit(data, conf_level = 0.95) |
|
297 |
#' |
|
298 |
#' @export |
|
299 |
or_clogit <- function(data, conf_level) { |
|
300 | 16x |
checkmate::assert_logical(data$rsp) |
301 | 16x |
assert_proportion_value(conf_level) |
302 | 16x |
assert_df_with_variables(data, list(rsp = "rsp", grp = "grp", strata = "strata")) |
303 | 16x |
checkmate::assert_multi_class(data$grp, classes = c("factor", "character")) |
304 | 16x |
checkmate::assert_multi_class(data$strata, classes = c("factor", "character")) |
305 | ||
306 | 16x |
data$grp <- as_factor_keep_attributes(data$grp) |
307 | 16x |
data$strata <- as_factor_keep_attributes(data$strata) |
308 | ||
309 |
# Deviation from convention: `survival::strata` must be simply `strata`. |
|
310 | 16x |
formula <- stats::as.formula("rsp ~ grp + strata(strata)") |
311 | 16x |
model_fit <- clogit_with_tryCatch(formula = formula, data = data) |
312 | ||
313 |
# Create a list with one set of OR estimates and CI per coefficient, i.e. |
|
314 |
# comparison of one group vs. the reference group. |
|
315 | 16x |
coef_est <- stats::coef(model_fit) |
316 | 16x |
ci_est <- stats::confint(model_fit, level = conf_level) |
317 | 16x |
or_ci <- list() |
318 | 16x |
for (coef_name in names(coef_est)) { |
319 | 18x |
grp_name <- gsub("^grp", "", x = coef_name) |
320 | 18x |
or_ci[[grp_name]] <- stats::setNames( |
321 | 18x |
object = exp(c(coef_est[coef_name], ci_est[coef_name, , drop = TRUE])), |
322 | 18x |
nm = c("est", "lcl", "ucl") |
323 |
) |
|
324 |
} |
|
325 | 16x |
list(or_ci = or_ci, n_tot = c(n_tot = model_fit$n)) |
326 |
} |
1 |
#' Incidence Rate |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Estimate the event rate adjusted for person-years at risk, otherwise known |
|
6 |
#' as incidence rate. Primary analysis variable is the person-years at risk. |
|
7 |
#' |
|
8 |
#' @inheritParams argument_convention |
|
9 |
#' @param control (`list`)\cr parameters for estimation details, specified by using |
|
10 |
#' the helper function [control_incidence_rate()]. Possible parameter options are: |
|
11 |
#' * `conf_level` (`proportion`)\cr confidence level for the estimated incidence rate. |
|
12 |
#' * `conf_type` (`string`)\cr `normal` (default), `normal_log`, `exact`, or `byar` |
|
13 |
#' for confidence interval type. |
|
14 |
#' * `input_time_unit` (`string`)\cr `day`, `week`, `month`, or `year` (default) |
|
15 |
#' indicating time unit for data input. |
|
16 |
#' * `num_pt_year` (`numeric`)\cr time unit for desired output (in person-years). |
|
17 |
#' @param n_events (`integer`)\cr number of events observed. |
|
18 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("estimate_incidence_rate")` |
|
19 |
#' to see available statistics for this function. |
|
20 |
#' |
|
21 |
#' @seealso [control_incidence_rate()] and helper functions [h_incidence_rate]. |
|
22 |
#' |
|
23 |
#' @name incidence_rate |
|
24 |
#' @order 1 |
|
25 |
NULL |
|
26 | ||
27 |
#' @describeIn incidence_rate Statistics function which estimates the incidence rate and the |
|
28 |
#' associated confidence interval. |
|
29 |
#' |
|
30 |
#' @return |
|
31 |
#' * `s_incidence_rate()` returns the following statistics: |
|
32 |
#' - `person_years`: Total person-years at risk. |
|
33 |
#' - `n_events`: Total number of events observed. |
|
34 |
#' - `rate`: Estimated incidence rate. |
|
35 |
#' - `rate_ci`: Confidence interval for the incidence rate. |
|
36 |
#' |
|
37 |
#' @keywords internal |
|
38 |
s_incidence_rate <- function(df, |
|
39 |
.var, |
|
40 |
n_events, |
|
41 |
is_event, |
|
42 |
control = control_incidence_rate()) { |
|
43 | 1x |
if (!missing(is_event)) { |
44 | ! |
warning("argument is_event will be deprecated. Please use n_events.") |
45 | ||
46 | ! |
if (missing(n_events)) { |
47 | ! |
assert_df_with_variables(df, list(tte = .var, is_event = is_event)) |
48 | ! |
checkmate::assert_string(.var) |
49 | ! |
checkmate::assert_logical(df[[is_event]], any.missing = FALSE) |
50 | ! |
checkmate::assert_numeric(df[[.var]], any.missing = FALSE) |
51 | ! |
n_events <- is_event |
52 |
} |
|
53 |
} else { |
|
54 | 1x |
assert_df_with_variables(df, list(tte = .var, n_events = n_events)) |
55 | 1x |
checkmate::assert_string(.var) |
56 | 1x |
checkmate::assert_numeric(df[[.var]], any.missing = FALSE) |
57 | 1x |
checkmate::assert_integer(df[[n_events]], any.missing = FALSE) |
58 |
} |
|
59 | ||
60 | 1x |
input_time_unit <- control$input_time_unit |
61 | 1x |
num_pt_year <- control$num_pt_year |
62 | 1x |
conf_level <- control$conf_level |
63 | 1x |
person_years <- sum(df[[.var]], na.rm = TRUE) * ( |
64 | 1x |
1 * (input_time_unit == "year") + |
65 | 1x |
1 / 12 * (input_time_unit == "month") + |
66 | 1x |
1 / 52.14 * (input_time_unit == "week") + |
67 | 1x |
1 / 365.24 * (input_time_unit == "day") |
68 |
) |
|
69 | 1x |
n_events <- sum(df[[n_events]], na.rm = TRUE) |
70 | ||
71 | 1x |
result <- h_incidence_rate( |
72 | 1x |
person_years, |
73 | 1x |
n_events, |
74 | 1x |
control |
75 |
) |
|
76 | 1x |
list( |
77 | 1x |
person_years = formatters::with_label(person_years, "Total patient-years at risk"), |
78 | 1x |
n_events = formatters::with_label(n_events, "Number of adverse events observed"), |
79 | 1x |
rate = formatters::with_label(result$rate, paste("AE rate per", num_pt_year, "patient-years")), |
80 | 1x |
rate_ci = formatters::with_label(result$rate_ci, f_conf_level(conf_level)) |
81 |
) |
|
82 |
} |
|
83 | ||
84 |
#' @describeIn incidence_rate Formatted analysis function which is used as `afun` |
|
85 |
#' in `estimate_incidence_rate()`. |
|
86 |
#' |
|
87 |
#' @return |
|
88 |
#' * `a_incidence_rate()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
89 |
#' |
|
90 |
#' @keywords internal |
|
91 |
a_incidence_rate <- make_afun( |
|
92 |
s_incidence_rate, |
|
93 |
.formats = c( |
|
94 |
"person_years" = "xx.x", |
|
95 |
"n_events" = "xx", |
|
96 |
"rate" = "xx.xx", |
|
97 |
"rate_ci" = "(xx.xx, xx.xx)" |
|
98 |
) |
|
99 |
) |
|
100 | ||
101 |
#' @describeIn incidence_rate Layout-creating function which can take statistics function arguments |
|
102 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
103 |
#' |
|
104 |
#' @return |
|
105 |
#' * `estimate_incidence_rate()` returns a layout object suitable for passing to further layouting functions, |
|
106 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
107 |
#' the statistics from `s_incidence_rate()` to the table layout. |
|
108 |
#' |
|
109 |
#' @examples |
|
110 |
#' library(dplyr) |
|
111 |
#' |
|
112 |
#' df <- data.frame( |
|
113 |
#' USUBJID = as.character(seq(6)), |
|
114 |
#' CNSR = c(0, 1, 1, 0, 0, 0), |
|
115 |
#' AVAL = c(10.1, 20.4, 15.3, 20.8, 18.7, 23.4), |
|
116 |
#' ARM = factor(c("A", "A", "A", "B", "B", "B")) |
|
117 |
#' ) %>% |
|
118 |
#' mutate(is_event = CNSR == 0) %>% |
|
119 |
#' mutate(n_events = as.integer(is_event)) |
|
120 |
#' |
|
121 |
#' basic_table() %>% |
|
122 |
#' split_cols_by("ARM") %>% |
|
123 |
#' add_colcounts() %>% |
|
124 |
#' estimate_incidence_rate( |
|
125 |
#' vars = "AVAL", |
|
126 |
#' n_events = "n_events", |
|
127 |
#' control = control_incidence_rate( |
|
128 |
#' input_time_unit = "month", |
|
129 |
#' num_pt_year = 100 |
|
130 |
#' ) |
|
131 |
#' ) %>% |
|
132 |
#' build_table(df) |
|
133 |
#' |
|
134 |
#' @export |
|
135 |
#' @order 2 |
|
136 |
estimate_incidence_rate <- function(lyt, |
|
137 |
vars, |
|
138 |
n_events, |
|
139 |
control = control_incidence_rate(), |
|
140 |
na_str = default_na_str(), |
|
141 |
nested = TRUE, |
|
142 |
..., |
|
143 |
show_labels = "hidden", |
|
144 |
table_names = vars, |
|
145 |
.stats = NULL, |
|
146 |
.formats = NULL, |
|
147 |
.labels = NULL, |
|
148 |
.indent_mods = NULL) { |
|
149 | 1x |
extra_args <- list(n_events = n_events, control = control, ...) |
150 | ||
151 | 1x |
afun <- make_afun( |
152 | 1x |
a_incidence_rate, |
153 | 1x |
.stats = .stats, |
154 | 1x |
.formats = .formats, |
155 | 1x |
.labels = .labels, |
156 | 1x |
.indent_mods = .indent_mods |
157 |
) |
|
158 | ||
159 | 1x |
analyze( |
160 | 1x |
lyt, |
161 | 1x |
vars, |
162 | 1x |
show_labels = show_labels, |
163 | 1x |
table_names = table_names, |
164 | 1x |
afun = afun, |
165 | 1x |
na_str = na_str, |
166 | 1x |
nested = nested, |
167 | 1x |
extra_args = extra_args |
168 |
) |
|
169 |
} |
|
170 | ||
171 |
#' Helper Functions for Incidence Rate |
|
172 |
#' |
|
173 |
#' @description `r lifecycle::badge("stable")` |
|
174 |
#' |
|
175 |
#' @param control (`list`)\cr parameters for estimation details, specified by using |
|
176 |
#' the helper function [control_incidence_rate()]. Possible parameter options are: |
|
177 |
#' * `conf_level`: (`proportion`)\cr confidence level for the estimated incidence rate. |
|
178 |
#' * `conf_type`: (`string`)\cr `normal` (default), `normal_log`, `exact`, or `byar` |
|
179 |
#' for confidence interval type. |
|
180 |
#' * `input_time_unit`: (`string`)\cr `day`, `week`, `month`, or `year` (default) |
|
181 |
#' indicating time unit for data input. |
|
182 |
#' * `num_pt_year`: (`numeric`)\cr time unit for desired output (in person-years). |
|
183 |
#' @param person_years (`numeric`)\cr total person-years at risk. |
|
184 |
#' @param alpha (`numeric`)\cr two-sided alpha-level for confidence interval. |
|
185 |
#' @param n_events (`integer`)\cr number of events observed. |
|
186 |
#' |
|
187 |
#' @return Estimated incidence rate `rate` and associated confidence interval `rate_ci`. |
|
188 |
#' |
|
189 |
#' @seealso [incidence_rate] |
|
190 |
#' |
|
191 |
#' @name h_incidence_rate |
|
192 |
NULL |
|
193 | ||
194 |
#' @describeIn h_incidence_rate Helper function to estimate the incidence rate and |
|
195 |
#' associated confidence interval based on the normal approximation for the |
|
196 |
#' incidence rate. Unit is one person-year. |
|
197 |
#' |
|
198 |
#' @examples |
|
199 |
#' h_incidence_rate_normal(200, 2) |
|
200 |
#' |
|
201 |
#' @export |
|
202 |
h_incidence_rate_normal <- function(person_years, |
|
203 |
n_events, |
|
204 |
alpha = 0.05) { |
|
205 | 1x |
checkmate::assert_number(person_years) |
206 | 1x |
checkmate::assert_number(n_events) |
207 | 1x |
assert_proportion_value(alpha) |
208 | ||
209 | 1x |
est <- n_events / person_years |
210 | 1x |
se <- sqrt(est / person_years) |
211 | 1x |
ci <- est + c(-1, 1) * stats::qnorm(1 - alpha / 2) * se |
212 | ||
213 | 1x |
list(rate = est, rate_ci = ci) |
214 |
} |
|
215 | ||
216 |
#' @describeIn h_incidence_rate Helper function to estimate the incidence rate and |
|
217 |
#' associated confidence interval based on the normal approximation for the |
|
218 |
#' logarithm of the incidence rate. Unit is one person-year. |
|
219 |
#' |
|
220 |
#' @examples |
|
221 |
#' h_incidence_rate_normal_log(200, 2) |
|
222 |
#' |
|
223 |
#' @export |
|
224 |
h_incidence_rate_normal_log <- function(person_years, |
|
225 |
n_events, |
|
226 |
alpha = 0.05) { |
|
227 | 5x |
checkmate::assert_number(person_years) |
228 | 5x |
checkmate::assert_number(n_events) |
229 | 5x |
assert_proportion_value(alpha) |
230 | ||
231 | 5x |
rate_est <- n_events / person_years |
232 | 5x |
rate_se <- sqrt(rate_est / person_years) |
233 | 5x |
lrate_est <- log(rate_est) |
234 | 5x |
lrate_se <- rate_se / rate_est |
235 | 5x |
ci <- exp(lrate_est + c(-1, 1) * stats::qnorm(1 - alpha / 2) * lrate_se) |
236 | ||
237 | 5x |
list(rate = rate_est, rate_ci = ci) |
238 |
} |
|
239 | ||
240 |
#' @describeIn h_incidence_rate Helper function to estimate the incidence rate and |
|
241 |
#' associated exact confidence interval. Unit is one person-year. |
|
242 |
#' |
|
243 |
#' @examples |
|
244 |
#' h_incidence_rate_exact(200, 2) |
|
245 |
#' |
|
246 |
#' @export |
|
247 |
h_incidence_rate_exact <- function(person_years, |
|
248 |
n_events, |
|
249 |
alpha = 0.05) { |
|
250 | 1x |
checkmate::assert_number(person_years) |
251 | 1x |
checkmate::assert_number(n_events) |
252 | 1x |
assert_proportion_value(alpha) |
253 | ||
254 | 1x |
est <- n_events / person_years |
255 | 1x |
lcl <- stats::qchisq(p = (alpha) / 2, df = 2 * n_events) / (2 * person_years) |
256 | 1x |
ucl <- stats::qchisq(p = 1 - (alpha) / 2, df = 2 * n_events + 2) / (2 * person_years) |
257 | ||
258 | 1x |
list(rate = est, rate_ci = c(lcl, ucl)) |
259 |
} |
|
260 | ||
261 |
#' @describeIn h_incidence_rate Helper function to estimate the incidence rate and |
|
262 |
#' associated `Byar`'s confidence interval. Unit is one person-year. |
|
263 |
#' |
|
264 |
#' @examples |
|
265 |
#' h_incidence_rate_byar(200, 2) |
|
266 |
#' |
|
267 |
#' @export |
|
268 |
h_incidence_rate_byar <- function(person_years, |
|
269 |
n_events, |
|
270 |
alpha = 0.05) { |
|
271 | 1x |
checkmate::assert_number(person_years) |
272 | 1x |
checkmate::assert_number(n_events) |
273 | 1x |
assert_proportion_value(alpha) |
274 | ||
275 | 1x |
est <- n_events / person_years |
276 | 1x |
seg_1 <- n_events + 0.5 |
277 | 1x |
seg_2 <- 1 - 1 / (9 * (n_events + 0.5)) |
278 | 1x |
seg_3 <- stats::qnorm(1 - alpha / 2) * sqrt(1 / (n_events + 0.5)) / 3 |
279 | 1x |
lcl <- seg_1 * ((seg_2 - seg_3)^3) / person_years |
280 | 1x |
ucl <- seg_1 * ((seg_2 + seg_3) ^ 3) / person_years # styler: off |
281 | ||
282 | 1x |
list(rate = est, rate_ci = c(lcl, ucl)) |
283 |
} |
|
284 | ||
285 |
#' @describeIn h_incidence_rate Helper function to estimate the incidence rate and |
|
286 |
#' associated confidence interval. |
|
287 |
#' |
|
288 |
#' @keywords internal |
|
289 |
h_incidence_rate <- function(person_years, |
|
290 |
n_events, |
|
291 |
control = control_incidence_rate()) { |
|
292 | 4x |
alpha <- 1 - control$conf_level |
293 | 4x |
est <- switch(control$conf_type, |
294 | 4x |
normal = h_incidence_rate_normal(person_years, n_events, alpha), |
295 | 4x |
normal_log = h_incidence_rate_normal_log(person_years, n_events, alpha), |
296 | 4x |
exact = h_incidence_rate_exact(person_years, n_events, alpha), |
297 | 4x |
byar = h_incidence_rate_byar(person_years, n_events, alpha) |
298 |
) |
|
299 | ||
300 | 4x |
num_pt_year <- control$num_pt_year |
301 | 4x |
list( |
302 | 4x |
rate = est$rate * num_pt_year, |
303 | 4x |
rate_ci = est$rate_ci * num_pt_year |
304 |
) |
|
305 |
} |
1 |
#' Patient Counts for Laboratory Events (Worsen From Baseline) by Highest Grade Post-Baseline |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Patient count and fraction for laboratory events (worsen from baseline) shift table. |
|
6 |
#' |
|
7 |
#' @inheritParams argument_convention |
|
8 |
#' @param variables (named `list` of `string`)\cr list of additional analysis variables including: |
|
9 |
#' * `id` (`string`)\cr subject variable name. |
|
10 |
#' * `baseline_var` (`string`)\cr name of the data column containing baseline toxicity variable. |
|
11 |
#' * `direction_var` (`string`)\cr see `direction_var` for more details. |
|
12 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("abnormal_by_worst_grade_worsen")` |
|
13 |
#' to see all available statistics. |
|
14 |
#' |
|
15 |
#' @seealso Relevant helper functions [h_adlb_worsen()] and [h_worsen_counter()] |
|
16 |
#' |
|
17 |
#' @name abnormal_by_worst_grade_worsen |
|
18 |
#' @order 1 |
|
19 |
NULL |
|
20 | ||
21 |
#' Helper Function to Prepare `ADLB` with Worst Labs |
|
22 |
#' |
|
23 |
#' @description `r lifecycle::badge("stable")` |
|
24 |
#' |
|
25 |
#' Helper function to prepare a `df` for generate the patient count shift table |
|
26 |
#' |
|
27 |
#' @param adlb (`data.frame`)\cr `ADLB` dataframe |
|
28 |
#' @param worst_flag_low (named `vector`)\cr Worst low post-baseline lab grade flag variable |
|
29 |
#' @param worst_flag_high (named `vector`)\cr Worst high post-baseline lab grade flag variable |
|
30 |
#' @param direction_var (`string`)\cr Direction variable specifying the direction of the shift table of interest. |
|
31 |
#' Only lab records flagged by `L`, `H` or `B` are included in the shift table. |
|
32 |
#' * `L`: low direction only |
|
33 |
#' * `H`: high direction only |
|
34 |
#' * `B`: both low and high directions |
|
35 |
#' |
|
36 |
#' @return `h_adlb_worsen()` returns the `adlb` `data.frame` containing only the |
|
37 |
#' worst labs specified according to `worst_flag_low` or `worst_flag_high` for the |
|
38 |
#' direction specified according to `direction_var`. For instance, for a lab that is |
|
39 |
#' needed for the low direction only, only records flagged by `worst_flag_low` are |
|
40 |
#' selected. For a lab that is needed for both low and high directions, the worst |
|
41 |
#' low records are selected for the low direction, and the worst high record are selected |
|
42 |
#' for the high direction. |
|
43 |
#' |
|
44 |
#' @seealso [abnormal_by_worst_grade_worsen] |
|
45 |
#' |
|
46 |
#' @examples |
|
47 |
#' library(dplyr) |
|
48 |
#' |
|
49 |
#' # The direction variable, GRADDR, is based on metadata |
|
50 |
#' adlb <- tern_ex_adlb %>% |
|
51 |
#' mutate( |
|
52 |
#' GRADDR = case_when( |
|
53 |
#' PARAMCD == "ALT" ~ "B", |
|
54 |
#' PARAMCD == "CRP" ~ "L", |
|
55 |
#' PARAMCD == "IGA" ~ "H" |
|
56 |
#' ) |
|
57 |
#' ) %>% |
|
58 |
#' filter(SAFFL == "Y" & ONTRTFL == "Y" & GRADDR != "") |
|
59 |
#' |
|
60 |
#' df <- h_adlb_worsen( |
|
61 |
#' adlb, |
|
62 |
#' worst_flag_low = c("WGRLOFL" = "Y"), |
|
63 |
#' worst_flag_high = c("WGRHIFL" = "Y"), |
|
64 |
#' direction_var = "GRADDR" |
|
65 |
#' ) |
|
66 |
#' |
|
67 |
#' @export |
|
68 |
h_adlb_worsen <- function(adlb, |
|
69 |
worst_flag_low = NULL, |
|
70 |
worst_flag_high = NULL, |
|
71 |
direction_var) { |
|
72 | 5x |
checkmate::assert_string(direction_var) |
73 | 5x |
checkmate::assert_subset(as.character(unique(adlb[[direction_var]])), c("B", "L", "H")) |
74 | 5x |
assert_df_with_variables(adlb, list("Col" = direction_var)) |
75 | ||
76 | 5x |
if (any(unique(adlb[[direction_var]]) == "H")) { |
77 | 4x |
assert_df_with_variables(adlb, list("High" = names(worst_flag_high))) |
78 |
} |
|
79 | ||
80 | 5x |
if (any(unique(adlb[[direction_var]]) == "L")) { |
81 | 4x |
assert_df_with_variables(adlb, list("Low" = names(worst_flag_low))) |
82 |
} |
|
83 | ||
84 | 5x |
if (any(unique(adlb[[direction_var]]) == "B")) { |
85 | 3x |
assert_df_with_variables( |
86 | 3x |
adlb, |
87 | 3x |
list( |
88 | 3x |
"Low" = names(worst_flag_low), |
89 | 3x |
"High" = names(worst_flag_high) |
90 |
) |
|
91 |
) |
|
92 |
} |
|
93 | ||
94 |
# extract patients with worst post-baseline lab, either low or high or both |
|
95 | 5x |
worst_flag <- c(worst_flag_low, worst_flag_high) |
96 | 5x |
col_names <- names(worst_flag) |
97 | 5x |
filter_values <- worst_flag |
98 | 5x |
temp <- Map( |
99 | 5x |
function(x, y) which(adlb[[x]] == y), |
100 | 5x |
col_names, |
101 | 5x |
filter_values |
102 |
) |
|
103 | 5x |
position_satisfy_filters <- Reduce(union, temp) |
104 | ||
105 |
# select variables of interest |
|
106 | 5x |
adlb_f <- adlb[position_satisfy_filters, ] |
107 | ||
108 |
# generate subsets for different directionality |
|
109 | 5x |
adlb_f_h <- adlb_f[which(adlb_f[[direction_var]] == "H"), ] |
110 | 5x |
adlb_f_l <- adlb_f[which(adlb_f[[direction_var]] == "L"), ] |
111 | 5x |
adlb_f_b <- adlb_f[which(adlb_f[[direction_var]] == "B"), ] |
112 | ||
113 |
# for labs requiring both high and low, data is duplicated and will be stacked on top of each other |
|
114 | 5x |
adlb_f_b_h <- adlb_f_b |
115 | 5x |
adlb_f_b_l <- adlb_f_b |
116 | ||
117 |
# extract data with worst lab |
|
118 | 5x |
if (!is.null(worst_flag_high) && !is.null(worst_flag_low)) { |
119 |
# change H to High, L to Low |
|
120 | 3x |
adlb_f_h[[direction_var]] <- rep("High", nrow(adlb_f_h)) |
121 | 3x |
adlb_f_l[[direction_var]] <- rep("Low", nrow(adlb_f_l)) |
122 | ||
123 |
# change, B to High and Low |
|
124 | 3x |
adlb_f_b_h[[direction_var]] <- rep("High", nrow(adlb_f_b_h)) |
125 | 3x |
adlb_f_b_l[[direction_var]] <- rep("Low", nrow(adlb_f_b_l)) |
126 | ||
127 | 3x |
adlb_out_h <- adlb_f_h[which(adlb_f_h[[names(worst_flag_high)]] == worst_flag_high), ] |
128 | 3x |
adlb_out_b_h <- adlb_f_b_h[which(adlb_f_b_h[[names(worst_flag_high)]] == worst_flag_high), ] |
129 | 3x |
adlb_out_l <- adlb_f_l[which(adlb_f_l[[names(worst_flag_low)]] == worst_flag_low), ] |
130 | 3x |
adlb_out_b_l <- adlb_f_b_l[which(adlb_f_b_l[[names(worst_flag_low)]] == worst_flag_low), ] |
131 | ||
132 | 3x |
out <- rbind(adlb_out_h, adlb_out_b_h, adlb_out_l, adlb_out_b_l) |
133 | 2x |
} else if (!is.null(worst_flag_high)) { |
134 | 1x |
adlb_f_h[[direction_var]] <- rep("High", nrow(adlb_f_h)) |
135 | 1x |
adlb_f_b_h[[direction_var]] <- rep("High", nrow(adlb_f_b_h)) |
136 | ||
137 | 1x |
adlb_out_h <- adlb_f_h[which(adlb_f_h[[names(worst_flag_high)]] == worst_flag_high), ] |
138 | 1x |
adlb_out_b_h <- adlb_f_b_h[which(adlb_f_b_h[[names(worst_flag_high)]] == worst_flag_high), ] |
139 | ||
140 | 1x |
out <- rbind(adlb_out_h, adlb_out_b_h) |
141 | 1x |
} else if (!is.null(worst_flag_low)) { |
142 | 1x |
adlb_f_l[[direction_var]] <- rep("Low", nrow(adlb_f_l)) |
143 | 1x |
adlb_f_b_l[[direction_var]] <- rep("Low", nrow(adlb_f_b_l)) |
144 | ||
145 | 1x |
adlb_out_l <- adlb_f_l[which(adlb_f_l[[names(worst_flag_low)]] == worst_flag_low), ] |
146 | 1x |
adlb_out_b_l <- adlb_f_b_l[which(adlb_f_b_l[[names(worst_flag_low)]] == worst_flag_low), ] |
147 | ||
148 | 1x |
out <- rbind(adlb_out_l, adlb_out_b_l) |
149 |
} |
|
150 | ||
151 |
# label |
|
152 | 5x |
formatters::var_labels(out) <- formatters::var_labels(adlb_f, fill = FALSE) |
153 |
# NA |
|
154 | 5x |
out |
155 |
} |
|
156 | ||
157 |
#' Helper Function to Analyze Patients for [s_count_abnormal_lab_worsen_by_baseline()] |
|
158 |
#' |
|
159 |
#' @description `r lifecycle::badge("stable")` |
|
160 |
#' |
|
161 |
#' Helper function to count the number of patients and the fraction of patients according to |
|
162 |
#' highest post-baseline lab grade variable `.var`, baseline lab grade variable `baseline_var`, |
|
163 |
#' and the direction of interest specified in `direction_var`. |
|
164 |
#' |
|
165 |
#' @inheritParams argument_convention |
|
166 |
#' @inheritParams h_adlb_worsen |
|
167 |
#' @param baseline_var (`string`)\cr baseline lab grade variable |
|
168 |
#' |
|
169 |
#' @return `h_worsen_counter()` returns the counts and fraction of patients |
|
170 |
#' whose worst post-baseline lab grades are worse than their baseline grades, for |
|
171 |
#' post-baseline worst grades "1", "2", "3", "4" and "Any". |
|
172 |
#' |
|
173 |
#' @seealso [abnormal_by_worst_grade_worsen] |
|
174 |
#' |
|
175 |
#' @examples |
|
176 |
#' library(dplyr) |
|
177 |
#' |
|
178 |
#' # The direction variable, GRADDR, is based on metadata |
|
179 |
#' adlb <- tern_ex_adlb %>% |
|
180 |
#' mutate( |
|
181 |
#' GRADDR = case_when( |
|
182 |
#' PARAMCD == "ALT" ~ "B", |
|
183 |
#' PARAMCD == "CRP" ~ "L", |
|
184 |
#' PARAMCD == "IGA" ~ "H" |
|
185 |
#' ) |
|
186 |
#' ) %>% |
|
187 |
#' filter(SAFFL == "Y" & ONTRTFL == "Y" & GRADDR != "") |
|
188 |
#' |
|
189 |
#' df <- h_adlb_worsen( |
|
190 |
#' adlb, |
|
191 |
#' worst_flag_low = c("WGRLOFL" = "Y"), |
|
192 |
#' worst_flag_high = c("WGRHIFL" = "Y"), |
|
193 |
#' direction_var = "GRADDR" |
|
194 |
#' ) |
|
195 |
#' |
|
196 |
#' # `h_worsen_counter` |
|
197 |
#' h_worsen_counter( |
|
198 |
#' df %>% filter(PARAMCD == "CRP" & GRADDR == "Low"), |
|
199 |
#' id = "USUBJID", |
|
200 |
#' .var = "ATOXGR", |
|
201 |
#' baseline_var = "BTOXGR", |
|
202 |
#' direction_var = "GRADDR" |
|
203 |
#' ) |
|
204 |
#' |
|
205 |
#' @export |
|
206 |
h_worsen_counter <- function(df, id, .var, baseline_var, direction_var) { |
|
207 | 17x |
checkmate::assert_string(id) |
208 | 17x |
checkmate::assert_string(.var) |
209 | 17x |
checkmate::assert_string(baseline_var) |
210 | 17x |
checkmate::assert_scalar(unique(df[[direction_var]])) |
211 | 17x |
checkmate::assert_subset(unique(df[[direction_var]]), c("High", "Low")) |
212 | 17x |
assert_df_with_variables(df, list(val = c(id, .var, baseline_var, direction_var))) |
213 | ||
214 |
# remove post-baseline missing |
|
215 | 17x |
df <- df[df[[.var]] != "<Missing>", ] |
216 | ||
217 |
# obtain directionality |
|
218 | 17x |
direction <- unique(df[[direction_var]]) |
219 | ||
220 | 17x |
if (direction == "Low") { |
221 | 10x |
grade <- -1:-4 |
222 | 10x |
worst_grade <- -4 |
223 | 7x |
} else if (direction == "High") { |
224 | 7x |
grade <- 1:4 |
225 | 7x |
worst_grade <- 4 |
226 |
} |
|
227 | ||
228 | 17x |
if (nrow(df) > 0) { |
229 | 17x |
by_grade <- lapply(grade, function(i) { |
230 |
# filter baseline values that is less than i or <Missing> |
|
231 | 68x |
df_temp <- df[df[[baseline_var]] %in% c((i + sign(i) * -1):(-1 * worst_grade), "<Missing>"), ] |
232 |
# num: number of patients with post-baseline worst lab equal to i |
|
233 | 68x |
num <- length(unique(df_temp[df_temp[[.var]] %in% i, id, drop = TRUE])) |
234 |
# denom: number of patients with baseline values less than i or <missing> and post-baseline in the same direction |
|
235 | 68x |
denom <- length(unique(df_temp[[id]])) |
236 | 68x |
rm(df_temp) |
237 | 68x |
c(num = num, denom = denom) |
238 |
}) |
|
239 |
} else { |
|
240 | ! |
by_grade <- lapply(1, function(i) { |
241 | ! |
c(num = 0, denom = 0) |
242 |
}) |
|
243 |
} |
|
244 | ||
245 | 17x |
names(by_grade) <- as.character(seq_along(by_grade)) |
246 | ||
247 |
# baseline grade less 4 or missing |
|
248 | 17x |
df_temp <- df[!df[[baseline_var]] %in% worst_grade, ] |
249 | ||
250 |
# denom: number of patients with baseline values less than 4 or <missing> and post-baseline in the same direction |
|
251 | 17x |
denom <- length(unique(df_temp[, id, drop = TRUE])) |
252 | ||
253 |
# condition 1: missing baseline and in the direction of abnormality |
|
254 | 17x |
con1 <- which(df_temp[[baseline_var]] == "<Missing>" & df_temp[[.var]] %in% grade) |
255 | 17x |
df_temp_nm <- df_temp[which(df_temp[[baseline_var]] != "<Missing>" & df_temp[[.var]] %in% grade), ] |
256 | ||
257 |
# condition 2: if post-baseline values are present then post-baseline values must be worse than baseline |
|
258 | 17x |
if (direction == "Low") { |
259 | 10x |
con2 <- which(as.numeric(as.character(df_temp_nm[[.var]])) < as.numeric(as.character(df_temp_nm[[baseline_var]]))) |
260 |
} else { |
|
261 | 7x |
con2 <- which(as.numeric(as.character(df_temp_nm[[.var]])) > as.numeric(as.character(df_temp_nm[[baseline_var]]))) |
262 |
} |
|
263 | ||
264 |
# number of patients satisfy either conditions 1 or 2 |
|
265 | 17x |
num <- length(unique(df_temp[union(con1, con2), id, drop = TRUE])) |
266 | ||
267 | 17x |
list(fraction = c(by_grade, list("Any" = c(num = num, denom = denom)))) |
268 |
} |
|
269 | ||
270 |
#' @describeIn abnormal_by_worst_grade_worsen Statistics function for patients whose worst post-baseline |
|
271 |
#' lab grades are worse than their baseline grades. |
|
272 |
#' |
|
273 |
#' @return |
|
274 |
#' * `s_count_abnormal_lab_worsen_by_baseline()` returns the counts and fraction of patients whose worst |
|
275 |
#' post-baseline lab grades are worse than their baseline grades, for post-baseline worst grades |
|
276 |
#' "1", "2", "3", "4" and "Any". |
|
277 |
#' |
|
278 |
#' @keywords internal |
|
279 |
s_count_abnormal_lab_worsen_by_baseline <- function(df, # nolint |
|
280 |
.var = "ATOXGR", |
|
281 |
variables = list( |
|
282 |
id = "USUBJID", |
|
283 |
baseline_var = "BTOXGR", |
|
284 |
direction_var = "GRADDR" |
|
285 |
)) { |
|
286 | 1x |
checkmate::assert_string(.var) |
287 | 1x |
checkmate::assert_set_equal(names(variables), c("id", "baseline_var", "direction_var")) |
288 | 1x |
checkmate::assert_string(variables$id) |
289 | 1x |
checkmate::assert_string(variables$baseline_var) |
290 | 1x |
checkmate::assert_string(variables$direction_var) |
291 | 1x |
assert_df_with_variables(df, c(aval = .var, variables[1:3])) |
292 | 1x |
assert_list_of_variables(variables) |
293 | ||
294 | 1x |
h_worsen_counter(df, variables$id, .var, variables$baseline_var, variables$direction_var) |
295 |
} |
|
296 | ||
297 | ||
298 |
#' @describeIn abnormal_by_worst_grade_worsen Formatted analysis function which is used as `afun` |
|
299 |
#' in `count_abnormal_lab_worsen_by_baseline()`. |
|
300 |
#' |
|
301 |
#' @return |
|
302 |
#' * `a_count_abnormal_lab_worsen_by_baseline()` returns the corresponding list with |
|
303 |
#' formatted [rtables::CellValue()]. |
|
304 |
#' |
|
305 |
#' @keywords internal |
|
306 |
a_count_abnormal_lab_worsen_by_baseline <- make_afun( # nolint |
|
307 |
s_count_abnormal_lab_worsen_by_baseline, |
|
308 |
.formats = c(fraction = format_fraction), |
|
309 |
.ungroup_stats = "fraction" |
|
310 |
) |
|
311 | ||
312 |
#' @describeIn abnormal_by_worst_grade_worsen Layout-creating function which can take statistics function |
|
313 |
#' arguments and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
314 |
#' |
|
315 |
#' @return |
|
316 |
#' * `count_abnormal_lab_worsen_by_baseline()` returns a layout object suitable for passing to further layouting |
|
317 |
#' functions, or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted |
|
318 |
#' rows containing the statistics from `s_count_abnormal_lab_worsen_by_baseline()` to the table layout. |
|
319 |
#' |
|
320 |
#' @examples |
|
321 |
#' library(dplyr) |
|
322 |
#' |
|
323 |
#' # The direction variable, GRADDR, is based on metadata |
|
324 |
#' adlb <- tern_ex_adlb %>% |
|
325 |
#' mutate( |
|
326 |
#' GRADDR = case_when( |
|
327 |
#' PARAMCD == "ALT" ~ "B", |
|
328 |
#' PARAMCD == "CRP" ~ "L", |
|
329 |
#' PARAMCD == "IGA" ~ "H" |
|
330 |
#' ) |
|
331 |
#' ) %>% |
|
332 |
#' filter(SAFFL == "Y" & ONTRTFL == "Y" & GRADDR != "") |
|
333 |
#' |
|
334 |
#' df <- h_adlb_worsen( |
|
335 |
#' adlb, |
|
336 |
#' worst_flag_low = c("WGRLOFL" = "Y"), |
|
337 |
#' worst_flag_high = c("WGRHIFL" = "Y"), |
|
338 |
#' direction_var = "GRADDR" |
|
339 |
#' ) |
|
340 |
#' |
|
341 |
#' basic_table() %>% |
|
342 |
#' split_cols_by("ARMCD") %>% |
|
343 |
#' add_colcounts() %>% |
|
344 |
#' split_rows_by("PARAMCD") %>% |
|
345 |
#' split_rows_by("GRADDR") %>% |
|
346 |
#' count_abnormal_lab_worsen_by_baseline( |
|
347 |
#' var = "ATOXGR", |
|
348 |
#' variables = list( |
|
349 |
#' id = "USUBJID", |
|
350 |
#' baseline_var = "BTOXGR", |
|
351 |
#' direction_var = "GRADDR" |
|
352 |
#' ) |
|
353 |
#' ) %>% |
|
354 |
#' append_topleft("Direction of Abnormality") %>% |
|
355 |
#' build_table(df = df, alt_counts_df = tern_ex_adsl) |
|
356 |
#' |
|
357 |
#' @export |
|
358 |
#' @order 2 |
|
359 |
count_abnormal_lab_worsen_by_baseline <- function(lyt, # nolint |
|
360 |
var, |
|
361 |
variables = list( |
|
362 |
id = "USUBJID", |
|
363 |
baseline_var = "BTOXGR", |
|
364 |
direction_var = "GRADDR" |
|
365 |
), |
|
366 |
na_str = default_na_str(), |
|
367 |
nested = TRUE, |
|
368 |
..., |
|
369 |
table_names = NULL, |
|
370 |
.stats = NULL, |
|
371 |
.formats = NULL, |
|
372 |
.labels = NULL, |
|
373 |
.indent_mods = NULL) { |
|
374 | 1x |
checkmate::assert_string(var) |
375 | ||
376 | 1x |
extra_args <- list(variables = variables, ...) |
377 | ||
378 | 1x |
afun <- make_afun( |
379 | 1x |
a_count_abnormal_lab_worsen_by_baseline, |
380 | 1x |
.stats = .stats, |
381 | 1x |
.formats = .formats, |
382 | 1x |
.labels = .labels, |
383 | 1x |
.indent_mods = .indent_mods |
384 |
) |
|
385 | ||
386 | 1x |
lyt <- analyze( |
387 | 1x |
lyt = lyt, |
388 | 1x |
vars = var, |
389 | 1x |
afun = afun, |
390 | 1x |
na_str = na_str, |
391 | 1x |
nested = nested, |
392 | 1x |
extra_args = extra_args, |
393 | 1x |
show_labels = "hidden" |
394 |
) |
|
395 | ||
396 | 1x |
lyt |
397 |
} |
1 |
#' Compare Variables Between Groups |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Comparison with a reference group for different `x` objects. |
|
6 |
#' |
|
7 |
#' @inheritParams argument_convention |
|
8 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("analyze_vars_numeric")` to see |
|
9 |
#' statistics available for numeric variables, and `get_stats("analyze_vars_counts")` for statistics available |
|
10 |
#' for non-numeric variables. |
|
11 |
#' |
|
12 |
#' @note |
|
13 |
#' * For factor variables, `denom` for factor proportions can only be `n` since the purpose is to compare proportions |
|
14 |
#' between columns, therefore a row-based proportion would not make sense. Proportion based on `N_col` would |
|
15 |
#' be difficult since we use counts for the chi-squared test statistic, therefore missing values should be accounted |
|
16 |
#' for as explicit factor levels. |
|
17 |
#' * If factor variables contain `NA`, these `NA` values are excluded by default. To include `NA` values |
|
18 |
#' set `na.rm = FALSE` and missing values will be displayed as an `NA` level. Alternatively, an explicit |
|
19 |
#' factor level can be defined for `NA` values during pre-processing via [df_explicit_na()] - the |
|
20 |
#' default `na_level` (`"<Missing>"`) will also be excluded when `na.rm` is set to `TRUE`. |
|
21 |
#' * For character variables, automatic conversion to factor does not guarantee that the table |
|
22 |
#' will be generated correctly. In particular for sparse tables this very likely can fail. |
|
23 |
#' Therefore it is always better to manually convert character variables to factors during pre-processing. |
|
24 |
#' * For `compare_vars()`, the column split must define a reference group via `ref_group` so that the comparison |
|
25 |
#' is well defined. |
|
26 |
#' |
|
27 |
#' @seealso Relevant constructor function [create_afun_compare()], [s_summary()] which is used internally |
|
28 |
#' to compute a summary within `s_compare()`, and [a_compare()] which is used (with `compare = TRUE`) as the analysis |
|
29 |
#' function for `compare_vars()`. |
|
30 |
#' |
|
31 |
#' @name compare_variables |
|
32 |
#' @include analyze_variables.R |
|
33 |
#' @order 1 |
|
34 |
NULL |
|
35 | ||
36 |
#' @describeIn compare_variables S3 generic function to produce a comparison summary. |
|
37 |
#' |
|
38 |
#' @return |
|
39 |
#' * `s_compare()` returns output of [s_summary()] and comparisons versus the reference group in the form of p-values. |
|
40 |
#' |
|
41 |
#' @export |
|
42 |
s_compare <- function(x, |
|
43 |
.ref_group, |
|
44 |
.in_ref_col, |
|
45 |
...) { |
|
46 | 31x |
UseMethod("s_compare", x) |
47 |
} |
|
48 | ||
49 |
#' @describeIn compare_variables Method for `numeric` class. This uses the standard t-test |
|
50 |
#' to calculate the p-value. |
|
51 |
#' |
|
52 |
#' @method s_compare numeric |
|
53 |
#' |
|
54 |
#' @examples |
|
55 |
#' # `s_compare.numeric` |
|
56 |
#' |
|
57 |
#' ## Usual case where both this and the reference group vector have more than 1 value. |
|
58 |
#' s_compare(rnorm(10, 5, 1), .ref_group = rnorm(5, -5, 1), .in_ref_col = FALSE) |
|
59 |
#' |
|
60 |
#' ## If one group has not more than 1 value, then p-value is not calculated. |
|
61 |
#' s_compare(rnorm(10, 5, 1), .ref_group = 1, .in_ref_col = FALSE) |
|
62 |
#' |
|
63 |
#' ## Empty numeric does not fail, it returns NA-filled items and no p-value. |
|
64 |
#' s_compare(numeric(), .ref_group = numeric(), .in_ref_col = FALSE) |
|
65 |
#' |
|
66 |
#' @export |
|
67 |
s_compare.numeric <- function(x, |
|
68 |
.ref_group, |
|
69 |
.in_ref_col, |
|
70 |
...) { |
|
71 | 15x |
checkmate::assert_numeric(x) |
72 | 15x |
checkmate::assert_numeric(.ref_group) |
73 | 15x |
checkmate::assert_flag(.in_ref_col) |
74 | ||
75 | 15x |
y <- s_summary.numeric(x = x, ...) |
76 | ||
77 | 15x |
y$pval <- if (!.in_ref_col && n_available(x) > 1 && n_available(.ref_group) > 1) { |
78 | 11x |
stats::t.test(x, .ref_group)$p.value |
79 |
} else { |
|
80 | 4x |
character() |
81 |
} |
|
82 | ||
83 | 15x |
y |
84 |
} |
|
85 | ||
86 |
#' @describeIn compare_variables Method for `factor` class. This uses the chi-squared test |
|
87 |
#' to calculate the p-value. |
|
88 |
#' |
|
89 |
#' @param denom (`string`)\cr choice of denominator for factor proportions, |
|
90 |
#' can only be `n` (number of values in this row and column intersection). |
|
91 |
#' |
|
92 |
#' @method s_compare factor |
|
93 |
#' |
|
94 |
#' @examples |
|
95 |
#' # `s_compare.factor` |
|
96 |
#' |
|
97 |
#' ## Basic usage: |
|
98 |
#' x <- factor(c("a", "a", "b", "c", "a")) |
|
99 |
#' y <- factor(c("a", "b", "c")) |
|
100 |
#' s_compare(x = x, .ref_group = y, .in_ref_col = FALSE) |
|
101 |
#' |
|
102 |
#' ## Management of NA values. |
|
103 |
#' x <- explicit_na(factor(c("a", "a", "b", "c", "a", NA, NA))) |
|
104 |
#' y <- explicit_na(factor(c("a", "b", "c", NA))) |
|
105 |
#' s_compare(x = x, .ref_group = y, .in_ref_col = FALSE, na.rm = TRUE) |
|
106 |
#' s_compare(x = x, .ref_group = y, .in_ref_col = FALSE, na.rm = FALSE) |
|
107 |
#' |
|
108 |
#' @export |
|
109 |
s_compare.factor <- function(x, |
|
110 |
.ref_group, |
|
111 |
.in_ref_col, |
|
112 |
denom = "n", |
|
113 |
na.rm = TRUE, # nolint |
|
114 |
...) { |
|
115 | 12x |
checkmate::assert_flag(.in_ref_col) |
116 | 12x |
assert_valid_factor(x) |
117 | 12x |
assert_valid_factor(.ref_group) |
118 | 12x |
denom <- match.arg(denom) |
119 | ||
120 | 12x |
y <- s_summary.factor( |
121 | 12x |
x = x, |
122 | 12x |
denom = denom, |
123 | 12x |
na.rm = na.rm, |
124 |
... |
|
125 |
) |
|
126 | ||
127 | 12x |
if (na.rm) { |
128 | 12x |
x <- x[!is.na(x)] %>% fct_discard("<Missing>") |
129 | 12x |
.ref_group <- .ref_group[!is.na(.ref_group)] %>% fct_discard("<Missing>") |
130 |
} else { |
|
131 | ! |
x <- x %>% explicit_na(label = "NA") |
132 | ! |
.ref_group <- .ref_group %>% explicit_na(label = "NA") |
133 |
} |
|
134 | ||
135 | ! |
if ("NA" %in% levels(x)) levels(.ref_group) <- c(levels(.ref_group), "NA") |
136 | 12x |
checkmate::assert_factor(x, levels = levels(.ref_group), min.levels = 2) |
137 | ||
138 | 12x |
y$pval_counts <- if (!.in_ref_col && length(x) > 0 && length(.ref_group) > 0) { |
139 | 9x |
tab <- rbind(table(x), table(.ref_group)) |
140 | 9x |
res <- suppressWarnings(stats::chisq.test(tab)) |
141 | 9x |
res$p.value |
142 |
} else { |
|
143 | 3x |
character() |
144 |
} |
|
145 | ||
146 | 12x |
y |
147 |
} |
|
148 | ||
149 |
#' @describeIn compare_variables Method for `character` class. This makes an automatic |
|
150 |
#' conversion to `factor` (with a warning) and then forwards to the method for factors. |
|
151 |
#' |
|
152 |
#' @param verbose (`logical`)\cr Whether warnings and messages should be printed. Mainly used |
|
153 |
#' to print out information about factor casting. Defaults to `TRUE`. |
|
154 |
#' |
|
155 |
#' @method s_compare character |
|
156 |
#' |
|
157 |
#' @examples |
|
158 |
#' # `s_compare.character` |
|
159 |
#' |
|
160 |
#' ## Basic usage: |
|
161 |
#' x <- c("a", "a", "b", "c", "a") |
|
162 |
#' y <- c("a", "b", "c") |
|
163 |
#' s_compare(x, .ref_group = y, .in_ref_col = FALSE, .var = "x", verbose = FALSE) |
|
164 |
#' |
|
165 |
#' ## Note that missing values handling can make a large difference: |
|
166 |
#' x <- c("a", "a", "b", "c", "a", NA) |
|
167 |
#' y <- c("a", "b", "c", rep(NA, 20)) |
|
168 |
#' s_compare(x, |
|
169 |
#' .ref_group = y, .in_ref_col = FALSE, |
|
170 |
#' .var = "x", verbose = FALSE |
|
171 |
#' ) |
|
172 |
#' s_compare(x, |
|
173 |
#' .ref_group = y, .in_ref_col = FALSE, .var = "x", |
|
174 |
#' na.rm = FALSE, verbose = FALSE |
|
175 |
#' ) |
|
176 |
#' |
|
177 |
#' @export |
|
178 |
s_compare.character <- function(x, |
|
179 |
.ref_group, |
|
180 |
.in_ref_col, |
|
181 |
denom = "n", |
|
182 |
na.rm = TRUE, # nolint |
|
183 |
.var, |
|
184 |
verbose = TRUE, |
|
185 |
...) { |
|
186 | 1x |
x <- as_factor_keep_attributes(x, verbose = verbose) |
187 | 1x |
.ref_group <- as_factor_keep_attributes(.ref_group, verbose = verbose) |
188 | 1x |
s_compare( |
189 | 1x |
x = x, |
190 | 1x |
.ref_group = .ref_group, |
191 | 1x |
.in_ref_col = .in_ref_col, |
192 | 1x |
denom = denom, |
193 | 1x |
na.rm = na.rm, |
194 |
... |
|
195 |
) |
|
196 |
} |
|
197 | ||
198 |
#' @describeIn compare_variables Method for `logical` class. A chi-squared test |
|
199 |
#' is used. If missing values are not removed, then they are counted as `FALSE`. |
|
200 |
#' |
|
201 |
#' @method s_compare logical |
|
202 |
#' |
|
203 |
#' @examples |
|
204 |
#' # `s_compare.logical` |
|
205 |
#' |
|
206 |
#' ## Basic usage: |
|
207 |
#' x <- c(TRUE, FALSE, TRUE, TRUE) |
|
208 |
#' y <- c(FALSE, FALSE, TRUE) |
|
209 |
#' s_compare(x, .ref_group = y, .in_ref_col = FALSE) |
|
210 |
#' |
|
211 |
#' ## Management of NA values. |
|
212 |
#' x <- c(NA, TRUE, FALSE) |
|
213 |
#' y <- c(NA, NA, NA, NA, FALSE) |
|
214 |
#' s_compare(x, .ref_group = y, .in_ref_col = FALSE, na.rm = TRUE) |
|
215 |
#' s_compare(x, .ref_group = y, .in_ref_col = FALSE, na.rm = FALSE) |
|
216 |
#' |
|
217 |
#' @export |
|
218 |
s_compare.logical <- function(x, |
|
219 |
.ref_group, |
|
220 |
.in_ref_col, |
|
221 |
na.rm = TRUE, # nolint |
|
222 |
denom = "n", |
|
223 |
...) { |
|
224 | 3x |
denom <- match.arg(denom) |
225 | ||
226 | 3x |
y <- s_summary.logical( |
227 | 3x |
x = x, |
228 | 3x |
na.rm = na.rm, |
229 | 3x |
denom = denom, |
230 |
... |
|
231 |
) |
|
232 | ||
233 | 3x |
if (na.rm) { |
234 | 2x |
x <- stats::na.omit(x) |
235 | 2x |
.ref_group <- stats::na.omit(.ref_group) |
236 |
} else { |
|
237 | 1x |
x[is.na(x)] <- FALSE |
238 | 1x |
.ref_group[is.na(.ref_group)] <- FALSE |
239 |
} |
|
240 | ||
241 | 3x |
y$pval_counts <- if (!.in_ref_col && length(x) > 0 && length(.ref_group) > 0) { |
242 | 3x |
x <- factor(x, levels = c(TRUE, FALSE)) |
243 | 3x |
.ref_group <- factor(.ref_group, levels = c(TRUE, FALSE)) |
244 | 3x |
tbl <- rbind(table(x), table(.ref_group)) |
245 | 3x |
suppressWarnings(prop_chisq(tbl)) |
246 |
} else { |
|
247 | ! |
character() |
248 |
} |
|
249 | ||
250 | 3x |
y |
251 |
} |
|
252 | ||
253 |
#' @describeIn compare_variables Formatted analysis function which is used as `afun` |
|
254 |
#' in `compare_vars()`. |
|
255 |
#' |
|
256 |
#' @return |
|
257 |
#' * `a_compare()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
258 |
#' |
|
259 |
#' @note `a_compare()` has been deprecated in favor of `a_summary()` with argument `compare` set to `TRUE`. |
|
260 |
#' |
|
261 |
#' @examples |
|
262 |
#' # `a_compare` deprecated - use `a_summary()` instead |
|
263 |
#' a_compare(rnorm(10, 5, 1), .ref_group = rnorm(20, -5, 1), .stats = c("n", "pval")) |
|
264 |
#' |
|
265 |
#' @export |
|
266 |
a_compare <- function(x, |
|
267 |
.N_col, # nolint |
|
268 |
.N_row, # nolint |
|
269 |
.var = NULL, |
|
270 |
.df_row = NULL, |
|
271 |
.ref_group = NULL, |
|
272 |
.in_ref_col = FALSE, |
|
273 |
...) { |
|
274 | 1x |
lifecycle::deprecate_warn( |
275 | 1x |
"0.8.3", |
276 | 1x |
"a_compare()", |
277 | 1x |
details = "Please use a_summary() with argument `compare` set to TRUE instead." |
278 |
) |
|
279 | 1x |
a_summary( |
280 | 1x |
x = x, |
281 | 1x |
.N_col = .N_col, |
282 | 1x |
.N_row = .N_row, |
283 | 1x |
.var = .var, |
284 | 1x |
.df_row = .df_row, |
285 | 1x |
.ref_group = .ref_group, |
286 | 1x |
.in_ref_col = .in_ref_col, |
287 | 1x |
compare = TRUE, |
288 |
... |
|
289 |
) |
|
290 |
} |
|
291 | ||
292 |
#' Constructor Function for [compare_vars()] |
|
293 |
#' |
|
294 |
#' @description `r lifecycle::badge("deprecated")` |
|
295 |
#' |
|
296 |
#' Constructor function which creates a combined formatted analysis function. |
|
297 |
#' |
|
298 |
#' @inheritParams argument_convention |
|
299 |
#' @param .indent_mods (named `vector` of `integer`)\cr indent modifiers for the labels. Each element of the vector |
|
300 |
#' should be a name-value pair with name corresponding to a statistic specified in `.stats` and value the indentation |
|
301 |
#' for that statistic's row label. |
|
302 |
#' |
|
303 |
#' @return Combined formatted analysis function for use in [compare_vars()]. |
|
304 |
#' |
|
305 |
#' @note This function has been deprecated in favor of direct implementation of `a_summary()` with argument `compare` |
|
306 |
#' set to `TRUE`. |
|
307 |
#' |
|
308 |
#' @seealso [compare_vars()] |
|
309 |
#' |
|
310 |
#' @export |
|
311 |
create_afun_compare <- function(.stats = NULL, |
|
312 |
.formats = NULL, |
|
313 |
.labels = NULL, |
|
314 |
.indent_mods = NULL) { |
|
315 | 1x |
lifecycle::deprecate_warn( |
316 | 1x |
"0.8.5.9010", |
317 | 1x |
"create_afun_compare()", |
318 | 1x |
details = "Please use a_summary(compare = TRUE) directly instead." |
319 |
) |
|
320 | 1x |
function(x, |
321 | 1x |
.ref_group, |
322 | 1x |
.in_ref_col, |
323 |
..., |
|
324 | 1x |
.var) { |
325 | ! |
a_summary(x, |
326 | ! |
compare = TRUE, |
327 | ! |
.stats = .stats, |
328 | ! |
.formats = .formats, |
329 | ! |
.labels = .labels, |
330 | ! |
.indent_mods = .indent_mods, |
331 | ! |
.ref_group = .ref_group, |
332 | ! |
.in_ref_col = .in_ref_col, |
333 | ! |
.var = .var, ... |
334 |
) |
|
335 |
} |
|
336 |
} |
|
337 | ||
338 |
#' @describeIn compare_variables Layout-creating function which can take statistics function arguments |
|
339 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
340 |
#' |
|
341 |
#' @param ... arguments passed to `s_compare()`. |
|
342 |
#' @param .indent_mods (named `vector` of `integer`)\cr indent modifiers for the labels. Each element of the vector |
|
343 |
#' should be a name-value pair with name corresponding to a statistic specified in `.stats` and value the indentation |
|
344 |
#' for that statistic's row label. |
|
345 |
#' |
|
346 |
#' @return |
|
347 |
#' * `compare_vars()` returns a layout object suitable for passing to further layouting functions, |
|
348 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
349 |
#' the statistics from `s_compare()` to the table layout. |
|
350 |
#' |
|
351 |
#' @examples |
|
352 |
#' # `compare_vars()` in `rtables` pipelines |
|
353 |
#' |
|
354 |
#' ## Default output within a `rtables` pipeline. |
|
355 |
#' lyt <- basic_table() %>% |
|
356 |
#' split_cols_by("ARMCD", ref_group = "ARM B") %>% |
|
357 |
#' compare_vars(c("AGE", "SEX")) |
|
358 |
#' build_table(lyt, tern_ex_adsl) |
|
359 |
#' |
|
360 |
#' ## Select and format statistics output. |
|
361 |
#' lyt <- basic_table() %>% |
|
362 |
#' split_cols_by("ARMCD", ref_group = "ARM C") %>% |
|
363 |
#' compare_vars( |
|
364 |
#' vars = "AGE", |
|
365 |
#' .stats = c("mean_sd", "pval"), |
|
366 |
#' .formats = c(mean_sd = "xx.x, xx.x"), |
|
367 |
#' .labels = c(mean_sd = "Mean, SD") |
|
368 |
#' ) |
|
369 |
#' build_table(lyt, df = tern_ex_adsl) |
|
370 |
#' |
|
371 |
#' @export |
|
372 |
#' @order 2 |
|
373 |
compare_vars <- function(lyt, |
|
374 |
vars, |
|
375 |
var_labels = vars, |
|
376 |
na_level = lifecycle::deprecated(), |
|
377 |
na_str = default_na_str(), |
|
378 |
nested = TRUE, |
|
379 |
..., |
|
380 |
na.rm = TRUE, # nolint |
|
381 |
show_labels = "default", |
|
382 |
table_names = vars, |
|
383 |
section_div = NA_character_, |
|
384 |
.stats = c("n", "mean_sd", "count_fraction", "pval"), |
|
385 |
.formats = NULL, |
|
386 |
.labels = NULL, |
|
387 |
.indent_mods = NULL) { |
|
388 | 4x |
if (lifecycle::is_present(na_level)) { |
389 | ! |
lifecycle::deprecate_warn("0.9.1", "compare_vars(na_level)", "compare_vars(na_str)") |
390 | ! |
na_str <- na_level |
391 |
} |
|
392 | ||
393 | 4x |
extra_args <- list(.stats = .stats, na.rm = na.rm, na_str = na_str, compare = TRUE, ...) |
394 | 1x |
if (!is.null(.formats)) extra_args[[".formats"]] <- .formats |
395 | 1x |
if (!is.null(.labels)) extra_args[[".labels"]] <- .labels |
396 | ! |
if (!is.null(.indent_mods)) extra_args[[".indent_mods"]] <- .indent_mods |
397 | ||
398 | 4x |
analyze( |
399 | 4x |
lyt = lyt, |
400 | 4x |
vars = vars, |
401 | 4x |
var_labels = var_labels, |
402 | 4x |
afun = a_summary, |
403 | 4x |
na_str = na_str, |
404 | 4x |
nested = nested, |
405 | 4x |
extra_args = extra_args, |
406 | 4x |
inclNAs = TRUE, |
407 | 4x |
show_labels = show_labels, |
408 | 4x |
table_names = table_names, |
409 | 4x |
section_div = section_div |
410 |
) |
|
411 |
} |
1 |
#' Helper Functions for Tabulating Biomarker Effects on Binary Response by Subgroup |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Helper functions which are documented here separately to not confuse the user |
|
6 |
#' when reading about the user-facing functions. |
|
7 |
#' |
|
8 |
#' @inheritParams response_biomarkers_subgroups |
|
9 |
#' @inheritParams extract_rsp_biomarkers |
|
10 |
#' @inheritParams argument_convention |
|
11 |
#' |
|
12 |
#' @examples |
|
13 |
#' library(dplyr) |
|
14 |
#' library(forcats) |
|
15 |
#' |
|
16 |
#' adrs <- tern_ex_adrs |
|
17 |
#' adrs_labels <- formatters::var_labels(adrs) |
|
18 |
#' |
|
19 |
#' adrs_f <- adrs %>% |
|
20 |
#' filter(PARAMCD == "BESRSPI") %>% |
|
21 |
#' mutate(rsp = AVALC == "CR") |
|
22 |
#' formatters::var_labels(adrs_f) <- c(adrs_labels, "Response") |
|
23 |
#' |
|
24 |
#' @name h_response_biomarkers_subgroups |
|
25 |
NULL |
|
26 | ||
27 |
#' @describeIn h_response_biomarkers_subgroups helps with converting the "response" function variable list |
|
28 |
#' to the "logistic regression" variable list. The reason is that currently there is an |
|
29 |
#' inconsistency between the variable names accepted by `extract_rsp_subgroups()` and `fit_logistic()`. |
|
30 |
#' |
|
31 |
#' @param biomarker (`string`)\cr the name of the biomarker variable. |
|
32 |
#' |
|
33 |
#' @return |
|
34 |
#' * `h_rsp_to_logistic_variables()` returns a named `list` of elements `response`, `arm`, `covariates`, and `strata`. |
|
35 |
#' |
|
36 |
#' @examples |
|
37 |
#' # This is how the variable list is converted internally. |
|
38 |
#' h_rsp_to_logistic_variables( |
|
39 |
#' variables = list( |
|
40 |
#' rsp = "RSP", |
|
41 |
#' covariates = c("A", "B"), |
|
42 |
#' strat = "D" |
|
43 |
#' ), |
|
44 |
#' biomarker = "AGE" |
|
45 |
#' ) |
|
46 |
#' |
|
47 |
#' @export |
|
48 |
h_rsp_to_logistic_variables <- function(variables, biomarker) { |
|
49 | 49x |
checkmate::assert_list(variables) |
50 | 49x |
checkmate::assert_string(variables$rsp) |
51 | 49x |
checkmate::assert_string(biomarker) |
52 | 49x |
list( |
53 | 49x |
response = variables$rsp, |
54 | 49x |
arm = biomarker, |
55 | 49x |
covariates = variables$covariates, |
56 | 49x |
strata = variables$strat |
57 |
) |
|
58 |
} |
|
59 | ||
60 |
#' @describeIn h_response_biomarkers_subgroups prepares estimates for number of responses, patients and |
|
61 |
#' overall response rate, as well as odds ratio estimates, confidence intervals and p-values, for multiple |
|
62 |
#' biomarkers in a given single data set. |
|
63 |
#' `variables` corresponds to names of variables found in `data`, passed as a named list and requires elements |
|
64 |
#' `rsp` and `biomarkers` (vector of continuous biomarker variables) and optionally `covariates` |
|
65 |
#' and `strat`. |
|
66 |
#' |
|
67 |
#' @return |
|
68 |
#' * `h_logistic_mult_cont_df()` returns a `data.frame` containing estimates and statistics for the selected biomarkers. |
|
69 |
#' |
|
70 |
#' @examples |
|
71 |
#' # For a single population, estimate separately the effects |
|
72 |
#' # of two biomarkers. |
|
73 |
#' df <- h_logistic_mult_cont_df( |
|
74 |
#' variables = list( |
|
75 |
#' rsp = "rsp", |
|
76 |
#' biomarkers = c("BMRKR1", "AGE"), |
|
77 |
#' covariates = "SEX" |
|
78 |
#' ), |
|
79 |
#' data = adrs_f |
|
80 |
#' ) |
|
81 |
#' df |
|
82 |
#' |
|
83 |
#' # If the data set is empty, still the corresponding rows with missings are returned. |
|
84 |
#' h_coxreg_mult_cont_df( |
|
85 |
#' variables = list( |
|
86 |
#' rsp = "rsp", |
|
87 |
#' biomarkers = c("BMRKR1", "AGE"), |
|
88 |
#' covariates = "SEX", |
|
89 |
#' strat = "STRATA1" |
|
90 |
#' ), |
|
91 |
#' data = adrs_f[NULL, ] |
|
92 |
#' ) |
|
93 |
#' |
|
94 |
#' @export |
|
95 |
h_logistic_mult_cont_df <- function(variables, |
|
96 |
data, |
|
97 |
control = control_logistic()) { |
|
98 | 28x |
assert_df_with_variables(data, variables) |
99 | ||
100 | 28x |
checkmate::assert_character(variables$biomarkers, min.len = 1, any.missing = FALSE) |
101 | 28x |
checkmate::assert_list(control, names = "named") |
102 | ||
103 | 28x |
conf_level <- control[["conf_level"]] |
104 | 28x |
pval_label <- "p-value (Wald)" |
105 | ||
106 |
# If there is any data, run model, otherwise return empty results. |
|
107 | 28x |
if (nrow(data) > 0) { |
108 | 27x |
bm_cols <- match(variables$biomarkers, names(data)) |
109 | 27x |
l_result <- lapply(variables$biomarkers, function(bm) { |
110 | 48x |
model_fit <- fit_logistic( |
111 | 48x |
variables = h_rsp_to_logistic_variables(variables, bm), |
112 | 48x |
data = data, |
113 | 48x |
response_definition = control$response_definition |
114 |
) |
|
115 | 48x |
result <- h_logistic_simple_terms( |
116 | 48x |
x = bm, |
117 | 48x |
fit_glm = model_fit, |
118 | 48x |
conf_level = control$conf_level |
119 |
) |
|
120 | 48x |
resp_vector <- if (inherits(model_fit, "glm")) { |
121 | 38x |
model_fit$model[[variables$rsp]] |
122 |
} else { |
|
123 | 10x |
as.logical(as.matrix(model_fit$y)[, "status"]) |
124 |
} |
|
125 | 48x |
data.frame( |
126 |
# Dummy column needed downstream to create a nested header. |
|
127 | 48x |
biomarker = bm, |
128 | 48x |
biomarker_label = formatters::var_labels(data[bm], fill = TRUE), |
129 | 48x |
n_tot = length(resp_vector), |
130 | 48x |
n_rsp = sum(resp_vector), |
131 | 48x |
prop = mean(resp_vector), |
132 | 48x |
or = as.numeric(result[1L, "odds_ratio"]), |
133 | 48x |
lcl = as.numeric(result[1L, "lcl"]), |
134 | 48x |
ucl = as.numeric(result[1L, "ucl"]), |
135 | 48x |
conf_level = conf_level, |
136 | 48x |
pval = as.numeric(result[1L, "pvalue"]), |
137 | 48x |
pval_label = pval_label, |
138 | 48x |
stringsAsFactors = FALSE |
139 |
) |
|
140 |
}) |
|
141 | 27x |
do.call(rbind, args = c(l_result, make.row.names = FALSE)) |
142 |
} else { |
|
143 | 1x |
data.frame( |
144 | 1x |
biomarker = variables$biomarkers, |
145 | 1x |
biomarker_label = formatters::var_labels(data[variables$biomarkers], fill = TRUE), |
146 | 1x |
n_tot = 0L, |
147 | 1x |
n_rsp = 0L, |
148 | 1x |
prop = NA, |
149 | 1x |
or = NA, |
150 | 1x |
lcl = NA, |
151 | 1x |
ucl = NA, |
152 | 1x |
conf_level = conf_level, |
153 | 1x |
pval = NA, |
154 | 1x |
pval_label = pval_label, |
155 | 1x |
row.names = seq_along(variables$biomarkers), |
156 | 1x |
stringsAsFactors = FALSE |
157 |
) |
|
158 |
} |
|
159 |
} |
|
160 | ||
161 |
#' @describeIn h_response_biomarkers_subgroups prepares a single sub-table given a `df_sub` containing |
|
162 |
#' the results for a single biomarker. |
|
163 |
#' |
|
164 |
#' @param df (`data.frame`)\cr results for a single biomarker, as part of what is |
|
165 |
#' returned by [extract_rsp_biomarkers()] (it needs a couple of columns which are |
|
166 |
#' added by that high-level function relative to what is returned by [h_logistic_mult_cont_df()], |
|
167 |
#' see the example). |
|
168 |
#' |
|
169 |
#' @return |
|
170 |
#' * `h_tab_rsp_one_biomarker()` returns an `rtables` table object with the given statistics arranged in columns. |
|
171 |
#' |
|
172 |
#' @examples |
|
173 |
#' # Starting from above `df`, zoom in on one biomarker and add required columns. |
|
174 |
#' df1 <- df[1, ] |
|
175 |
#' df1$subgroup <- "All patients" |
|
176 |
#' df1$row_type <- "content" |
|
177 |
#' df1$var <- "ALL" |
|
178 |
#' df1$var_label <- "All patients" |
|
179 |
#' |
|
180 |
#' h_tab_rsp_one_biomarker( |
|
181 |
#' df1, |
|
182 |
#' vars = c("n_tot", "n_rsp", "prop", "or", "ci", "pval") |
|
183 |
#' ) |
|
184 |
#' |
|
185 |
#' @export |
|
186 |
h_tab_rsp_one_biomarker <- function(df, |
|
187 |
vars, |
|
188 |
na_str = default_na_str(), |
|
189 |
.indent_mods = 0L) { |
|
190 | 8x |
afuns <- a_response_subgroups(na_str = na_str)[vars] |
191 | 8x |
colvars <- d_rsp_subgroups_colvars( |
192 | 8x |
vars, |
193 | 8x |
conf_level = df$conf_level[1], |
194 | 8x |
method = df$pval_label[1] |
195 |
) |
|
196 | 8x |
h_tab_one_biomarker( |
197 | 8x |
df = df, |
198 | 8x |
afuns = afuns, |
199 | 8x |
colvars = colvars, |
200 | 8x |
na_str = na_str, |
201 | 8x |
.indent_mods = .indent_mods |
202 |
) |
|
203 |
} |
1 |
#' Counting Patients and Events in Columns |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Counting the number of unique patients and the total number of all and specific events |
|
6 |
#' when a column table layout is required. |
|
7 |
#' |
|
8 |
#' @inheritParams argument_convention |
|
9 |
#' @param filters_list (named `list` of `character`)\cr each element in this list describes one |
|
10 |
#' type of event describe by filters, in the same format as [s_count_patients_with_event()]. |
|
11 |
#' If it has a label, then this will be used for the column title. |
|
12 |
#' @param empty_stats (`character`)\cr optional names of the statistics that should be returned empty such |
|
13 |
#' that corresponding table cells will stay blank. |
|
14 |
#' @param custom_label (`string` or `NULL`)\cr if provided and `labelstr` is empty then this will |
|
15 |
#' be used as label. |
|
16 |
#' @param .stats (`character`)\cr statistics to select for the table. Run |
|
17 |
#' `get_stats("summarize_patients_events_in_cols")` to see available statistics for this function, in addition |
|
18 |
#' to any added using `filters_list`. |
|
19 |
#' |
|
20 |
#' @name count_patients_events_in_cols |
|
21 |
#' @order 1 |
|
22 |
NULL |
|
23 | ||
24 |
#' @describeIn count_patients_events_in_cols Statistics function which counts numbers of patients and multiple |
|
25 |
#' events defined by filters. Used as analysis function `afun` in `summarize_patients_events_in_cols()`. |
|
26 |
#' |
|
27 |
#' @return |
|
28 |
#' * `s_count_patients_and_multiple_events()` returns a list with the statistics: |
|
29 |
#' - `unique`: number of unique patients in `df`. |
|
30 |
#' - `all`: number of rows in `df`. |
|
31 |
#' - one element with the same name as in `filters_list`: number of rows in `df`, |
|
32 |
#' i.e. events, fulfilling the filter condition. |
|
33 |
#' |
|
34 |
#' @keywords internal |
|
35 |
s_count_patients_and_multiple_events <- function(df, # nolint |
|
36 |
id, |
|
37 |
filters_list, |
|
38 |
empty_stats = character(), |
|
39 |
labelstr = "", |
|
40 |
custom_label = NULL) { |
|
41 | 9x |
checkmate::assert_list(filters_list, names = "named") |
42 | 9x |
checkmate::assert_data_frame(df) |
43 | 9x |
checkmate::assert_string(id) |
44 | 9x |
checkmate::assert_disjunct(c("unique", "all"), names(filters_list)) |
45 | 9x |
checkmate::assert_character(empty_stats) |
46 | 9x |
checkmate::assert_string(labelstr) |
47 | 9x |
checkmate::assert_string(custom_label, null.ok = TRUE) |
48 | ||
49 |
# Below we want to count each row in `df` once, therefore introducing this helper index column. |
|
50 | 9x |
df$.row_index <- as.character(seq_len(nrow(df))) |
51 | 9x |
y <- list() |
52 | 9x |
row_label <- if (labelstr != "") { |
53 | ! |
labelstr |
54 | 9x |
} else if (!is.null(custom_label)) { |
55 | 2x |
custom_label |
56 |
} else { |
|
57 | 7x |
"counts" |
58 |
} |
|
59 | 9x |
y$unique <- formatters::with_label( |
60 | 9x |
s_num_patients_content(df = df, .N_col = 1, .var = id, required = NULL)$unique[1L], |
61 | 9x |
row_label |
62 |
) |
|
63 | 9x |
y$all <- formatters::with_label( |
64 | 9x |
nrow(df), |
65 | 9x |
row_label |
66 |
) |
|
67 | 9x |
events <- Map( |
68 | 9x |
function(filters) { |
69 | 25x |
formatters::with_label( |
70 | 25x |
s_count_patients_with_event(df = df, .var = ".row_index", filters = filters, .N_col = 1, .N_row = 1)$count, |
71 | 25x |
row_label |
72 |
) |
|
73 |
}, |
|
74 | 9x |
filters = filters_list |
75 |
) |
|
76 | 9x |
y_complete <- c(y, events) |
77 | 9x |
y <- if (length(empty_stats) > 0) { |
78 | 3x |
y_reduced <- y_complete |
79 | 3x |
for (stat in intersect(names(y_complete), empty_stats)) { |
80 | 4x |
y_reduced[[stat]] <- formatters::with_label(character(), obj_label(y_reduced[[stat]])) |
81 |
} |
|
82 | 3x |
y_reduced |
83 |
} else { |
|
84 | 6x |
y_complete |
85 |
} |
|
86 | 9x |
y |
87 |
} |
|
88 | ||
89 |
#' @describeIn count_patients_events_in_cols Layout-creating function which can take statistics function |
|
90 |
#' arguments and additional format arguments. This function is a wrapper for [rtables::summarize_row_groups()]. |
|
91 |
#' |
|
92 |
#' @param col_split (`flag`)\cr whether the columns should be split. |
|
93 |
#' Set to `FALSE` when the required column split has been done already earlier in the layout pipe. |
|
94 |
#' |
|
95 |
#' @return |
|
96 |
#' * `summarize_patients_events_in_cols()` returns a layout object suitable for passing to further layouting functions, |
|
97 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted content rows |
|
98 |
#' containing the statistics from `s_count_patients_and_multiple_events()` to the table layout. |
|
99 |
#' |
|
100 |
#' @examples |
|
101 |
#' df <- data.frame( |
|
102 |
#' USUBJID = rep(c("id1", "id2", "id3", "id4"), c(2, 3, 1, 1)), |
|
103 |
#' ARM = c("A", "A", "B", "B", "B", "B", "A"), |
|
104 |
#' AESER = rep("Y", 7), |
|
105 |
#' AESDTH = c("Y", "Y", "N", "Y", "Y", "N", "N"), |
|
106 |
#' AEREL = c("Y", "Y", "N", "Y", "Y", "N", "Y"), |
|
107 |
#' AEDECOD = c("A", "A", "A", "B", "B", "C", "D"), |
|
108 |
#' AEBODSYS = rep(c("SOC1", "SOC2", "SOC3"), c(3, 3, 1)) |
|
109 |
#' ) |
|
110 |
#' |
|
111 |
#' # `summarize_patients_events_in_cols()` |
|
112 |
#' basic_table() %>% |
|
113 |
#' summarize_patients_events_in_cols( |
|
114 |
#' filters_list = list( |
|
115 |
#' related = formatters::with_label(c(AEREL = "Y"), "Events (Related)"), |
|
116 |
#' fatal = c(AESDTH = "Y"), |
|
117 |
#' fatal_related = c(AEREL = "Y", AESDTH = "Y") |
|
118 |
#' ), |
|
119 |
#' custom_label = "%s Total number of patients and events" |
|
120 |
#' ) %>% |
|
121 |
#' build_table(df) |
|
122 |
#' |
|
123 |
#' @export |
|
124 |
#' @order 2 |
|
125 |
summarize_patients_events_in_cols <- function(lyt, # nolint |
|
126 |
id = "USUBJID", |
|
127 |
filters_list = list(), |
|
128 |
empty_stats = character(), |
|
129 |
na_str = default_na_str(), |
|
130 |
..., |
|
131 |
.stats = c( |
|
132 |
"unique", |
|
133 |
"all", |
|
134 |
names(filters_list) |
|
135 |
), |
|
136 |
.labels = c( |
|
137 |
unique = "Patients (All)", |
|
138 |
all = "Events (All)", |
|
139 |
labels_or_names(filters_list) |
|
140 |
), |
|
141 |
col_split = TRUE) { |
|
142 | 2x |
extra_args <- list(id = id, filters_list = filters_list, empty_stats = empty_stats, ...) |
143 | ||
144 | 2x |
afun_list <- Map( |
145 | 2x |
function(stat) { |
146 | 7x |
make_afun( |
147 | 7x |
s_count_patients_and_multiple_events, |
148 | 7x |
.stats = stat, |
149 | 7x |
.formats = "xx." |
150 |
) |
|
151 |
}, |
|
152 | 2x |
stat = .stats |
153 |
) |
|
154 | 2x |
if (col_split) { |
155 | 2x |
lyt <- split_cols_by_multivar( |
156 | 2x |
lyt = lyt, |
157 | 2x |
vars = rep(id, length(.stats)), |
158 | 2x |
varlabels = .labels[.stats] |
159 |
) |
|
160 |
} |
|
161 | 2x |
summarize_row_groups( |
162 | 2x |
lyt = lyt, |
163 | 2x |
cfun = afun_list, |
164 | 2x |
na_str = na_str, |
165 | 2x |
extra_args = extra_args |
166 |
) |
|
167 |
} |
1 |
#' Helper Function for Tabulation of a Single Biomarker Result |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Please see [h_tab_surv_one_biomarker()] and [h_tab_rsp_one_biomarker()], which use this function for examples. |
|
6 |
#' This function is a wrapper for [rtables::summarize_row_groups()]. |
|
7 |
#' |
|
8 |
#' @inheritParams argument_convention |
|
9 |
#' @param df (`data.frame`)\cr results for a single biomarker. |
|
10 |
#' @param afuns (named `list` of `function`)\cr analysis functions. |
|
11 |
#' @param colvars (`list` with `vars` and `labels`)\cr variables to tabulate and their labels. |
|
12 |
#' |
|
13 |
#' @return An `rtables` table object with statistics in columns. |
|
14 |
#' |
|
15 |
#' @export |
|
16 |
h_tab_one_biomarker <- function(df, |
|
17 |
afuns, |
|
18 |
colvars, |
|
19 |
na_str = default_na_str(), |
|
20 |
.indent_mods = 0L, |
|
21 |
...) { |
|
22 | 16x |
extra_args <- list(...) |
23 | ||
24 | 16x |
lyt <- basic_table() |
25 | ||
26 |
# Row split by row type - only keep the content rows here. |
|
27 | 16x |
lyt <- split_rows_by( |
28 | 16x |
lyt = lyt, |
29 | 16x |
var = "row_type", |
30 | 16x |
split_fun = keep_split_levels("content"), |
31 | 16x |
nested = FALSE |
32 |
) |
|
33 | ||
34 |
# Summarize rows with all patients. |
|
35 | 16x |
lyt <- summarize_row_groups( |
36 | 16x |
lyt = lyt, |
37 | 16x |
var = "var_label", |
38 | 16x |
cfun = afuns, |
39 | 16x |
na_str = na_str, |
40 | 16x |
indent_mod = .indent_mods, |
41 | 16x |
extra_args = extra_args |
42 |
) |
|
43 | ||
44 |
# Split cols by the multiple variables to populate into columns. |
|
45 | 16x |
lyt <- split_cols_by_multivar( |
46 | 16x |
lyt = lyt, |
47 | 16x |
vars = colvars$vars, |
48 | 16x |
varlabels = colvars$labels |
49 |
) |
|
50 | ||
51 |
# If there is any subgroup variables, we extend the layout accordingly. |
|
52 | 16x |
if ("analysis" %in% df$row_type) { |
53 |
# Now only continue with the subgroup rows. |
|
54 | 8x |
lyt <- split_rows_by( |
55 | 8x |
lyt = lyt, |
56 | 8x |
var = "row_type", |
57 | 8x |
split_fun = keep_split_levels("analysis"), |
58 | 8x |
nested = FALSE, |
59 | 8x |
child_labels = "hidden" |
60 |
) |
|
61 | ||
62 |
# Split by the subgroup variable. |
|
63 | 8x |
lyt <- split_rows_by( |
64 | 8x |
lyt = lyt, |
65 | 8x |
var = "var", |
66 | 8x |
labels_var = "var_label", |
67 | 8x |
nested = TRUE, |
68 | 8x |
child_labels = "visible", |
69 | 8x |
indent_mod = .indent_mods * 2 |
70 |
) |
|
71 | ||
72 |
# Then analyze colvars for each subgroup. |
|
73 | 8x |
lyt <- summarize_row_groups( |
74 | 8x |
lyt = lyt, |
75 | 8x |
cfun = afuns, |
76 | 8x |
var = "subgroup", |
77 | 8x |
na_str = na_str, |
78 | 8x |
extra_args = extra_args |
79 |
) |
|
80 |
} |
|
81 | 16x |
build_table(lyt, df = df) |
82 |
} |
1 |
#' Estimation of Proportions per Level of Factor |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Estimate the proportion along with confidence interval of a proportion |
|
6 |
#' regarding the level of a factor. |
|
7 |
#' |
|
8 |
#' @inheritParams argument_convention |
|
9 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("estimate_multinomial_response")` |
|
10 |
#' to see available statistics for this function. |
|
11 |
#' |
|
12 |
#' @seealso Relevant description function [d_onco_rsp_label()]. |
|
13 |
#' |
|
14 |
#' @name estimate_multinomial_rsp |
|
15 |
#' @order 1 |
|
16 |
NULL |
|
17 | ||
18 |
#' Description of Standard Oncology Response |
|
19 |
#' |
|
20 |
#' @description `r lifecycle::badge("stable")` |
|
21 |
#' |
|
22 |
#' Describe the oncology response in a standard way. |
|
23 |
#' |
|
24 |
#' @param x (`character`)\cr the standard oncology code to be described. |
|
25 |
#' |
|
26 |
#' @return Response labels. |
|
27 |
#' |
|
28 |
#' @seealso [estimate_multinomial_rsp()] |
|
29 |
#' |
|
30 |
#' @examples |
|
31 |
#' d_onco_rsp_label( |
|
32 |
#' c("CR", "PR", "SD", "NON CR/PD", "PD", "NE", "Missing", "<Missing>", "NE/Missing") |
|
33 |
#' ) |
|
34 |
#' |
|
35 |
#' # Adding some values not considered in d_onco_rsp_label |
|
36 |
#' |
|
37 |
#' d_onco_rsp_label( |
|
38 |
#' c("CR", "PR", "hello", "hi") |
|
39 |
#' ) |
|
40 |
#' |
|
41 |
#' @export |
|
42 |
d_onco_rsp_label <- function(x) { |
|
43 | 2x |
x <- as.character(x) |
44 | 2x |
desc <- c( |
45 | 2x |
CR = "Complete Response (CR)", |
46 | 2x |
PR = "Partial Response (PR)", |
47 | 2x |
MR = "Minimal/Minor Response (MR)", |
48 | 2x |
MRD = "Minimal Residual Disease (MRD)", |
49 | 2x |
SD = "Stable Disease (SD)", |
50 | 2x |
PD = "Progressive Disease (PD)", |
51 | 2x |
`NON CR/PD` = "Non-CR or Non-PD (NON CR/PD)", |
52 | 2x |
NE = "Not Evaluable (NE)", |
53 | 2x |
`NE/Missing` = "Missing or unevaluable", |
54 | 2x |
Missing = "Missing", |
55 | 2x |
`NA` = "Not Applicable (NA)", |
56 | 2x |
ND = "Not Done (ND)" |
57 |
) |
|
58 | ||
59 | 2x |
values_label <- vapply( |
60 | 2x |
X = x, |
61 | 2x |
FUN.VALUE = character(1), |
62 | 2x |
function(val) { |
63 | ! |
if (val %in% names(desc)) desc[val] else val |
64 |
} |
|
65 |
) |
|
66 | ||
67 | 2x |
return(factor(values_label, levels = c(intersect(desc, values_label), setdiff(values_label, desc)))) |
68 |
} |
|
69 | ||
70 |
#' @describeIn estimate_multinomial_rsp Statistics function which feeds the length of `x` as number |
|
71 |
#' of successes, and `.N_col` as total number of successes and failures into [s_proportion()]. |
|
72 |
#' |
|
73 |
#' @return |
|
74 |
#' * `s_length_proportion()` returns statistics from [s_proportion()]. |
|
75 |
#' |
|
76 |
#' @examples |
|
77 |
#' s_length_proportion(rep("CR", 10), .N_col = 100) |
|
78 |
#' s_length_proportion(factor(character(0)), .N_col = 100) |
|
79 |
#' |
|
80 |
#' @export |
|
81 |
s_length_proportion <- function(x, |
|
82 |
.N_col, # nolint |
|
83 |
...) { |
|
84 | 4x |
checkmate::assert_multi_class(x, classes = c("factor", "character")) |
85 | 3x |
checkmate::assert_vector(x, min.len = 0, max.len = .N_col) |
86 | 2x |
checkmate::assert_vector(unique(x), min.len = 0, max.len = 1) |
87 | ||
88 | 1x |
n_true <- length(x) |
89 | 1x |
n_false <- .N_col - n_true |
90 | 1x |
x_logical <- rep(c(TRUE, FALSE), c(n_true, n_false)) |
91 | 1x |
s_proportion(df = x_logical, ...) |
92 |
} |
|
93 | ||
94 |
#' @describeIn estimate_multinomial_rsp Formatted analysis function which is used as `afun` |
|
95 |
#' in `estimate_multinomial_response()`. |
|
96 |
#' |
|
97 |
#' @return |
|
98 |
#' * `a_length_proportion()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
99 |
#' |
|
100 |
#' @examples |
|
101 |
#' a_length_proportion(rep("CR", 10), .N_col = 100) |
|
102 |
#' a_length_proportion(factor(character(0)), .N_col = 100) |
|
103 |
#' |
|
104 |
#' @export |
|
105 |
a_length_proportion <- make_afun( |
|
106 |
s_length_proportion, |
|
107 |
.formats = c( |
|
108 |
n_prop = "xx (xx.x%)", |
|
109 |
prop_ci = "(xx.xx, xx.xx)" |
|
110 |
) |
|
111 |
) |
|
112 | ||
113 |
#' @describeIn estimate_multinomial_rsp Layout-creating function which can take statistics function arguments |
|
114 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()] and |
|
115 |
#' [rtables::summarize_row_groups()]. |
|
116 |
#' |
|
117 |
#' @return |
|
118 |
#' * `estimate_multinomial_response()` returns a layout object suitable for passing to further layouting functions, |
|
119 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
120 |
#' the statistics from `s_length_proportion()` to the table layout. |
|
121 |
#' |
|
122 |
#' @examples |
|
123 |
#' library(dplyr) |
|
124 |
#' |
|
125 |
#' # Use of the layout creating function. |
|
126 |
#' dta_test <- data.frame( |
|
127 |
#' USUBJID = paste0("S", 1:12), |
|
128 |
#' ARM = factor(rep(LETTERS[1:3], each = 4)), |
|
129 |
#' AVAL = c(A = c(1, 1, 1, 1), B = c(0, 0, 1, 1), C = c(0, 0, 0, 0)) |
|
130 |
#' ) %>% mutate( |
|
131 |
#' AVALC = factor(AVAL, |
|
132 |
#' levels = c(0, 1), |
|
133 |
#' labels = c("Complete Response (CR)", "Partial Response (PR)") |
|
134 |
#' ) |
|
135 |
#' ) |
|
136 |
#' |
|
137 |
#' lyt <- basic_table() %>% |
|
138 |
#' split_cols_by("ARM") %>% |
|
139 |
#' estimate_multinomial_response(var = "AVALC") |
|
140 |
#' |
|
141 |
#' tbl <- build_table(lyt, dta_test) |
|
142 |
#' |
|
143 |
#' tbl |
|
144 |
#' |
|
145 |
#' @export |
|
146 |
#' @order 2 |
|
147 |
estimate_multinomial_response <- function(lyt, |
|
148 |
var, |
|
149 |
na_str = default_na_str(), |
|
150 |
nested = TRUE, |
|
151 |
..., |
|
152 |
show_labels = "hidden", |
|
153 |
table_names = var, |
|
154 |
.stats = "prop_ci", |
|
155 |
.formats = NULL, |
|
156 |
.labels = NULL, |
|
157 |
.indent_mods = NULL) { |
|
158 | 1x |
extra_args <- list(...) |
159 | ||
160 | 1x |
afun <- make_afun( |
161 | 1x |
a_length_proportion, |
162 | 1x |
.stats = .stats, |
163 | 1x |
.formats = .formats, |
164 | 1x |
.labels = .labels, |
165 | 1x |
.indent_mods = .indent_mods |
166 |
) |
|
167 | 1x |
lyt <- split_rows_by(lyt, var = var) |
168 | 1x |
lyt <- summarize_row_groups(lyt, na_str = na_str) |
169 | ||
170 | 1x |
analyze( |
171 | 1x |
lyt, |
172 | 1x |
vars = var, |
173 | 1x |
afun = afun, |
174 | 1x |
show_labels = show_labels, |
175 | 1x |
table_names = table_names, |
176 | 1x |
na_str = na_str, |
177 | 1x |
nested = nested, |
178 | 1x |
extra_args = extra_args |
179 |
) |
|
180 |
} |
1 |
#' Helper Functions for Cox Proportional Hazards Regression |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Helper functions used in [fit_coxreg_univar()] and [fit_coxreg_multivar()]. |
|
6 |
#' |
|
7 |
#' @inheritParams argument_convention |
|
8 |
#' @inheritParams h_coxreg_univar_extract |
|
9 |
#' @inheritParams cox_regression_inter |
|
10 |
#' @inheritParams control_coxreg |
|
11 |
#' |
|
12 |
#' @seealso [cox_regression] |
|
13 |
#' |
|
14 |
#' @name h_cox_regression |
|
15 |
NULL |
|
16 | ||
17 |
#' @describeIn h_cox_regression Helper for Cox regression formula. Creates a list of formulas. It is used |
|
18 |
#' internally by [fit_coxreg_univar()] for the comparison of univariate Cox regression models. |
|
19 |
#' |
|
20 |
#' @return |
|
21 |
#' * `h_coxreg_univar_formulas()` returns a `character` vector coercible into formulas (e.g [stats::as.formula()]). |
|
22 |
#' |
|
23 |
#' @examples |
|
24 |
#' # `h_coxreg_univar_formulas` |
|
25 |
#' |
|
26 |
#' ## Simple formulas. |
|
27 |
#' h_coxreg_univar_formulas( |
|
28 |
#' variables = list( |
|
29 |
#' time = "time", event = "status", arm = "armcd", covariates = c("X", "y") |
|
30 |
#' ) |
|
31 |
#' ) |
|
32 |
#' |
|
33 |
#' ## Addition of an optional strata. |
|
34 |
#' h_coxreg_univar_formulas( |
|
35 |
#' variables = list( |
|
36 |
#' time = "time", event = "status", arm = "armcd", covariates = c("X", "y"), |
|
37 |
#' strata = "SITE" |
|
38 |
#' ) |
|
39 |
#' ) |
|
40 |
#' |
|
41 |
#' ## Inclusion of the interaction term. |
|
42 |
#' h_coxreg_univar_formulas( |
|
43 |
#' variables = list( |
|
44 |
#' time = "time", event = "status", arm = "armcd", covariates = c("X", "y"), |
|
45 |
#' strata = "SITE" |
|
46 |
#' ), |
|
47 |
#' interaction = TRUE |
|
48 |
#' ) |
|
49 |
#' |
|
50 |
#' ## Only covariates fitted in separate models. |
|
51 |
#' h_coxreg_univar_formulas( |
|
52 |
#' variables = list( |
|
53 |
#' time = "time", event = "status", covariates = c("X", "y") |
|
54 |
#' ) |
|
55 |
#' ) |
|
56 |
#' |
|
57 |
#' @export |
|
58 |
h_coxreg_univar_formulas <- function(variables, |
|
59 |
interaction = FALSE) { |
|
60 | 41x |
checkmate::assert_list(variables, names = "named") |
61 | 41x |
has_arm <- "arm" %in% names(variables) |
62 | 41x |
arm_name <- if (has_arm) "arm" else NULL |
63 | ||
64 | 41x |
checkmate::assert_character(variables$covariates, null.ok = TRUE) |
65 | ||
66 | 41x |
checkmate::assert_flag(interaction) |
67 | ||
68 | 41x |
if (!has_arm || is.null(variables$covariates)) { |
69 | 10x |
checkmate::assert_false(interaction) |
70 |
} |
|
71 | ||
72 | 39x |
assert_list_of_variables(variables[c(arm_name, "event", "time")]) |
73 | ||
74 | 39x |
if (!is.null(variables$covariates)) { |
75 | 38x |
forms <- paste0( |
76 | 38x |
"survival::Surv(", variables$time, ", ", variables$event, ") ~ ", |
77 | 38x |
ifelse(has_arm, variables$arm, "1"), |
78 | 38x |
ifelse(interaction, " * ", " + "), |
79 | 38x |
variables$covariates, |
80 | 38x |
ifelse( |
81 | 38x |
!is.null(variables$strata), |
82 | 38x |
paste0(" + strata(", paste0(variables$strata, collapse = ", "), ")"), |
83 |
"" |
|
84 |
) |
|
85 |
) |
|
86 |
} else { |
|
87 | 1x |
forms <- NULL |
88 |
} |
|
89 | 39x |
nams <- variables$covariates |
90 | 39x |
if (has_arm) { |
91 | 32x |
ref <- paste0( |
92 | 32x |
"survival::Surv(", variables$time, ", ", variables$event, ") ~ ", |
93 | 32x |
variables$arm, |
94 | 32x |
ifelse( |
95 | 32x |
!is.null(variables$strata), |
96 | 32x |
paste0( |
97 | 32x |
" + strata(", paste0(variables$strata, collapse = ", "), ")" |
98 |
), |
|
99 |
"" |
|
100 |
) |
|
101 |
) |
|
102 | 32x |
forms <- c(ref, forms) |
103 | 32x |
nams <- c("ref", nams) |
104 |
} |
|
105 | 39x |
stats::setNames(forms, nams) |
106 |
} |
|
107 | ||
108 |
#' @describeIn h_cox_regression Helper for multivariate Cox regression formula. Creates a formulas |
|
109 |
#' string. It is used internally by [fit_coxreg_multivar()] for the comparison of multivariate Cox |
|
110 |
#' regression models. Interactions will not be included in multivariate Cox regression model. |
|
111 |
#' |
|
112 |
#' @return |
|
113 |
#' * `h_coxreg_multivar_formula()` returns a `string` coercible into a formula (e.g [stats::as.formula()]). |
|
114 |
#' |
|
115 |
#' @examples |
|
116 |
#' # `h_coxreg_multivar_formula` |
|
117 |
#' |
|
118 |
#' h_coxreg_multivar_formula( |
|
119 |
#' variables = list( |
|
120 |
#' time = "AVAL", event = "event", arm = "ARMCD", covariates = c("RACE", "AGE") |
|
121 |
#' ) |
|
122 |
#' ) |
|
123 |
#' |
|
124 |
#' # Addition of an optional strata. |
|
125 |
#' h_coxreg_multivar_formula( |
|
126 |
#' variables = list( |
|
127 |
#' time = "AVAL", event = "event", arm = "ARMCD", covariates = c("RACE", "AGE"), |
|
128 |
#' strata = "SITE" |
|
129 |
#' ) |
|
130 |
#' ) |
|
131 |
#' |
|
132 |
#' # Example without treatment arm. |
|
133 |
#' h_coxreg_multivar_formula( |
|
134 |
#' variables = list( |
|
135 |
#' time = "AVAL", event = "event", covariates = c("RACE", "AGE"), |
|
136 |
#' strata = "SITE" |
|
137 |
#' ) |
|
138 |
#' ) |
|
139 |
#' |
|
140 |
#' @export |
|
141 |
h_coxreg_multivar_formula <- function(variables) { |
|
142 | 69x |
checkmate::assert_list(variables, names = "named") |
143 | 69x |
has_arm <- "arm" %in% names(variables) |
144 | 69x |
arm_name <- if (has_arm) "arm" else NULL |
145 | ||
146 | 69x |
checkmate::assert_character(variables$covariates, null.ok = TRUE) |
147 | ||
148 | 69x |
assert_list_of_variables(variables[c(arm_name, "event", "time")]) |
149 | ||
150 | 69x |
y <- paste0( |
151 | 69x |
"survival::Surv(", variables$time, ", ", variables$event, ") ~ ", |
152 | 69x |
ifelse(has_arm, variables$arm, "1") |
153 |
) |
|
154 | 69x |
if (length(variables$covariates) > 0) { |
155 | 18x |
y <- paste(y, paste(variables$covariates, collapse = " + "), sep = " + ") |
156 |
} |
|
157 | 69x |
if (!is.null(variables$strata)) { |
158 | 5x |
y <- paste0(y, " + strata(", paste0(variables$strata, collapse = ", "), ")") |
159 |
} |
|
160 | 69x |
y |
161 |
} |
|
162 | ||
163 |
#' @describeIn h_cox_regression Utility function to help tabulate the result of |
|
164 |
#' a univariate Cox regression model. |
|
165 |
#' |
|
166 |
#' @param effect (`string`)\cr the treatment variable. |
|
167 |
#' @param mod (`coxph`)\cr Cox regression model fitted by [survival::coxph()]. |
|
168 |
#' |
|
169 |
#' @return |
|
170 |
#' * `h_coxreg_univar_extract()` returns a `data.frame` with variables `effect`, `term`, `term_label`, `level`, |
|
171 |
#' `n`, `hr`, `lcl`, `ucl`, and `pval`. |
|
172 |
#' |
|
173 |
#' @examples |
|
174 |
#' library(survival) |
|
175 |
#' |
|
176 |
#' dta_simple <- data.frame( |
|
177 |
#' time = c(5, 5, 10, 10, 5, 5, 10, 10), |
|
178 |
#' status = c(0, 0, 1, 0, 0, 1, 1, 1), |
|
179 |
#' armcd = factor(LETTERS[c(1, 1, 1, 1, 2, 2, 2, 2)], levels = c("A", "B")), |
|
180 |
#' var1 = c(45, 55, 65, 75, 55, 65, 85, 75), |
|
181 |
#' var2 = c("F", "M", "F", "M", "F", "M", "F", "U") |
|
182 |
#' ) |
|
183 |
#' mod <- coxph(Surv(time, status) ~ armcd + var1, data = dta_simple) |
|
184 |
#' result <- h_coxreg_univar_extract( |
|
185 |
#' effect = "armcd", covar = "armcd", mod = mod, data = dta_simple |
|
186 |
#' ) |
|
187 |
#' result |
|
188 |
#' |
|
189 |
#' @export |
|
190 |
h_coxreg_univar_extract <- function(effect, |
|
191 |
covar, |
|
192 |
data, |
|
193 |
mod, |
|
194 |
control = control_coxreg()) { |
|
195 | 47x |
checkmate::assert_string(covar) |
196 | 47x |
checkmate::assert_string(effect) |
197 | 47x |
checkmate::assert_class(mod, "coxph") |
198 | 47x |
test_statistic <- c(wald = "Wald", likelihood = "LR")[control$pval_method] |
199 | ||
200 | 47x |
mod_aov <- muffled_car_anova(mod, test_statistic) |
201 | 47x |
msum <- summary(mod, conf.int = control$conf_level) |
202 | 47x |
sum_cox <- broom::tidy(msum) |
203 | ||
204 |
# Combine results together. |
|
205 | 47x |
effect_aov <- mod_aov[effect, , drop = TRUE] |
206 | 47x |
pval <- effect_aov[[grep(pattern = "Pr", x = names(effect_aov)), drop = TRUE]] |
207 | 47x |
sum_main <- sum_cox[grepl(effect, sum_cox$level), ] |
208 | ||
209 | 47x |
term_label <- if (effect == covar) { |
210 | 25x |
paste0( |
211 | 25x |
levels(data[[covar]])[2], |
212 | 25x |
" vs control (", |
213 | 25x |
levels(data[[covar]])[1], |
214 |
")" |
|
215 |
) |
|
216 |
} else { |
|
217 | 22x |
unname(labels_or_names(data[covar])) |
218 |
} |
|
219 | 47x |
data.frame( |
220 | 47x |
effect = ifelse(covar == effect, "Treatment:", "Covariate:"), |
221 | 47x |
term = covar, |
222 | 47x |
term_label = term_label, |
223 | 47x |
level = levels(data[[effect]])[2], |
224 | 47x |
n = mod[["n"]], |
225 | 47x |
hr = unname(sum_main["exp(coef)"]), |
226 | 47x |
lcl = unname(sum_main[grep("lower", names(sum_main))]), |
227 | 47x |
ucl = unname(sum_main[grep("upper", names(sum_main))]), |
228 | 47x |
pval = pval, |
229 | 47x |
stringsAsFactors = FALSE |
230 |
) |
|
231 |
} |
|
232 | ||
233 |
#' @describeIn h_cox_regression Tabulation of multivariate Cox regressions. Utility function to help |
|
234 |
#' tabulate the result of a multivariate Cox regression model for a treatment/covariate variable. |
|
235 |
#' |
|
236 |
#' @return |
|
237 |
#' * `h_coxreg_multivar_extract()` returns a `data.frame` with variables `pval`, `hr`, `lcl`, `ucl`, `level`, |
|
238 |
#' `n`, `term`, and `term_label`. |
|
239 |
#' |
|
240 |
#' @examples |
|
241 |
#' mod <- coxph(Surv(time, status) ~ armcd + var1, data = dta_simple) |
|
242 |
#' result <- h_coxreg_multivar_extract( |
|
243 |
#' var = "var1", mod = mod, data = dta_simple |
|
244 |
#' ) |
|
245 |
#' result |
|
246 |
#' |
|
247 |
#' @export |
|
248 |
h_coxreg_multivar_extract <- function(var, |
|
249 |
data, |
|
250 |
mod, |
|
251 |
control = control_coxreg()) { |
|
252 | 88x |
test_statistic <- c(wald = "Wald", likelihood = "LR")[control$pval_method] |
253 | 88x |
mod_aov <- muffled_car_anova(mod, test_statistic) |
254 | ||
255 | 88x |
msum <- summary(mod, conf.int = control$conf_level) |
256 | 88x |
sum_anova <- broom::tidy(mod_aov) |
257 | 88x |
sum_cox <- broom::tidy(msum) |
258 | ||
259 | 88x |
ret_anova <- sum_anova[sum_anova$term == var, c("term", "p.value")] |
260 | 88x |
names(ret_anova)[2] <- "pval" |
261 | 88x |
if (is.factor(data[[var]])) { |
262 | 29x |
ret_cox <- sum_cox[startsWith(prefix = var, x = sum_cox$level), !(names(sum_cox) %in% "exp(-coef)")] |
263 |
} else { |
|
264 | 59x |
ret_cox <- sum_cox[(var == sum_cox$level), !(names(sum_cox) %in% "exp(-coef)")] |
265 |
} |
|
266 | 88x |
names(ret_cox)[1:4] <- c("pval", "hr", "lcl", "ucl") |
267 | 88x |
varlab <- unname(labels_or_names(data[var])) |
268 | 88x |
ret_cox$term <- varlab |
269 | ||
270 | 88x |
if (is.numeric(data[[var]])) { |
271 | 59x |
ret <- ret_cox |
272 | 59x |
ret$term_label <- ret$term |
273 | 29x |
} else if (length(levels(data[[var]])) <= 2) { |
274 | 18x |
ret_anova$pval <- NA |
275 | 18x |
ret_anova$term_label <- paste0(varlab, " (reference = ", levels(data[[var]])[1], ")") |
276 | 18x |
ret_cox$level <- gsub(var, "", ret_cox$level) |
277 | 18x |
ret_cox$term_label <- ret_cox$level |
278 | 18x |
ret <- dplyr::bind_rows(ret_anova, ret_cox) |
279 |
} else { |
|
280 | 11x |
ret_anova$term_label <- paste0(varlab, " (reference = ", levels(data[[var]])[1], ")") |
281 | 11x |
ret_cox$level <- gsub(var, "", ret_cox$level) |
282 | 11x |
ret_cox$term_label <- ret_cox$level |
283 | 11x |
ret <- dplyr::bind_rows(ret_anova, ret_cox) |
284 |
} |
|
285 | ||
286 | 88x |
as.data.frame(ret) |
287 |
} |
1 |
#' Add Titles, Footnotes, Page Number, and a Bounding Box to a Grid Grob |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' This function is useful to label grid grobs (also `ggplot2`, and `lattice` plots) |
|
6 |
#' with title, footnote, and page numbers. |
|
7 |
#' |
|
8 |
#' @inheritParams grid::grob |
|
9 |
#' @param grob a grid grob object, optionally `NULL` if only a `grob` with the decoration should be shown. |
|
10 |
#' @param titles vector of character strings. Vector elements are separated by a newline and strings are wrapped |
|
11 |
#' according to the page width. |
|
12 |
#' @param footnotes vector of character string. Same rules as for `titles`. |
|
13 |
#' @param page string with page numeration, if `NULL` then no page number is displayed. |
|
14 |
#' @param width_titles unit object |
|
15 |
#' @param width_footnotes unit object |
|
16 |
#' @param border boolean, whether a a border should be drawn around the plot or not. |
|
17 |
#' @param margins unit object of length 4 |
|
18 |
#' @param padding unit object of length 4 |
|
19 |
#' @param outer_margins unit object of length 4 |
|
20 |
#' @param gp_titles a `gpar` object |
|
21 |
#' @param gp_footnotes a `gpar` object |
|
22 |
#' |
|
23 |
#' @return A grid grob (`gTree`). |
|
24 |
#' |
|
25 |
#' @details The titles and footnotes will be ragged, i.e. each title will be wrapped individually. |
|
26 |
#' |
|
27 |
#' @examples |
|
28 |
#' library(grid) |
|
29 |
#' |
|
30 |
#' titles <- c( |
|
31 |
#' "Edgar Anderson's Iris Data", |
|
32 |
#' paste( |
|
33 |
#' "This famous (Fisher's or Anderson's) iris data set gives the measurements", |
|
34 |
#' "in centimeters of the variables sepal length and width and petal length", |
|
35 |
#' "and width, respectively, for 50 flowers from each of 3 species of iris." |
|
36 |
#' ) |
|
37 |
#' ) |
|
38 |
#' |
|
39 |
#' footnotes <- c( |
|
40 |
#' "The species are Iris setosa, versicolor, and virginica.", |
|
41 |
#' paste( |
|
42 |
#' "iris is a data frame with 150 cases (rows) and 5 variables (columns) named", |
|
43 |
#' "Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, and Species." |
|
44 |
#' ) |
|
45 |
#' ) |
|
46 |
#' |
|
47 |
#' ## empty plot |
|
48 |
#' grid.newpage() |
|
49 |
#' |
|
50 |
#' grid.draw( |
|
51 |
#' decorate_grob( |
|
52 |
#' NULL, |
|
53 |
#' titles = titles, |
|
54 |
#' footnotes = footnotes, |
|
55 |
#' page = "Page 4 of 10" |
|
56 |
#' ) |
|
57 |
#' ) |
|
58 |
#' |
|
59 |
#' # grid |
|
60 |
#' p <- gTree( |
|
61 |
#' children = gList( |
|
62 |
#' rectGrob(), |
|
63 |
#' xaxisGrob(), |
|
64 |
#' yaxisGrob(), |
|
65 |
#' textGrob("Sepal.Length", y = unit(-4, "lines")), |
|
66 |
#' textGrob("Petal.Length", x = unit(-3.5, "lines"), rot = 90), |
|
67 |
#' pointsGrob(iris$Sepal.Length, iris$Petal.Length, gp = gpar(col = iris$Species), pch = 16) |
|
68 |
#' ), |
|
69 |
#' vp = vpStack(plotViewport(), dataViewport(xData = iris$Sepal.Length, yData = iris$Petal.Length)) |
|
70 |
#' ) |
|
71 |
#' grid.newpage() |
|
72 |
#' grid.draw(p) |
|
73 |
#' |
|
74 |
#' grid.newpage() |
|
75 |
#' grid.draw( |
|
76 |
#' decorate_grob( |
|
77 |
#' grob = p, |
|
78 |
#' titles = titles, |
|
79 |
#' footnotes = footnotes, |
|
80 |
#' page = "Page 6 of 129" |
|
81 |
#' ) |
|
82 |
#' ) |
|
83 |
#' |
|
84 |
#' ## with ggplot2 |
|
85 |
#' library(ggplot2) |
|
86 |
#' |
|
87 |
#' p_gg <- ggplot2::ggplot(iris, aes(Sepal.Length, Sepal.Width, col = Species)) + |
|
88 |
#' ggplot2::geom_point() |
|
89 |
#' p_gg |
|
90 |
#' p <- ggplotGrob(p_gg) |
|
91 |
#' grid.newpage() |
|
92 |
#' grid.draw( |
|
93 |
#' decorate_grob( |
|
94 |
#' grob = p, |
|
95 |
#' titles = titles, |
|
96 |
#' footnotes = footnotes, |
|
97 |
#' page = "Page 6 of 129" |
|
98 |
#' ) |
|
99 |
#' ) |
|
100 |
#' |
|
101 |
#' ## with lattice |
|
102 |
#' library(lattice) |
|
103 |
#' |
|
104 |
#' xyplot(Sepal.Length ~ Petal.Length, data = iris, col = iris$Species) |
|
105 |
#' p <- grid.grab() |
|
106 |
#' grid.newpage() |
|
107 |
#' grid.draw( |
|
108 |
#' decorate_grob( |
|
109 |
#' grob = p, |
|
110 |
#' titles = titles, |
|
111 |
#' footnotes = footnotes, |
|
112 |
#' page = "Page 6 of 129" |
|
113 |
#' ) |
|
114 |
#' ) |
|
115 |
#' |
|
116 |
#' # with gridExtra - no borders |
|
117 |
#' library(gridExtra) |
|
118 |
#' grid.newpage() |
|
119 |
#' grid.draw( |
|
120 |
#' decorate_grob( |
|
121 |
#' tableGrob( |
|
122 |
#' head(mtcars) |
|
123 |
#' ), |
|
124 |
#' titles = "title", |
|
125 |
#' footnotes = "footnote", |
|
126 |
#' border = FALSE |
|
127 |
#' ) |
|
128 |
#' ) |
|
129 |
#' |
|
130 |
#' @export |
|
131 |
decorate_grob <- function(grob, |
|
132 |
titles, |
|
133 |
footnotes, |
|
134 |
page = "", |
|
135 |
width_titles = grid::unit(1, "npc") - grid::unit(1.5, "cm"), |
|
136 |
width_footnotes = grid::unit(1, "npc") - grid::unit(1.5, "cm"), |
|
137 |
border = TRUE, |
|
138 |
margins = grid::unit(c(1, 0, 1, 0), "lines"), |
|
139 |
padding = grid::unit(rep(1, 4), "lines"), |
|
140 |
outer_margins = grid::unit(c(2, 1.5, 3, 1.5), "cm"), |
|
141 |
gp_titles = grid::gpar(), |
|
142 |
gp_footnotes = grid::gpar(fontsize = 8), |
|
143 |
name = NULL, |
|
144 |
gp = grid::gpar(), |
|
145 |
vp = NULL) { |
|
146 | 9x |
st_titles <- split_text_grob( |
147 | 9x |
titles, |
148 | 9x |
x = 0, y = 1, |
149 | 9x |
just = c("left", "top"), |
150 | 9x |
width = width_titles, |
151 | 9x |
vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1), |
152 | 9x |
gp = gp_titles |
153 |
) |
|
154 | ||
155 | 9x |
st_footnotes <- split_text_grob( |
156 | 9x |
footnotes, |
157 | 9x |
x = 0, y = 1, |
158 | 9x |
just = c("left", "top"), |
159 | 9x |
width = width_footnotes, |
160 | 9x |
vp = grid::viewport(layout.pos.row = 3, layout.pos.col = 1), |
161 | 9x |
gp = gp_footnotes |
162 |
) |
|
163 | ||
164 | 9x |
pg_footnote <- grid::textGrob( |
165 | 9x |
paste("\n", page), |
166 | 9x |
x = 1, y = 0, |
167 | 9x |
just = c("right", "bottom"), |
168 | 9x |
vp = grid::viewport(layout.pos.row = 4, layout.pos.col = 1), |
169 | 9x |
gp = gp_footnotes |
170 |
) |
|
171 | ||
172 | 9x |
grid::gTree( |
173 | 9x |
grob = grob, |
174 | 9x |
titles = titles, |
175 | 9x |
footnotes = footnotes, |
176 | 9x |
page = page, |
177 | 9x |
width_titles = width_titles, |
178 | 9x |
width_footnotes = width_footnotes, |
179 | 9x |
border = border, |
180 | 9x |
margins = margins, |
181 | 9x |
padding = padding, |
182 | 9x |
outer_margins = outer_margins, |
183 | 9x |
gp_titles = gp_titles, |
184 | 9x |
gp_footnotes = gp_footnotes, |
185 | 9x |
children = grid::gList( |
186 | 9x |
grid::gTree( |
187 | 9x |
children = grid::gList( |
188 | 9x |
st_titles, |
189 | 9x |
grid::gTree( |
190 | 9x |
children = grid::gList( |
191 | 9x |
if (border) grid::rectGrob(), |
192 | 9x |
grid::gTree( |
193 | 9x |
children = grid::gList( |
194 | 9x |
grob |
195 |
), |
|
196 | 9x |
vp = grid::plotViewport(margins = padding) |
197 |
) |
|
198 |
), |
|
199 | 9x |
vp = grid::vpStack( |
200 | 9x |
grid::viewport(layout.pos.row = 2, layout.pos.col = 1), |
201 | 9x |
grid::plotViewport(margins = margins) |
202 |
) |
|
203 |
), |
|
204 | 9x |
st_footnotes, |
205 | 9x |
pg_footnote |
206 |
), |
|
207 | 9x |
childrenvp = NULL, |
208 | 9x |
name = "titles_grob_footnotes", |
209 | 9x |
vp = grid::vpStack( |
210 | 9x |
grid::plotViewport(margins = outer_margins), |
211 | 9x |
grid::viewport( |
212 | 9x |
layout = grid::grid.layout( |
213 | 9x |
nrow = 4, ncol = 1, |
214 | 9x |
heights = grid::unit.c( |
215 | 9x |
grid::grobHeight(st_titles), |
216 | 9x |
grid::unit(1, "null"), |
217 | 9x |
grid::grobHeight(st_footnotes), |
218 | 9x |
grid::grobHeight(pg_footnote) |
219 |
) |
|
220 |
) |
|
221 |
) |
|
222 |
) |
|
223 |
) |
|
224 |
), |
|
225 | 9x |
name = name, |
226 | 9x |
gp = gp, |
227 | 9x |
vp = vp, |
228 | 9x |
cl = "decoratedGrob" |
229 |
) |
|
230 |
} |
|
231 | ||
232 |
#' @importFrom grid validDetails |
|
233 |
#' @noRd |
|
234 |
validDetails.decoratedGrob <- function(x) { |
|
235 | ! |
checkmate::assert_character(x$titles) |
236 | ! |
checkmate::assert_character(x$footnotes) |
237 | ||
238 | ! |
if (!is.null(x$grob)) { |
239 | ! |
checkmate::assert_true(grid::is.grob(x$grob)) |
240 |
} |
|
241 | ! |
if (length(x$page) == 1) { |
242 | ! |
checkmate::assert_character(x$page) |
243 |
} |
|
244 | ! |
if (!grid::is.unit(x$outer_margins)) { |
245 | ! |
checkmate::assert_vector(x$outer_margins, len = 4) |
246 |
} |
|
247 | ! |
if (!grid::is.unit(x$margins)) { |
248 | ! |
checkmate::assert_vector(x$margins, len = 4) |
249 |
} |
|
250 | ! |
if (!grid::is.unit(x$padding)) { |
251 | ! |
checkmate::assert_vector(x$padding, len = 4) |
252 |
} |
|
253 | ||
254 | ! |
x |
255 |
} |
|
256 | ||
257 |
#' @importFrom grid widthDetails |
|
258 |
#' @noRd |
|
259 |
widthDetails.decoratedGrob <- function(x) { |
|
260 | ! |
grid::unit(1, "null") |
261 |
} |
|
262 | ||
263 |
#' @importFrom grid heightDetails |
|
264 |
#' @noRd |
|
265 |
heightDetails.decoratedGrob <- function(x) { |
|
266 | ! |
grid::unit(1, "null") |
267 |
} |
|
268 | ||
269 |
# Adapted from Paul Murell R Graphics 2nd Edition |
|
270 |
# https://www.stat.auckland.ac.nz/~paul/RG2e/interactgrid-splittext.R |
|
271 |
split_string <- function(text, width) { |
|
272 | 19x |
strings <- strsplit(text, " ") |
273 | 19x |
out_string <- NA |
274 | 19x |
for (string_i in seq_along(strings)) { |
275 | 19x |
newline_str <- strings[[string_i]] |
276 | 6x |
if (length(newline_str) == 0) newline_str <- "" |
277 | 19x |
if (is.na(out_string[string_i])) { |
278 | 19x |
out_string[string_i] <- newline_str[[1]][[1]] |
279 | 19x |
linewidth <- grid::stringWidth(out_string[string_i]) |
280 |
} |
|
281 | 19x |
gapwidth <- grid::stringWidth(" ") |
282 | 19x |
availwidth <- as.numeric(width) |
283 | 19x |
if (length(newline_str) > 1) { |
284 | 7x |
for (i in seq(2, length(newline_str))) { |
285 | 83x |
width_i <- grid::stringWidth(newline_str[i]) |
286 | 83x |
if (grid::convertWidth(linewidth + gapwidth + width_i, grid::unitType(width), valueOnly = TRUE) < availwidth) { |
287 | 78x |
sep <- " " |
288 | 78x |
linewidth <- linewidth + gapwidth + width_i |
289 |
} else { |
|
290 | 5x |
sep <- "\n" |
291 | 5x |
linewidth <- width_i |
292 |
} |
|
293 | 83x |
out_string[string_i] <- paste(out_string[string_i], newline_str[i], sep = sep) |
294 |
} |
|
295 |
} |
|
296 |
} |
|
297 | 19x |
paste(out_string, collapse = "\n") |
298 |
} |
|
299 | ||
300 |
#' Split Text According To Available Text Width |
|
301 |
#' |
|
302 |
#' Dynamically wrap text. |
|
303 |
#' |
|
304 |
#' @inheritParams grid::grid.text |
|
305 |
#' @param text character string |
|
306 |
#' @param width a unit object specifying max width of text |
|
307 |
#' |
|
308 |
#' @return A text grob. |
|
309 |
#' |
|
310 |
#' @details This code is taken from `R Graphics by Paul Murell, 2nd edition` |
|
311 |
#' |
|
312 |
#' @keywords internal |
|
313 |
split_text_grob <- function(text, |
|
314 |
x = grid::unit(0.5, "npc"), |
|
315 |
y = grid::unit(0.5, "npc"), |
|
316 |
width = grid::unit(1, "npc"), |
|
317 |
just = "centre", |
|
318 |
hjust = NULL, |
|
319 |
vjust = NULL, |
|
320 |
default.units = "npc", # nolint |
|
321 |
name = NULL, |
|
322 |
gp = grid::gpar(), |
|
323 |
vp = NULL) { |
|
324 | 18x |
if (!grid::is.unit(x)) x <- grid::unit(x, default.units) |
325 | 18x |
if (!grid::is.unit(y)) y <- grid::unit(y, default.units) |
326 | ! |
if (!grid::is.unit(width)) width <- grid::unit(width, default.units) |
327 | ! |
if (grid::unitType(x) %in% c("sum", "min", "max")) x <- grid::convertUnit(x, default.units) |
328 | ! |
if (grid::unitType(y) %in% c("sum", "min", "max")) y <- grid::convertUnit(y, default.units) |
329 | 18x |
if (grid::unitType(width) %in% c("sum", "min", "max")) width <- grid::convertUnit(width, default.units) |
330 | ||
331 | 18x |
if (length(gp) > 0) { # account for effect of gp on text width |
332 | 9x |
width <- width * grid::convertWidth(grid::grobWidth(grid::textGrob(text)), "npc", valueOnly = TRUE) / |
333 | 9x |
grid::convertWidth(grid::grobWidth(grid::textGrob(text, gp = gp)), "npc", valueOnly = TRUE) |
334 |
} |
|
335 | ||
336 |
## if it is a fixed unit then we do not need to recalculate when viewport resized |
|
337 | 18x |
if (!inherits(width, "unit.arithmetic") && !is.null(attr(width, "unit")) && |
338 | 18x |
attr(width, "unit") %in% c("cm", "inches", "mm", "points", "picas", "bigpts", "dida", "cicero", "scaledpts")) { # nolint |
339 | ! |
attr(text, "fixed_text") <- paste(vapply(text, split_string, character(1), width = width), collapse = "\n") |
340 |
} |
|
341 | ||
342 | 18x |
grid::grid.text( |
343 | 18x |
label = split_string(text, width), |
344 | 18x |
x = x, y = y, |
345 | 18x |
just = just, |
346 | 18x |
hjust = hjust, |
347 | 18x |
vjust = vjust, |
348 | 18x |
rot = 0, |
349 | 18x |
check.overlap = FALSE, |
350 | 18x |
name = name, |
351 | 18x |
gp = gp, |
352 | 18x |
vp = vp, |
353 | 18x |
draw = FALSE |
354 |
) |
|
355 |
} |
|
356 | ||
357 |
#' @importFrom grid validDetails |
|
358 |
#' @noRd |
|
359 |
validDetails.dynamicSplitText <- function(x) { |
|
360 | ! |
checkmate::assert_character(x$text) |
361 | ! |
checkmate::assert_true(grid::is.unit(x$width)) |
362 | ! |
checkmate::assert_vector(x$width, len = 1) |
363 | ! |
x |
364 |
} |
|
365 | ||
366 |
#' @importFrom grid heightDetails |
|
367 |
#' @noRd |
|
368 |
heightDetails.dynamicSplitText <- function(x) { |
|
369 | ! |
txt <- if (!is.null(attr(x$text, "fixed_text"))) { |
370 | ! |
attr(x$text, "fixed_text") |
371 |
} else { |
|
372 | ! |
paste(vapply(x$text, split_string, character(1), width = x$width), collapse = "\n") |
373 |
} |
|
374 | ! |
grid::stringHeight(txt) |
375 |
} |
|
376 | ||
377 |
#' @importFrom grid widthDetails |
|
378 |
#' @noRd |
|
379 |
widthDetails.dynamicSplitText <- function(x) { |
|
380 | ! |
x$width |
381 |
} |
|
382 | ||
383 |
#' @importFrom grid drawDetails |
|
384 |
#' @noRd |
|
385 |
drawDetails.dynamicSplitText <- function(x, recording) { |
|
386 | ! |
txt <- if (!is.null(attr(x$text, "fixed_text"))) { |
387 | ! |
attr(x$text, "fixed_text") |
388 |
} else { |
|
389 | ! |
paste(vapply(x$text, split_string, character(1), width = x$width), collapse = "\n") |
390 |
} |
|
391 | ||
392 | ! |
x$width <- NULL |
393 | ! |
x$label <- txt |
394 | ! |
x$text <- NULL |
395 | ! |
class(x) <- c("text", class(x)[-1]) |
396 | ||
397 | ! |
grid::grid.draw(x) |
398 |
} |
|
399 | ||
400 |
#' Update Page Number |
|
401 |
#' |
|
402 |
#' Automatically updates page number. |
|
403 |
#' |
|
404 |
#' @param npages number of pages in total |
|
405 |
#' @param ... passed on to [decorate_grob()] |
|
406 |
#' |
|
407 |
#' @return Closure that increments the page number. |
|
408 |
#' |
|
409 |
#' @keywords internal |
|
410 |
decorate_grob_factory <- function(npages, ...) { |
|
411 | 2x |
current_page <- 0 |
412 | 2x |
function(grob) { |
413 | 7x |
current_page <<- current_page + 1 |
414 | 7x |
if (current_page > npages) { |
415 | 1x |
stop(paste("current page is", current_page, "but max.", npages, "specified.")) |
416 |
} |
|
417 | 6x |
decorate_grob(grob = grob, page = paste("Page", current_page, "of", npages), ...) |
418 |
} |
|
419 |
} |
|
420 | ||
421 |
#' Decorate Set of `grobs` and Add Page Numbering |
|
422 |
#' |
|
423 |
#' @description `r lifecycle::badge("stable")` |
|
424 |
#' |
|
425 |
#' Note that this uses the [decorate_grob_factory()] function. |
|
426 |
#' |
|
427 |
#' @param grobs a list of grid grobs |
|
428 |
#' @param ... arguments passed on to [decorate_grob()]. |
|
429 |
#' |
|
430 |
#' @return A decorated grob. |
|
431 |
#' |
|
432 |
#' @examples |
|
433 |
#' library(ggplot2) |
|
434 |
#' library(grid) |
|
435 |
#' g <- with(data = iris, { |
|
436 |
#' list( |
|
437 |
#' ggplot2::ggplotGrob( |
|
438 |
#' ggplot2::ggplot(mapping = aes(Sepal.Length, Sepal.Width, col = Species)) + |
|
439 |
#' ggplot2::geom_point() |
|
440 |
#' ), |
|
441 |
#' ggplot2::ggplotGrob( |
|
442 |
#' ggplot2::ggplot(mapping = aes(Sepal.Length, Petal.Length, col = Species)) + |
|
443 |
#' ggplot2::geom_point() |
|
444 |
#' ), |
|
445 |
#' ggplot2::ggplotGrob( |
|
446 |
#' ggplot2::ggplot(mapping = aes(Sepal.Length, Petal.Width, col = Species)) + |
|
447 |
#' ggplot2::geom_point() |
|
448 |
#' ), |
|
449 |
#' ggplot2::ggplotGrob( |
|
450 |
#' ggplot2::ggplot(mapping = aes(Sepal.Width, Petal.Length, col = Species)) + |
|
451 |
#' ggplot2::geom_point() |
|
452 |
#' ), |
|
453 |
#' ggplot2::ggplotGrob( |
|
454 |
#' ggplot2::ggplot(mapping = aes(Sepal.Width, Petal.Width, col = Species)) + |
|
455 |
#' ggplot2::geom_point() |
|
456 |
#' ), |
|
457 |
#' ggplot2::ggplotGrob( |
|
458 |
#' ggplot2::ggplot(mapping = aes(Petal.Length, Petal.Width, col = Species)) + |
|
459 |
#' ggplot2::geom_point() |
|
460 |
#' ) |
|
461 |
#' ) |
|
462 |
#' }) |
|
463 |
#' lg <- decorate_grob_set(grobs = g, titles = "Hello\nOne\nTwo\nThree", footnotes = "") |
|
464 |
#' |
|
465 |
#' draw_grob(lg[[1]]) |
|
466 |
#' draw_grob(lg[[2]]) |
|
467 |
#' draw_grob(lg[[6]]) |
|
468 |
#' |
|
469 |
#' @export |
|
470 |
decorate_grob_set <- function(grobs, ...) { |
|
471 | 1x |
n <- length(grobs) |
472 | 1x |
lgf <- decorate_grob_factory(npages = n, ...) |
473 | 1x |
lapply(grobs, lgf) |
474 |
} |
1 |
#' Tabulate Biomarker Effects on Survival by Subgroup |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Tabulate the estimated effects of multiple continuous biomarker variables |
|
6 |
#' across population subgroups. |
|
7 |
#' |
|
8 |
#' @inheritParams fit_coxreg_multivar |
|
9 |
#' @inheritParams survival_duration_subgroups |
|
10 |
#' @inheritParams argument_convention |
|
11 |
#' @param df (`data.frame`)\cr containing all analysis variables, as returned by |
|
12 |
#' [extract_survival_biomarkers()]. |
|
13 |
#' @param vars (`character`)\cr the names of statistics to be reported among: |
|
14 |
#' * `n_tot_events`: Total number of events per group. |
|
15 |
#' * `n_tot`: Total number of observations per group. |
|
16 |
#' * `median`: Median survival time. |
|
17 |
#' * `hr`: Hazard ratio. |
|
18 |
#' * `ci`: Confidence interval of hazard ratio. |
|
19 |
#' * `pval`: p-value of the effect. |
|
20 |
#' Note, one of the statistics `n_tot` and `n_tot_events`, as well as both `hr` and `ci` are required. |
|
21 |
#' |
|
22 |
#' @details These functions create a layout starting from a data frame which contains |
|
23 |
#' the required statistics. The tables are then typically used as input for forest plots. |
|
24 |
#' |
|
25 |
#' @examples |
|
26 |
#' library(dplyr) |
|
27 |
#' |
|
28 |
#' adtte <- tern_ex_adtte |
|
29 |
#' |
|
30 |
#' # Save variable labels before data processing steps. |
|
31 |
#' adtte_labels <- formatters::var_labels(adtte) |
|
32 |
#' |
|
33 |
#' adtte_f <- adtte %>% |
|
34 |
#' filter(PARAMCD == "OS") %>% |
|
35 |
#' mutate( |
|
36 |
#' AVALU = as.character(AVALU), |
|
37 |
#' is_event = CNSR == 0 |
|
38 |
#' ) |
|
39 |
#' labels <- c("AVALU" = adtte_labels[["AVALU"]], "is_event" = "Event Flag") |
|
40 |
#' formatters::var_labels(adtte_f)[names(labels)] <- labels |
|
41 |
#' |
|
42 |
#' # Typical analysis of two continuous biomarkers `BMRKR1` and `AGE`, |
|
43 |
#' # in multiple regression models containing one covariate `RACE`, |
|
44 |
#' # as well as one stratification variable `STRATA1`. The subgroups |
|
45 |
#' # are defined by the levels of `BMRKR2`. |
|
46 |
#' |
|
47 |
#' df <- extract_survival_biomarkers( |
|
48 |
#' variables = list( |
|
49 |
#' tte = "AVAL", |
|
50 |
#' is_event = "is_event", |
|
51 |
#' biomarkers = c("BMRKR1", "AGE"), |
|
52 |
#' strata = "STRATA1", |
|
53 |
#' covariates = "SEX", |
|
54 |
#' subgroups = "BMRKR2" |
|
55 |
#' ), |
|
56 |
#' data = adtte_f |
|
57 |
#' ) |
|
58 |
#' df |
|
59 |
#' |
|
60 |
#' # Here we group the levels of `BMRKR2` manually. |
|
61 |
#' df_grouped <- extract_survival_biomarkers( |
|
62 |
#' variables = list( |
|
63 |
#' tte = "AVAL", |
|
64 |
#' is_event = "is_event", |
|
65 |
#' biomarkers = c("BMRKR1", "AGE"), |
|
66 |
#' strata = "STRATA1", |
|
67 |
#' covariates = "SEX", |
|
68 |
#' subgroups = "BMRKR2" |
|
69 |
#' ), |
|
70 |
#' data = adtte_f, |
|
71 |
#' groups_lists = list( |
|
72 |
#' BMRKR2 = list( |
|
73 |
#' "low" = "LOW", |
|
74 |
#' "low/medium" = c("LOW", "MEDIUM"), |
|
75 |
#' "low/medium/high" = c("LOW", "MEDIUM", "HIGH") |
|
76 |
#' ) |
|
77 |
#' ) |
|
78 |
#' ) |
|
79 |
#' df_grouped |
|
80 |
#' |
|
81 |
#' @name survival_biomarkers_subgroups |
|
82 |
#' @order 1 |
|
83 |
NULL |
|
84 | ||
85 |
#' Prepares Survival Data Estimates for Multiple Biomarkers in a Single Data Frame |
|
86 |
#' |
|
87 |
#' @description `r lifecycle::badge("stable")` |
|
88 |
#' |
|
89 |
#' Prepares estimates for number of events, patients and median survival times, as well as hazard ratio estimates, |
|
90 |
#' confidence intervals and p-values, for multiple biomarkers across population subgroups in a single data frame. |
|
91 |
#' `variables` corresponds to the names of variables found in `data`, passed as a named `list` and requires elements |
|
92 |
#' `tte`, `is_event`, `biomarkers` (vector of continuous biomarker variables), and optionally `subgroups` and `strat`. |
|
93 |
#' `groups_lists` optionally specifies groupings for `subgroups` variables. |
|
94 |
#' |
|
95 |
#' @inheritParams argument_convention |
|
96 |
#' @inheritParams fit_coxreg_multivar |
|
97 |
#' @inheritParams survival_duration_subgroups |
|
98 |
#' |
|
99 |
#' @return A `data.frame` with columns `biomarker`, `biomarker_label`, `n_tot`, `n_tot_events`, |
|
100 |
#' `median`, `hr`, `lcl`, `ucl`, `conf_level`, `pval`, `pval_label`, `subgroup`, `var`, |
|
101 |
#' `var_label`, and `row_type`. |
|
102 |
#' |
|
103 |
#' @seealso [h_coxreg_mult_cont_df()] which is used internally, [tabulate_survival_biomarkers()]. |
|
104 |
#' |
|
105 |
#' @export |
|
106 |
extract_survival_biomarkers <- function(variables, |
|
107 |
data, |
|
108 |
groups_lists = list(), |
|
109 |
control = control_coxreg(), |
|
110 |
label_all = "All Patients") { |
|
111 | 5x |
checkmate::assert_list(variables) |
112 | 5x |
checkmate::assert_character(variables$subgroups, null.ok = TRUE) |
113 | 5x |
checkmate::assert_string(label_all) |
114 | ||
115 |
# Start with all patients. |
|
116 | 5x |
result_all <- h_coxreg_mult_cont_df( |
117 | 5x |
variables = variables, |
118 | 5x |
data = data, |
119 | 5x |
control = control |
120 |
) |
|
121 | 5x |
result_all$subgroup <- label_all |
122 | 5x |
result_all$var <- "ALL" |
123 | 5x |
result_all$var_label <- label_all |
124 | 5x |
result_all$row_type <- "content" |
125 | 5x |
if (is.null(variables$subgroups)) { |
126 |
# Only return result for all patients. |
|
127 | 1x |
result_all |
128 |
} else { |
|
129 |
# Add subgroups results. |
|
130 | 4x |
l_data <- h_split_by_subgroups( |
131 | 4x |
data, |
132 | 4x |
variables$subgroups, |
133 | 4x |
groups_lists = groups_lists |
134 |
) |
|
135 | 4x |
l_result <- lapply(l_data, function(grp) { |
136 | 20x |
result <- h_coxreg_mult_cont_df( |
137 | 20x |
variables = variables, |
138 | 20x |
data = grp$df, |
139 | 20x |
control = control |
140 |
) |
|
141 | 20x |
result_labels <- grp$df_labels[rep(1, times = nrow(result)), ] |
142 | 20x |
cbind(result, result_labels) |
143 |
}) |
|
144 | 4x |
result_subgroups <- do.call(rbind, args = c(l_result, make.row.names = FALSE)) |
145 | 4x |
result_subgroups$row_type <- "analysis" |
146 | 4x |
rbind( |
147 | 4x |
result_all, |
148 | 4x |
result_subgroups |
149 |
) |
|
150 |
} |
|
151 |
} |
|
152 | ||
153 |
#' @describeIn survival_biomarkers_subgroups Table-creating function which creates a table |
|
154 |
#' summarizing biomarker effects on survival by subgroup. |
|
155 |
#' |
|
156 |
#' @return An `rtables` table summarizing biomarker effects on survival by subgroup. |
|
157 |
#' |
|
158 |
#' @note In contrast to [tabulate_survival_subgroups()] this tabulation function does |
|
159 |
#' not start from an input layout `lyt`. This is because internally the table is |
|
160 |
#' created by combining multiple subtables. |
|
161 |
#' |
|
162 |
#' @seealso [h_tab_surv_one_biomarker()] which is used internally, [extract_survival_biomarkers()]. |
|
163 |
#' |
|
164 |
#' @examples |
|
165 |
#' ## Table with default columns. |
|
166 |
#' tabulate_survival_biomarkers(df) |
|
167 |
#' |
|
168 |
#' ## Table with a manually chosen set of columns: leave out "pval", reorder. |
|
169 |
#' tab <- tabulate_survival_biomarkers( |
|
170 |
#' df = df, |
|
171 |
#' vars = c("n_tot_events", "ci", "n_tot", "median", "hr"), |
|
172 |
#' time_unit = as.character(adtte_f$AVALU[1]) |
|
173 |
#' ) |
|
174 |
#' |
|
175 |
#' ## Finally produce the forest plot. |
|
176 |
#' \donttest{ |
|
177 |
#' g_forest(tab, xlim = c(0.8, 1.2)) |
|
178 |
#' } |
|
179 |
#' |
|
180 |
#' @export |
|
181 |
#' @order 2 |
|
182 |
tabulate_survival_biomarkers <- function(df, |
|
183 |
vars = c("n_tot", "n_tot_events", "median", "hr", "ci", "pval"), |
|
184 |
groups_lists = list(), |
|
185 |
control = control_coxreg(), |
|
186 |
label_all = "All Patients", |
|
187 |
time_unit = NULL, |
|
188 |
na_str = default_na_str(), |
|
189 |
.indent_mods = 0L) { |
|
190 | 4x |
checkmate::assert_data_frame(df) |
191 | 4x |
checkmate::assert_character(df$biomarker) |
192 | 4x |
checkmate::assert_character(df$biomarker_label) |
193 | 4x |
checkmate::assert_subset(vars, get_stats("tabulate_survival_biomarkers")) |
194 | ||
195 | 4x |
extra_args <- list(groups_lists = groups_lists, control = control, label_all = label_all) |
196 | ||
197 | 4x |
df_subs <- split(df, f = df$biomarker) |
198 | 4x |
tabs <- lapply(df_subs, FUN = function(df_sub) { |
199 | 7x |
tab_sub <- h_tab_surv_one_biomarker( |
200 | 7x |
df = df_sub, |
201 | 7x |
vars = vars, |
202 | 7x |
time_unit = time_unit, |
203 | 7x |
na_str = na_str, |
204 | 7x |
.indent_mods = .indent_mods, |
205 | 7x |
extra_args = extra_args |
206 |
) |
|
207 |
# Insert label row as first row in table. |
|
208 | 7x |
label_at_path(tab_sub, path = row_paths(tab_sub)[[1]][1]) <- df_sub$biomarker_label[1] |
209 | 7x |
tab_sub |
210 |
}) |
|
211 | 4x |
result <- do.call(rbind, tabs) |
212 | ||
213 | 4x |
n_tot_ids <- grep("^n_tot", vars) |
214 | 4x |
hr_id <- match("hr", vars) |
215 | 4x |
ci_id <- match("ci", vars) |
216 | 4x |
structure( |
217 | 4x |
result, |
218 | 4x |
forest_header = paste0(c("Higher", "Lower"), "\nBetter"), |
219 | 4x |
col_x = hr_id, |
220 | 4x |
col_ci = ci_id, |
221 | 4x |
col_symbol_size = n_tot_ids[1] |
222 |
) |
|
223 |
} |
1 |
#' Convert `rtable` object to `ggplot` object |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("experimental")` |
|
4 |
#' |
|
5 |
#' Given a [rtables::rtable()] object, performs basic conversion to a [ggplot2::ggplot()] object built using |
|
6 |
#' functions from the `ggplot2` package. Any table titles and/or footnotes are ignored. |
|
7 |
#' |
|
8 |
#' @param tbl (`rtable`)\cr a `rtable` object. |
|
9 |
#' @param fontsize (`numeric`)\cr font size. |
|
10 |
#' @param colwidths (`vector` of `numeric`)\cr a vector of column widths. Each element's position in |
|
11 |
#' `colwidths` corresponds to the column of `tbl` in the same position. If `NULL`, column widths |
|
12 |
#' are calculated according to maximum number of characters per column. |
|
13 |
#' @param lbl_col_padding (`numeric`)\cr additional padding to use when calculating spacing between |
|
14 |
#' the first (label) column and the second column of `tbl`. If `colwidths` is specified, |
|
15 |
#' the width of the first column becomes `colwidths[1] + lbl_col_padding`. Defaults to 0. |
|
16 |
#' |
|
17 |
#' @return a `ggplot` object. |
|
18 |
#' |
|
19 |
#' @examples |
|
20 |
#' dta <- data.frame( |
|
21 |
#' ARM = rep(LETTERS[1:3], rep(6, 3)), |
|
22 |
#' AVISIT = rep(paste0("V", 1:3), 6), |
|
23 |
#' AVAL = c(9:1, rep(NA, 9)) |
|
24 |
#' ) |
|
25 |
#' |
|
26 |
#' lyt <- basic_table() %>% |
|
27 |
#' split_cols_by(var = "ARM") %>% |
|
28 |
#' split_rows_by(var = "AVISIT") %>% |
|
29 |
#' analyze_vars(vars = "AVAL") |
|
30 |
#' |
|
31 |
#' tbl <- build_table(lyt, df = dta) |
|
32 |
#' |
|
33 |
#' rtable2gg(tbl) |
|
34 |
#' |
|
35 |
#' rtable2gg(tbl, fontsize = 5, colwidths = c(2, 1, 1, 1)) |
|
36 |
#' |
|
37 |
#' @export |
|
38 |
rtable2gg <- function(tbl, fontsize = 4, colwidths = NULL, lbl_col_padding = 0) { |
|
39 | ! |
mat <- rtables::matrix_form(tbl) |
40 | ! |
mat_strings <- formatters::mf_strings(mat) |
41 | ! |
mat_aligns <- formatters::mf_aligns(mat) |
42 | ! |
mat_indent <- formatters::mf_rinfo(mat)$indent |
43 | ! |
mat_display <- formatters::mf_display(mat) |
44 | ! |
nlines_hdr <- formatters::mf_nlheader(mat) |
45 | ! |
shared_hdr_rows <- which(apply(mat_display, 1, function(x) (any(!x)))) |
46 | ||
47 | ! |
tbl_df <- data.frame(mat_strings) |
48 | ! |
body_rows <- seq(nlines_hdr + 1, nrow(tbl_df)) |
49 | ! |
mat_aligns <- apply(mat_aligns, 1:2, function(x) if (x == "left") 0 else if (x == "right") 1 else 0.5) |
50 | ||
51 |
# Apply indentation in first column |
|
52 | ! |
tbl_df[body_rows, 1] <- sapply(body_rows, function(i) { |
53 | ! |
ind_i <- mat_indent[i - nlines_hdr] * 4 |
54 | ! |
if (ind_i > 0) paste0(paste(rep(" ", ind_i), collapse = ""), tbl_df[i, 1]) else tbl_df[i, 1] |
55 |
}) |
|
56 | ||
57 |
# Get column widths |
|
58 | ! |
if (is.null(colwidths)) { |
59 | ! |
colwidths <- apply(tbl_df, 2, function(x) max(nchar(x))) + 1 |
60 |
} |
|
61 | ! |
tot_width <- sum(colwidths) + lbl_col_padding |
62 | ||
63 | ! |
if (length(shared_hdr_rows) > 0) { |
64 | ! |
tbl_df <- tbl_df[-shared_hdr_rows, ] |
65 | ! |
mat_aligns <- mat_aligns[-shared_hdr_rows, ] |
66 |
} |
|
67 | ||
68 | ! |
res <- ggplot(data = tbl_df) + |
69 | ! |
theme_void() + |
70 | ! |
scale_x_continuous(limits = c(0, tot_width)) + |
71 | ! |
scale_y_continuous(limits = c(0, nrow(mat_strings))) + |
72 | ! |
geom_segment(aes( |
73 | ! |
x = 0, xend = tot_width, |
74 | ! |
y = nrow(mat_strings) - nlines_hdr + 0.5, yend = nrow(mat_strings) - nlines_hdr + 0.5 |
75 |
)) |
|
76 | ||
77 |
# If header content spans multiple columns, center over these columns |
|
78 | ! |
if (length(shared_hdr_rows) > 0) { |
79 | ! |
mat_strings[shared_hdr_rows, ] <- trimws(mat_strings[shared_hdr_rows, ]) |
80 | ! |
for (hr in shared_hdr_rows) { |
81 | ! |
hdr_lbls <- mat_strings[1:hr, mat_display[hr, -1]] |
82 | ! |
hdr_lbls <- matrix(hdr_lbls[nzchar(hdr_lbls)], nrow = hr) |
83 | ! |
for (idx_hl in seq_len(ncol(hdr_lbls))) { |
84 | ! |
cur_lbl <- tail(hdr_lbls[, idx_hl], 1) |
85 | ! |
which_cols <- if (hr == 1) { |
86 | ! |
which(mat_strings[hr, ] == hdr_lbls[idx_hl]) |
87 | ! |
} else { # for >2 col splits, only print labels for each unique combo of nested columns |
88 | ! |
which( |
89 | ! |
apply(mat_strings[1:hr, ], 2, function(x) all(x == hdr_lbls[1:hr, idx_hl])) |
90 |
) |
|
91 |
} |
|
92 | ! |
line_pos <- c( |
93 | ! |
sum(colwidths[1:(which_cols[1] - 1)]) + 1 + lbl_col_padding, |
94 | ! |
sum(colwidths[1:max(which_cols)]) - 1 + lbl_col_padding |
95 |
) |
|
96 | ||
97 | ! |
res <- res + |
98 | ! |
geom_text( |
99 | ! |
x = mean(line_pos), |
100 | ! |
y = nrow(mat_strings) + 1 - hr, |
101 | ! |
label = cur_lbl, |
102 | ! |
size = fontsize |
103 |
) + |
|
104 | ! |
geom_segment( |
105 | ! |
x = line_pos[1], |
106 | ! |
xend = line_pos[2], |
107 | ! |
y = nrow(mat_strings) - hr + 0.5, |
108 | ! |
yend = nrow(mat_strings) - hr + 0.5 |
109 |
) |
|
110 |
} |
|
111 |
} |
|
112 |
} |
|
113 | ||
114 |
# Add table columns |
|
115 | ! |
for (i in seq_len(ncol(tbl_df))) { |
116 | ! |
res <- res + geom_text( |
117 | ! |
x = if (i == 1) 0 else sum(colwidths[1:i]) - 0.5 * colwidths[i] + lbl_col_padding, |
118 | ! |
y = rev(seq_len(nrow(tbl_df))), |
119 | ! |
label = tbl_df[, i], |
120 | ! |
hjust = mat_aligns[, i], |
121 | ! |
size = fontsize |
122 |
) |
|
123 |
} |
|
124 | ||
125 | ! |
res |
126 |
} |
1 |
#' Summary for analysis of covariance (`ANCOVA`). |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Summarize results of `ANCOVA`. This can be used to analyze multiple endpoints and/or |
|
6 |
#' multiple timepoints within the same response variable `.var`. |
|
7 |
#' |
|
8 |
#' @inheritParams h_ancova |
|
9 |
#' @inheritParams argument_convention |
|
10 |
#' @param interaction_y (`character`)\cr a selected item inside of the interaction_item column which will be used |
|
11 |
#' to select the specific `ANCOVA` results. if the interaction is not needed, the default option is `FALSE`. |
|
12 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("summarize_ancova")` |
|
13 |
#' to see available statistics for this function. |
|
14 |
#' |
|
15 |
#' @name summarize_ancova |
|
16 |
#' @order 1 |
|
17 |
NULL |
|
18 | ||
19 |
#' Helper Function to Return Results of a Linear Model |
|
20 |
#' |
|
21 |
#' @description `r lifecycle::badge("stable")` |
|
22 |
#' |
|
23 |
#' @inheritParams argument_convention |
|
24 |
#' @param .df_row (`data.frame`)\cr data set that includes all the variables that are called in `.var` and `variables`. |
|
25 |
#' @param variables (named `list` of `strings`)\cr list of additional analysis variables, with expected elements: |
|
26 |
#' * `arm` (`string`)\cr group variable, for which the covariate adjusted means of multiple groups will be |
|
27 |
#' summarized. Specifically, the first level of `arm` variable is taken as the reference group. |
|
28 |
#' * `covariates` (`character`)\cr a vector that can contain single variable names (such as `"X1"`), and/or |
|
29 |
#' interaction terms indicated by `"X1 * X2"`. |
|
30 |
#' @param interaction_item (`character`)\cr name of the variable that should have interactions |
|
31 |
#' with arm. if the interaction is not needed, the default option is `NULL`. |
|
32 |
#' |
|
33 |
#' @return The summary of a linear model. |
|
34 |
#' |
|
35 |
#' @examples |
|
36 |
#' h_ancova( |
|
37 |
#' .var = "Sepal.Length", |
|
38 |
#' .df_row = iris, |
|
39 |
#' variables = list(arm = "Species", covariates = c("Petal.Length * Petal.Width", "Sepal.Width")) |
|
40 |
#' ) |
|
41 |
#' |
|
42 |
#' @export |
|
43 |
h_ancova <- function(.var, |
|
44 |
.df_row, |
|
45 |
variables, |
|
46 |
interaction_item = NULL) { |
|
47 | 18x |
checkmate::assert_string(.var) |
48 | 18x |
checkmate::assert_list(variables) |
49 | 18x |
checkmate::assert_subset(names(variables), c("arm", "covariates")) |
50 | 18x |
assert_df_with_variables(.df_row, list(rsp = .var)) |
51 | ||
52 | 17x |
arm <- variables$arm |
53 | 17x |
covariates <- variables$covariates |
54 | 17x |
if (!is.null(covariates) && length(covariates) > 0) { |
55 |
# Get all covariate variable names in the model. |
|
56 | 11x |
var_list <- get_covariates(covariates) |
57 | 11x |
assert_df_with_variables(.df_row, var_list) |
58 |
} |
|
59 | ||
60 | 16x |
covariates_part <- paste(covariates, collapse = " + ") |
61 | 16x |
if (covariates_part != "") { |
62 | 10x |
formula <- stats::as.formula(paste0(.var, " ~ ", covariates_part, " + ", arm)) |
63 |
} else { |
|
64 | 6x |
formula <- stats::as.formula(paste0(.var, " ~ ", arm)) |
65 |
} |
|
66 | ||
67 | 16x |
if (is.null(interaction_item)) { |
68 | 12x |
specs <- arm |
69 |
} else { |
|
70 | 4x |
specs <- c(arm, interaction_item) |
71 |
} |
|
72 | ||
73 | 16x |
lm_fit <- stats::lm( |
74 | 16x |
formula = formula, |
75 | 16x |
data = .df_row |
76 |
) |
|
77 | 16x |
emmeans_fit <- emmeans::emmeans( |
78 | 16x |
lm_fit, |
79 |
# Specify here the group variable over which EMM are desired. |
|
80 | 16x |
specs = specs, |
81 |
# Pass the data again so that the factor levels of the arm variable can be inferred. |
|
82 | 16x |
data = .df_row |
83 |
) |
|
84 | ||
85 | 16x |
emmeans_fit |
86 |
} |
|
87 | ||
88 |
#' @describeIn summarize_ancova Statistics function that produces a named list of results |
|
89 |
#' of the investigated linear model. |
|
90 |
#' |
|
91 |
#' @return |
|
92 |
#' * `s_ancova()` returns a named list of 5 statistics: |
|
93 |
#' * `n`: Count of complete sample size for the group. |
|
94 |
#' * `lsmean`: Estimated marginal means in the group. |
|
95 |
#' * `lsmean_diff`: Difference in estimated marginal means in comparison to the reference group. |
|
96 |
#' If working with the reference group, this will be empty. |
|
97 |
#' * `lsmean_diff_ci`: Confidence level for difference in estimated marginal means in comparison |
|
98 |
#' to the reference group. |
|
99 |
#' * `pval`: p-value (not adjusted for multiple comparisons). |
|
100 |
#' |
|
101 |
#' @keywords internal |
|
102 |
s_ancova <- function(df, |
|
103 |
.var, |
|
104 |
.df_row, |
|
105 |
variables, |
|
106 |
.ref_group, |
|
107 |
.in_ref_col, |
|
108 |
conf_level, |
|
109 |
interaction_y = FALSE, |
|
110 |
interaction_item = NULL) { |
|
111 | 3x |
emmeans_fit <- h_ancova(.var = .var, variables = variables, .df_row = .df_row, interaction_item = interaction_item) |
112 | ||
113 | 3x |
sum_fit <- summary( |
114 | 3x |
emmeans_fit, |
115 | 3x |
level = conf_level |
116 |
) |
|
117 | ||
118 | 3x |
arm <- variables$arm |
119 | ||
120 | 3x |
sum_level <- as.character(unique(df[[arm]])) |
121 | ||
122 |
# Ensure that there is only one element in sum_level. |
|
123 | 3x |
checkmate::assert_scalar(sum_level) |
124 | ||
125 | 2x |
sum_fit_level <- sum_fit[sum_fit[[arm]] == sum_level, ] |
126 | ||
127 |
# Get the index of the ref arm |
|
128 | 2x |
if (interaction_y != FALSE) { |
129 | 1x |
y <- unlist(df[(df[[interaction_item]] == interaction_y), .var]) |
130 |
# convert characters selected in interaction_y into the numeric order |
|
131 | 1x |
interaction_y <- which(sum_fit_level[[interaction_item]] == interaction_y) |
132 | 1x |
sum_fit_level <- sum_fit_level[interaction_y, ] |
133 |
# if interaction is called, reset the index |
|
134 | 1x |
ref_key <- seq(sum_fit[[arm]][unique(.ref_group[[arm]])]) |
135 | 1x |
ref_key <- tail(ref_key, n = 1) |
136 | 1x |
ref_key <- (interaction_y - 1) * length(unique(.df_row[[arm]])) + ref_key |
137 |
} else { |
|
138 | 1x |
y <- df[[.var]] |
139 |
# Get the index of the ref arm when interaction is not called |
|
140 | 1x |
ref_key <- seq(sum_fit[[arm]][unique(.ref_group[[arm]])]) |
141 | 1x |
ref_key <- tail(ref_key, n = 1) |
142 |
} |
|
143 | ||
144 | 2x |
if (.in_ref_col) { |
145 | 1x |
list( |
146 | 1x |
n = length(y[!is.na(y)]), |
147 | 1x |
lsmean = formatters::with_label(sum_fit_level$emmean, "Adjusted Mean"), |
148 | 1x |
lsmean_diff = formatters::with_label(character(), "Difference in Adjusted Means"), |
149 | 1x |
lsmean_diff_ci = formatters::with_label(character(), f_conf_level(conf_level)), |
150 | 1x |
pval = formatters::with_label(character(), "p-value") |
151 |
) |
|
152 |
} else { |
|
153 |
# Estimate the differences between the marginal means. |
|
154 | 1x |
emmeans_contrasts <- emmeans::contrast( |
155 | 1x |
emmeans_fit, |
156 |
# Compare all arms versus the control arm. |
|
157 | 1x |
method = "trt.vs.ctrl", |
158 |
# Take the arm factor from .ref_group as the control arm. |
|
159 | 1x |
ref = ref_key, |
160 | 1x |
level = conf_level |
161 |
) |
|
162 | 1x |
sum_contrasts <- summary( |
163 | 1x |
emmeans_contrasts, |
164 |
# Derive confidence intervals, t-tests and p-values. |
|
165 | 1x |
infer = TRUE, |
166 |
# Do not adjust the p-values for multiplicity. |
|
167 | 1x |
adjust = "none" |
168 |
) |
|
169 | ||
170 | 1x |
sum_contrasts_level <- sum_contrasts[grepl(sum_level, sum_contrasts$contrast), ] |
171 | 1x |
if (interaction_y != FALSE) { |
172 | ! |
sum_contrasts_level <- sum_contrasts_level[interaction_y, ] |
173 |
} |
|
174 | ||
175 | 1x |
list( |
176 | 1x |
n = length(y[!is.na(y)]), |
177 | 1x |
lsmean = formatters::with_label(sum_fit_level$emmean, "Adjusted Mean"), |
178 | 1x |
lsmean_diff = formatters::with_label(sum_contrasts_level$estimate, "Difference in Adjusted Means"), |
179 | 1x |
lsmean_diff_ci = formatters::with_label( |
180 | 1x |
c(sum_contrasts_level$lower.CL, sum_contrasts_level$upper.CL), |
181 | 1x |
f_conf_level(conf_level) |
182 |
), |
|
183 | 1x |
pval = formatters::with_label(sum_contrasts_level$p.value, "p-value") |
184 |
) |
|
185 |
} |
|
186 |
} |
|
187 | ||
188 |
#' @describeIn summarize_ancova Formatted analysis function which is used as `afun` in `summarize_ancova()`. |
|
189 |
#' |
|
190 |
#' @return |
|
191 |
#' * `a_ancova()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
192 |
#' |
|
193 |
#' @keywords internal |
|
194 |
a_ancova <- make_afun( |
|
195 |
s_ancova, |
|
196 |
.indent_mods = c("n" = 0L, "lsmean" = 0L, "lsmean_diff" = 0L, "lsmean_diff_ci" = 1L, "pval" = 1L), |
|
197 |
.formats = c( |
|
198 |
"n" = "xx", |
|
199 |
"lsmean" = "xx.xx", |
|
200 |
"lsmean_diff" = "xx.xx", |
|
201 |
"lsmean_diff_ci" = "(xx.xx, xx.xx)", |
|
202 |
"pval" = "x.xxxx | (<0.0001)" |
|
203 |
), |
|
204 |
.null_ref_cells = FALSE |
|
205 |
) |
|
206 | ||
207 |
#' @describeIn summarize_ancova Layout-creating function which can take statistics function arguments |
|
208 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
209 |
#' |
|
210 |
#' @return |
|
211 |
#' * `summarize_ancova()` returns a layout object suitable for passing to further layouting functions, |
|
212 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
213 |
#' the statistics from `s_ancova()` to the table layout. |
|
214 |
#' |
|
215 |
#' @examples |
|
216 |
#' basic_table() %>% |
|
217 |
#' split_cols_by("Species", ref_group = "setosa") %>% |
|
218 |
#' add_colcounts() %>% |
|
219 |
#' summarize_ancova( |
|
220 |
#' vars = "Petal.Length", |
|
221 |
#' variables = list(arm = "Species", covariates = NULL), |
|
222 |
#' table_names = "unadj", |
|
223 |
#' conf_level = 0.95, var_labels = "Unadjusted comparison", |
|
224 |
#' .labels = c(lsmean = "Mean", lsmean_diff = "Difference in Means") |
|
225 |
#' ) %>% |
|
226 |
#' summarize_ancova( |
|
227 |
#' vars = "Petal.Length", |
|
228 |
#' variables = list(arm = "Species", covariates = c("Sepal.Length", "Sepal.Width")), |
|
229 |
#' table_names = "adj", |
|
230 |
#' conf_level = 0.95, var_labels = "Adjusted comparison (covariates: Sepal.Length and Sepal.Width)" |
|
231 |
#' ) %>% |
|
232 |
#' build_table(iris) |
|
233 |
#' |
|
234 |
#' @export |
|
235 |
#' @order 2 |
|
236 |
summarize_ancova <- function(lyt, |
|
237 |
vars, |
|
238 |
variables, |
|
239 |
conf_level, |
|
240 |
interaction_y = FALSE, |
|
241 |
interaction_item = NULL, |
|
242 |
var_labels, |
|
243 |
na_str = default_na_str(), |
|
244 |
nested = TRUE, |
|
245 |
..., |
|
246 |
show_labels = "visible", |
|
247 |
table_names = vars, |
|
248 |
.stats = NULL, |
|
249 |
.formats = NULL, |
|
250 |
.labels = NULL, |
|
251 |
.indent_mods = NULL) { |
|
252 | 4x |
extra_args <- list( |
253 | 4x |
variables = variables, conf_level = conf_level, interaction_y = interaction_y, |
254 | 4x |
interaction_item = interaction_item, ... |
255 |
) |
|
256 | ||
257 | 4x |
afun <- make_afun( |
258 | 4x |
a_ancova, |
259 | 4x |
interaction_y = interaction_y, |
260 | 4x |
interaction_item = interaction_item, |
261 | 4x |
.stats = .stats, |
262 | 4x |
.formats = .formats, |
263 | 4x |
.labels = .labels, |
264 | 4x |
.indent_mods = .indent_mods |
265 |
) |
|
266 | ||
267 | 4x |
analyze( |
268 | 4x |
lyt, |
269 | 4x |
vars, |
270 | 4x |
var_labels = var_labels, |
271 | 4x |
show_labels = show_labels, |
272 | 4x |
table_names = table_names, |
273 | 4x |
afun = afun, |
274 | 4x |
na_str = na_str, |
275 | 4x |
nested = nested, |
276 | 4x |
extra_args = extra_args |
277 |
) |
|
278 |
} |
1 |
#' Occurrence Counts by Grade |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Functions for analyzing frequencies and fractions of occurrences by grade for patients |
|
6 |
#' with occurrence data. Multiple occurrences within one individual are counted once at the |
|
7 |
#' greatest intensity/highest grade level. |
|
8 |
#' |
|
9 |
#' @inheritParams argument_convention |
|
10 |
#' @param grade_groups (named `list` of `character`)\cr containing groupings of grades. |
|
11 |
#' @param remove_single (`logical`)\cr `TRUE` to not include the elements of one-element grade groups |
|
12 |
#' in the the output list; in this case only the grade groups names will be included in the output. |
|
13 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("count_occurrences_by_grade")` |
|
14 |
#' to see available statistics for this function. |
|
15 |
#' |
|
16 |
#' @seealso Relevant helper function [h_append_grade_groups()]. |
|
17 |
#' |
|
18 |
#' @name count_occurrences_by_grade |
|
19 |
#' @order 1 |
|
20 |
NULL |
|
21 | ||
22 |
#' Helper function for [s_count_occurrences_by_grade()] |
|
23 |
#' |
|
24 |
#' @description `r lifecycle::badge("stable")` |
|
25 |
#' |
|
26 |
#' Helper function for [s_count_occurrences_by_grade()] to insert grade groupings into list with |
|
27 |
#' individual grade frequencies. The order of the final result follows the order of `grade_groups`. |
|
28 |
#' The elements under any-grade group (if any), i.e. the grade group equal to `refs` will be moved to |
|
29 |
#' the end. Grade groups names must be unique. |
|
30 |
#' |
|
31 |
#' @inheritParams count_occurrences_by_grade |
|
32 |
#' @param refs (named `list` of `numeric`)\cr where each name corresponds to a reference grade level |
|
33 |
#' and each entry represents a count. |
|
34 |
#' |
|
35 |
#' @return Formatted list of grade groupings. |
|
36 |
#' |
|
37 |
#' @examples |
|
38 |
#' h_append_grade_groups( |
|
39 |
#' list( |
|
40 |
#' "Any Grade" = as.character(1:5), |
|
41 |
#' "Grade 1-2" = c("1", "2"), |
|
42 |
#' "Grade 3-4" = c("3", "4") |
|
43 |
#' ), |
|
44 |
#' list("1" = 10, "2" = 20, "3" = 30, "4" = 40, "5" = 50) |
|
45 |
#' ) |
|
46 |
#' |
|
47 |
#' h_append_grade_groups( |
|
48 |
#' list( |
|
49 |
#' "Any Grade" = as.character(5:1), |
|
50 |
#' "Grade A" = "5", |
|
51 |
#' "Grade B" = c("4", "3") |
|
52 |
#' ), |
|
53 |
#' list("1" = 10, "2" = 20, "3" = 30, "4" = 40, "5" = 50) |
|
54 |
#' ) |
|
55 |
#' |
|
56 |
#' h_append_grade_groups( |
|
57 |
#' list( |
|
58 |
#' "Any Grade" = as.character(1:5), |
|
59 |
#' "Grade 1-2" = c("1", "2"), |
|
60 |
#' "Grade 3-4" = c("3", "4") |
|
61 |
#' ), |
|
62 |
#' list("1" = 10, "2" = 5, "3" = 0) |
|
63 |
#' ) |
|
64 |
#' |
|
65 |
#' @export |
|
66 |
h_append_grade_groups <- function(grade_groups, refs, remove_single = TRUE) { |
|
67 | 13x |
checkmate::assert_list(grade_groups) |
68 | 13x |
checkmate::assert_list(refs) |
69 | 13x |
refs_orig <- refs |
70 | 13x |
elements <- unique(unlist(grade_groups)) |
71 | ||
72 |
### compute sums in groups |
|
73 | 13x |
grp_sum <- lapply(grade_groups, function(i) do.call(sum, refs[i])) |
74 | 13x |
if (!checkmate::test_subset(elements, names(refs))) { |
75 | 2x |
padding_el <- setdiff(elements, names(refs)) |
76 | 2x |
refs[padding_el] <- 0 |
77 |
} |
|
78 | 13x |
result <- c(grp_sum, refs) |
79 | ||
80 |
### order result while keeping grade_groups's ordering |
|
81 | 13x |
ordr <- grade_groups |
82 | ||
83 |
# elements of any-grade group (if any) will be moved to the end |
|
84 | 13x |
is_any <- sapply(grade_groups, setequal, y = names(refs)) |
85 | 13x |
ordr[is_any] <- list(character(0)) # hide elements under any-grade group |
86 | ||
87 |
# groups-elements combined sequence |
|
88 | 13x |
ordr <- c(lapply(names(ordr), function(g) c(g, ordr[[g]])), recursive = TRUE, use.names = FALSE) |
89 | 13x |
ordr <- ordr[!duplicated(ordr)] |
90 | ||
91 |
# append remaining elements (if any) |
|
92 | 13x |
ordr <- union(ordr, unlist(grade_groups[is_any])) # from any-grade group |
93 | 13x |
ordr <- union(ordr, names(refs)) # from refs |
94 | ||
95 |
# remove elements of single-element groups, if any |
|
96 | 13x |
if (remove_single) { |
97 | 13x |
is_single <- sapply(grade_groups, length) == 1L |
98 | 13x |
ordr <- setdiff(ordr, unlist(grade_groups[is_single])) |
99 |
} |
|
100 | ||
101 |
# apply the order |
|
102 | 13x |
result <- result[ordr] |
103 | ||
104 |
# remove groups without any elements in the original refs |
|
105 |
# note: it's OK if groups have 0 value |
|
106 | 13x |
keep_grp <- vapply(grade_groups, function(x, rf) { |
107 | 37x |
any(x %in% rf) |
108 | 13x |
}, rf = names(refs_orig), logical(1)) |
109 | ||
110 | 13x |
keep_el <- names(result) %in% names(refs_orig) | names(result) %in% names(keep_grp)[keep_grp] |
111 | 13x |
result <- result[keep_el] |
112 | ||
113 | 13x |
result |
114 |
} |
|
115 | ||
116 |
#' @describeIn count_occurrences_by_grade Statistics function which counts the |
|
117 |
#' number of patients by highest grade. |
|
118 |
#' |
|
119 |
#' @return |
|
120 |
#' * `s_count_occurrences_by_grade()` returns a list of counts and fractions with one element per grade level or |
|
121 |
#' grade level grouping. |
|
122 |
#' |
|
123 |
#' @examples |
|
124 |
#' s_count_occurrences_by_grade( |
|
125 |
#' df, |
|
126 |
#' .N_col = 10L, |
|
127 |
#' .var = "AETOXGR", |
|
128 |
#' id = "USUBJID", |
|
129 |
#' grade_groups = list("ANY" = levels(df$AETOXGR)) |
|
130 |
#' ) |
|
131 |
#' |
|
132 |
#' @export |
|
133 |
s_count_occurrences_by_grade <- function(df, |
|
134 |
.var, |
|
135 |
.N_col, # nolint |
|
136 |
id = "USUBJID", |
|
137 |
grade_groups = list(), |
|
138 |
remove_single = TRUE, |
|
139 |
labelstr = "") { |
|
140 | 6x |
assert_valid_factor(df[[.var]]) |
141 | 6x |
assert_df_with_variables(df, list(grade = .var, id = id)) |
142 | ||
143 | 6x |
if (nrow(df) < 1) { |
144 | ! |
grade_levels <- levels(df[[.var]]) |
145 | ! |
l_count <- as.list(rep(0, length(grade_levels))) |
146 | ! |
names(l_count) <- grade_levels |
147 |
} else { |
|
148 | 6x |
if (isTRUE(is.factor(df[[id]]))) { |
149 | ! |
assert_valid_factor(df[[id]], any.missing = FALSE) |
150 |
} else { |
|
151 | 6x |
checkmate::assert_character(df[[id]], min.chars = 1, any.missing = FALSE) |
152 |
} |
|
153 | 6x |
checkmate::assert_count(.N_col) |
154 | ||
155 | 6x |
id <- df[[id]] |
156 | 6x |
grade <- df[[.var]] |
157 | ||
158 | 6x |
if (!is.ordered(grade)) { |
159 | 6x |
grade_lbl <- obj_label(grade) |
160 | 6x |
lvls <- levels(grade) |
161 | 6x |
if (sum(grepl("^\\d+$", lvls)) %in% c(0, length(lvls))) { |
162 | 5x |
lvl_ord <- lvls |
163 |
} else { |
|
164 | 1x |
lvls[!grepl("^\\d+$", lvls)] <- min(as.numeric(lvls[grepl("^\\d+$", lvls)])) - 1 |
165 | 1x |
lvl_ord <- levels(grade)[order(as.numeric(lvls))] |
166 |
} |
|
167 | 6x |
grade <- formatters::with_label(factor(grade, levels = lvl_ord, ordered = TRUE), grade_lbl) |
168 |
} |
|
169 | ||
170 | 6x |
missing_lvl <- grepl("missing", tolower(levels(grade))) |
171 | 6x |
if (any(missing_lvl)) { |
172 | 1x |
grade <- factor( |
173 | 1x |
grade, |
174 | 1x |
levels = c(levels(grade)[!missing_lvl], levels(grade)[missing_lvl]), |
175 | 1x |
ordered = is.ordered(grade) |
176 |
) |
|
177 |
} |
|
178 | 6x |
df_max <- stats::aggregate(grade ~ id, FUN = max, drop = FALSE) |
179 | 6x |
l_count <- as.list(table(df_max$grade)) |
180 |
} |
|
181 | ||
182 | 6x |
if (length(grade_groups) > 0) { |
183 | 2x |
l_count <- h_append_grade_groups(grade_groups, l_count, remove_single) |
184 |
} |
|
185 | ||
186 | 6x |
l_count_fraction <- lapply(l_count, function(i, denom) c(i, i / denom), denom = .N_col) |
187 | ||
188 | 6x |
list( |
189 | 6x |
count_fraction = l_count_fraction |
190 |
) |
|
191 |
} |
|
192 | ||
193 |
#' @describeIn count_occurrences_by_grade Formatted analysis function which is used as `afun` |
|
194 |
#' in `count_occurrences_by_grade()`. |
|
195 |
#' |
|
196 |
#' @return |
|
197 |
#' * `a_count_occurrences_by_grade()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
198 |
#' |
|
199 |
#' @examples |
|
200 |
#' # We need to ungroup `count_fraction` first so that the `rtables` formatting |
|
201 |
#' # function `format_count_fraction()` can be applied correctly. |
|
202 |
#' afun <- make_afun(a_count_occurrences_by_grade, .ungroup_stats = "count_fraction") |
|
203 |
#' afun( |
|
204 |
#' df, |
|
205 |
#' .N_col = 10L, |
|
206 |
#' .var = "AETOXGR", |
|
207 |
#' id = "USUBJID", |
|
208 |
#' grade_groups = list("ANY" = levels(df$AETOXGR)) |
|
209 |
#' ) |
|
210 |
#' |
|
211 |
#' @export |
|
212 |
a_count_occurrences_by_grade <- make_afun( |
|
213 |
s_count_occurrences_by_grade, |
|
214 |
.formats = c("count_fraction" = format_count_fraction_fixed_dp) |
|
215 |
) |
|
216 | ||
217 |
#' @describeIn count_occurrences_by_grade Layout-creating function which can take statistics function |
|
218 |
#' arguments and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
219 |
#' |
|
220 |
#' @return |
|
221 |
#' * `count_occurrences_by_grade()` returns a layout object suitable for passing to further layouting functions, |
|
222 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
223 |
#' the statistics from `s_count_occurrences_by_grade()` to the table layout. |
|
224 |
#' |
|
225 |
#' @examples |
|
226 |
#' library(dplyr) |
|
227 |
#' |
|
228 |
#' df <- data.frame( |
|
229 |
#' USUBJID = as.character(c(1:6, 1)), |
|
230 |
#' ARM = factor(c("A", "A", "A", "B", "B", "B", "A"), levels = c("A", "B")), |
|
231 |
#' AETOXGR = factor(c(1, 2, 3, 4, 1, 2, 3), levels = c(1:5)), |
|
232 |
#' AESEV = factor( |
|
233 |
#' x = c("MILD", "MODERATE", "SEVERE", "MILD", "MILD", "MODERATE", "SEVERE"), |
|
234 |
#' levels = c("MILD", "MODERATE", "SEVERE") |
|
235 |
#' ), |
|
236 |
#' stringsAsFactors = FALSE |
|
237 |
#' ) |
|
238 |
#' |
|
239 |
#' df_adsl <- df %>% |
|
240 |
#' select(USUBJID, ARM) %>% |
|
241 |
#' unique() |
|
242 |
#' |
|
243 |
#' # Layout creating function with custom format. |
|
244 |
#' basic_table() %>% |
|
245 |
#' split_cols_by("ARM") %>% |
|
246 |
#' add_colcounts() %>% |
|
247 |
#' count_occurrences_by_grade( |
|
248 |
#' var = "AESEV", |
|
249 |
#' .formats = c("count_fraction" = "xx.xx (xx.xx%)") |
|
250 |
#' ) %>% |
|
251 |
#' build_table(df, alt_counts_df = df_adsl) |
|
252 |
#' |
|
253 |
#' # Define additional grade groupings. |
|
254 |
#' grade_groups <- list( |
|
255 |
#' "-Any-" = c("1", "2", "3", "4", "5"), |
|
256 |
#' "Grade 1-2" = c("1", "2"), |
|
257 |
#' "Grade 3-5" = c("3", "4", "5") |
|
258 |
#' ) |
|
259 |
#' |
|
260 |
#' basic_table() %>% |
|
261 |
#' split_cols_by("ARM") %>% |
|
262 |
#' add_colcounts() %>% |
|
263 |
#' count_occurrences_by_grade( |
|
264 |
#' var = "AETOXGR", |
|
265 |
#' grade_groups = grade_groups |
|
266 |
#' ) %>% |
|
267 |
#' build_table(df, alt_counts_df = df_adsl) |
|
268 |
#' |
|
269 |
#' @export |
|
270 |
#' @order 2 |
|
271 |
count_occurrences_by_grade <- function(lyt, |
|
272 |
var, |
|
273 |
id = "USUBJID", |
|
274 |
grade_groups = list(), |
|
275 |
remove_single = TRUE, |
|
276 |
var_labels = var, |
|
277 |
show_labels = "default", |
|
278 |
riskdiff = FALSE, |
|
279 |
na_str = default_na_str(), |
|
280 |
nested = TRUE, |
|
281 |
..., |
|
282 |
table_names = var, |
|
283 |
.stats = NULL, |
|
284 |
.formats = NULL, |
|
285 |
.indent_mods = NULL, |
|
286 |
.labels = NULL) { |
|
287 | 8x |
checkmate::assert_flag(riskdiff) |
288 | ||
289 | 8x |
s_args <- list(id = id, grade_groups = grade_groups, remove_single = remove_single, ...) |
290 | ||
291 | 8x |
afun <- make_afun( |
292 | 8x |
a_count_occurrences_by_grade, |
293 | 8x |
.stats = .stats, |
294 | 8x |
.formats = .formats, |
295 | 8x |
.indent_mods = .indent_mods, |
296 | 8x |
.ungroup_stats = "count_fraction" |
297 |
) |
|
298 | ||
299 | 8x |
extra_args <- if (isFALSE(riskdiff)) { |
300 | 7x |
s_args |
301 |
} else { |
|
302 | 1x |
list( |
303 | 1x |
afun = list("s_count_occurrences_by_grade" = afun), |
304 | 1x |
.stats = .stats, |
305 | 1x |
.indent_mods = .indent_mods, |
306 | 1x |
s_args = s_args |
307 |
) |
|
308 |
} |
|
309 | ||
310 | 8x |
analyze( |
311 | 8x |
lyt = lyt, |
312 | 8x |
vars = var, |
313 | 8x |
var_labels = var_labels, |
314 | 8x |
show_labels = show_labels, |
315 | 8x |
afun = ifelse(isFALSE(riskdiff), afun, afun_riskdiff), |
316 | 8x |
table_names = table_names, |
317 | 8x |
na_str = na_str, |
318 | 8x |
nested = nested, |
319 | 8x |
extra_args = extra_args |
320 |
) |
|
321 |
} |
|
322 | ||
323 |
#' @describeIn count_occurrences_by_grade Layout-creating function which can take content function arguments |
|
324 |
#' and additional format arguments. This function is a wrapper for [rtables::summarize_row_groups()]. |
|
325 |
#' |
|
326 |
#' @return |
|
327 |
#' * `summarize_occurrences_by_grade()` returns a layout object suitable for passing to further layouting functions, |
|
328 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted content rows |
|
329 |
#' containing the statistics from `s_count_occurrences_by_grade()` to the table layout. |
|
330 |
#' |
|
331 |
#' @examples |
|
332 |
#' # Layout creating function with custom format. |
|
333 |
#' basic_table() %>% |
|
334 |
#' add_colcounts() %>% |
|
335 |
#' split_rows_by("ARM", child_labels = "visible", nested = TRUE) %>% |
|
336 |
#' summarize_occurrences_by_grade( |
|
337 |
#' var = "AESEV", |
|
338 |
#' .formats = c("count_fraction" = "xx.xx (xx.xx%)") |
|
339 |
#' ) %>% |
|
340 |
#' build_table(df, alt_counts_df = df_adsl) |
|
341 |
#' |
|
342 |
#' basic_table() %>% |
|
343 |
#' add_colcounts() %>% |
|
344 |
#' split_rows_by("ARM", child_labels = "visible", nested = TRUE) %>% |
|
345 |
#' summarize_occurrences_by_grade( |
|
346 |
#' var = "AETOXGR", |
|
347 |
#' grade_groups = grade_groups |
|
348 |
#' ) %>% |
|
349 |
#' build_table(df, alt_counts_df = df_adsl) |
|
350 |
#' |
|
351 |
#' @export |
|
352 |
#' @order 3 |
|
353 |
summarize_occurrences_by_grade <- function(lyt, |
|
354 |
var, |
|
355 |
id = "USUBJID", |
|
356 |
grade_groups = list(), |
|
357 |
remove_single = TRUE, |
|
358 |
na_str = default_na_str(), |
|
359 |
..., |
|
360 |
.stats = NULL, |
|
361 |
.formats = NULL, |
|
362 |
.indent_mods = NULL, |
|
363 |
.labels = NULL) { |
|
364 | 2x |
extra_args <- list(id = id, grade_groups = grade_groups, remove_single = remove_single, ...) |
365 | ||
366 | 2x |
cfun <- make_afun( |
367 | 2x |
a_count_occurrences_by_grade, |
368 | 2x |
.stats = .stats, |
369 | 2x |
.formats = .formats, |
370 | 2x |
.labels = .labels, |
371 | 2x |
.indent_mods = .indent_mods, |
372 | 2x |
.ungroup_stats = "count_fraction" |
373 |
) |
|
374 | ||
375 | 2x |
summarize_row_groups( |
376 | 2x |
lyt = lyt, |
377 | 2x |
var = var, |
378 | 2x |
cfun = cfun, |
379 | 2x |
na_str = na_str, |
380 | 2x |
extra_args = extra_args |
381 |
) |
|
382 |
} |
1 |
#' Subgroup Treatment Effect Pattern (STEP) Fit for Survival Outcome |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' This fits the Subgroup Treatment Effect Pattern models for a survival outcome. The treatment arm |
|
6 |
#' variable must have exactly 2 levels, where the first one is taken as reference and the estimated |
|
7 |
#' hazard ratios are for the comparison of the second level vs. the first one. |
|
8 |
#' |
|
9 |
#' The model which is fit is: |
|
10 |
#' |
|
11 |
#' `Surv(time, event) ~ arm * poly(biomarker, degree) + covariates + strata(strata)` |
|
12 |
#' |
|
13 |
#' where `degree` is specified by `control_step()`. |
|
14 |
#' |
|
15 |
#' @inheritParams argument_convention |
|
16 |
#' @param variables (named `list` of `character`)\cr list of analysis variables: needs `time`, `event`, |
|
17 |
#' `arm`, `biomarker`, and optional `covariates` and `strata`. |
|
18 |
#' @param control (named `list`)\cr combined control list from [control_step()] and [control_coxph()]. |
|
19 |
#' |
|
20 |
#' @return A matrix of class `step`. The first part of the columns describe the subgroup intervals used |
|
21 |
#' for the biomarker variable, including where the center of the intervals are and their bounds. The |
|
22 |
#' second part of the columns contain the estimates for the treatment arm comparison. |
|
23 |
#' |
|
24 |
#' @note For the default degree 0 the `biomarker` variable is not included in the model. |
|
25 |
#' |
|
26 |
#' @seealso [control_step()] and [control_coxph()] for the available customization options. |
|
27 |
#' |
|
28 |
#' @examples |
|
29 |
#' # Testing dataset with just two treatment arms. |
|
30 |
#' library(dplyr) |
|
31 |
#' |
|
32 |
#' adtte_f <- tern_ex_adtte %>% |
|
33 |
#' filter( |
|
34 |
#' PARAMCD == "OS", |
|
35 |
#' ARM %in% c("B: Placebo", "A: Drug X") |
|
36 |
#' ) %>% |
|
37 |
#' mutate( |
|
38 |
#' # Reorder levels of ARM to display reference arm before treatment arm. |
|
39 |
#' ARM = droplevels(forcats::fct_relevel(ARM, "B: Placebo")), |
|
40 |
#' is_event = CNSR == 0 |
|
41 |
#' ) |
|
42 |
#' labels <- c("ARM" = "Treatment Arm", "is_event" = "Event Flag") |
|
43 |
#' formatters::var_labels(adtte_f)[names(labels)] <- labels |
|
44 |
#' |
|
45 |
#' variables <- list( |
|
46 |
#' arm = "ARM", |
|
47 |
#' biomarker = "BMRKR1", |
|
48 |
#' covariates = c("AGE", "BMRKR2"), |
|
49 |
#' event = "is_event", |
|
50 |
#' time = "AVAL" |
|
51 |
#' ) |
|
52 |
#' |
|
53 |
#' # Fit default STEP models: Here a constant treatment effect is estimated in each subgroup. |
|
54 |
#' step_matrix <- fit_survival_step( |
|
55 |
#' variables = variables, |
|
56 |
#' data = adtte_f |
|
57 |
#' ) |
|
58 |
#' dim(step_matrix) |
|
59 |
#' head(step_matrix) |
|
60 |
#' |
|
61 |
#' # Specify different polynomial degree for the biomarker interaction to use more flexible local |
|
62 |
#' # models. Or specify different Cox regression options. |
|
63 |
#' step_matrix2 <- fit_survival_step( |
|
64 |
#' variables = variables, |
|
65 |
#' data = adtte_f, |
|
66 |
#' control = c(control_coxph(conf_level = 0.9), control_step(degree = 2)) |
|
67 |
#' ) |
|
68 |
#' |
|
69 |
#' # Use a global model with cubic interaction and only 5 points. |
|
70 |
#' step_matrix3 <- fit_survival_step( |
|
71 |
#' variables = variables, |
|
72 |
#' data = adtte_f, |
|
73 |
#' control = c(control_coxph(), control_step(bandwidth = NULL, degree = 3, num_points = 5L)) |
|
74 |
#' ) |
|
75 |
#' |
|
76 |
#' @export |
|
77 |
fit_survival_step <- function(variables, |
|
78 |
data, |
|
79 |
control = c(control_step(), control_coxph())) { |
|
80 | 4x |
checkmate::assert_list(control) |
81 | 4x |
assert_df_with_variables(data, variables) |
82 | 4x |
data <- data[!is.na(data[[variables$biomarker]]), ] |
83 | 4x |
window_sel <- h_step_window(x = data[[variables$biomarker]], control = control) |
84 | 4x |
interval_center <- window_sel$interval[, "Interval Center"] |
85 | 4x |
form <- h_step_survival_formula(variables = variables, control = control) |
86 | 4x |
estimates <- if (is.null(control$bandwidth)) { |
87 | 1x |
h_step_survival_est( |
88 | 1x |
formula = form, |
89 | 1x |
data = data, |
90 | 1x |
variables = variables, |
91 | 1x |
x = interval_center, |
92 | 1x |
control = control |
93 |
) |
|
94 |
} else { |
|
95 | 3x |
tmp <- mapply( |
96 | 3x |
FUN = h_step_survival_est, |
97 | 3x |
x = interval_center, |
98 | 3x |
subset = as.list(as.data.frame(window_sel$sel)), |
99 | 3x |
MoreArgs = list( |
100 | 3x |
formula = form, |
101 | 3x |
data = data, |
102 | 3x |
variables = variables, |
103 | 3x |
control = control |
104 |
) |
|
105 |
) |
|
106 |
# Maybe we find a more elegant solution than this. |
|
107 | 3x |
rownames(tmp) <- c("n", "events", "loghr", "se", "ci_lower", "ci_upper") |
108 | 3x |
t(tmp) |
109 |
} |
|
110 | 4x |
result <- cbind(window_sel$interval, estimates) |
111 | 4x |
structure( |
112 | 4x |
result, |
113 | 4x |
class = c("step", "matrix"), |
114 | 4x |
variables = variables, |
115 | 4x |
control = control |
116 |
) |
|
117 |
} |
1 |
#' Cumulative Counts with Thresholds |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Summarize cumulative counts of a (`numeric`) vector that is less than, less or equal to, |
|
6 |
#' greater than, or greater or equal to user-specific thresholds. |
|
7 |
#' |
|
8 |
#' @inheritParams h_count_cumulative |
|
9 |
#' @inheritParams argument_convention |
|
10 |
#' @param thresholds (`numeric`)\cr vector of cutoff value for the counts. |
|
11 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("count_cumulative")` |
|
12 |
#' to see available statistics for this function. |
|
13 |
#' |
|
14 |
#' @seealso Relevant helper function [h_count_cumulative()], and descriptive function [d_count_cumulative()]. |
|
15 |
#' |
|
16 |
#' @name count_cumulative |
|
17 |
#' @order 1 |
|
18 |
NULL |
|
19 | ||
20 |
#' Helper Function for [s_count_cumulative()] |
|
21 |
#' |
|
22 |
#' @description `r lifecycle::badge("stable")` |
|
23 |
#' |
|
24 |
#' Helper function to calculate count and fraction of `x` values in the lower or upper tail given a threshold. |
|
25 |
#' |
|
26 |
#' @inheritParams argument_convention |
|
27 |
#' @param threshold (`number`)\cr a cutoff value as threshold to count values of `x`. |
|
28 |
#' @param lower_tail (`logical`)\cr whether to count lower tail, default is `TRUE`. |
|
29 |
#' @param include_eq (`logical`)\cr whether to include value equal to the `threshold` in |
|
30 |
#' count, default is `TRUE`. |
|
31 |
#' |
|
32 |
#' @return A named vector with items: |
|
33 |
#' * `count`: the count of values less than, less or equal to, greater than, or greater or equal to a threshold |
|
34 |
#' of user specification. |
|
35 |
#' * `fraction`: the fraction of the count. |
|
36 |
#' |
|
37 |
#' @seealso [count_cumulative] |
|
38 |
#' |
|
39 |
#' @examples |
|
40 |
#' set.seed(1, kind = "Mersenne-Twister") |
|
41 |
#' x <- c(sample(1:10, 10), NA) |
|
42 |
#' .N_col <- length(x) |
|
43 |
#' |
|
44 |
#' h_count_cumulative(x, 5, .N_col = .N_col) |
|
45 |
#' h_count_cumulative(x, 5, lower_tail = FALSE, include_eq = FALSE, na.rm = FALSE, .N_col = .N_col) |
|
46 |
#' h_count_cumulative(x, 0, lower_tail = FALSE, .N_col = .N_col) |
|
47 |
#' h_count_cumulative(x, 100, lower_tail = FALSE, .N_col = .N_col) |
|
48 |
#' |
|
49 |
#' @export |
|
50 |
h_count_cumulative <- function(x, |
|
51 |
threshold, |
|
52 |
lower_tail = TRUE, |
|
53 |
include_eq = TRUE, |
|
54 |
na.rm = TRUE, # nolint |
|
55 |
.N_col) { # nolint |
|
56 | 20x |
checkmate::assert_numeric(x) |
57 | 20x |
checkmate::assert_numeric(threshold) |
58 | 20x |
checkmate::assert_numeric(.N_col) |
59 | 20x |
checkmate::assert_flag(lower_tail) |
60 | 20x |
checkmate::assert_flag(include_eq) |
61 | 20x |
checkmate::assert_flag(na.rm) |
62 | ||
63 | 20x |
is_keep <- if (na.rm) !is.na(x) else rep(TRUE, length(x)) |
64 | 20x |
count <- if (lower_tail && include_eq) { |
65 | 7x |
length(x[is_keep & x <= threshold]) |
66 | 20x |
} else if (lower_tail && !include_eq) { |
67 | ! |
length(x[is_keep & x < threshold]) |
68 | 20x |
} else if (!lower_tail && include_eq) { |
69 | 6x |
length(x[is_keep & x >= threshold]) |
70 | 20x |
} else if (!lower_tail && !include_eq) { |
71 | 7x |
length(x[is_keep & x > threshold]) |
72 |
} |
|
73 | ||
74 | 20x |
result <- c(count = count, fraction = count / .N_col) |
75 | 20x |
result |
76 |
} |
|
77 | ||
78 |
#' Description of Cumulative Count |
|
79 |
#' |
|
80 |
#' @description `r lifecycle::badge("stable")` |
|
81 |
#' |
|
82 |
#' This is a helper function that describes the analysis in [s_count_cumulative()]. |
|
83 |
#' |
|
84 |
#' @inheritParams h_count_cumulative |
|
85 |
#' |
|
86 |
#' @return Labels for [s_count_cumulative()]. |
|
87 |
#' |
|
88 |
#' @export |
|
89 |
d_count_cumulative <- function(threshold, lower_tail, include_eq) { |
|
90 | 18x |
checkmate::assert_numeric(threshold) |
91 | 18x |
lg <- if (lower_tail) "<" else ">" |
92 | 18x |
eq <- if (include_eq) "=" else "" |
93 | 18x |
paste0(lg, eq, " ", threshold) |
94 |
} |
|
95 | ||
96 |
#' @describeIn count_cumulative Statistics function that produces a named list given a numeric vector of thresholds. |
|
97 |
#' |
|
98 |
#' @return |
|
99 |
#' * `s_count_cumulative()` returns a named list of `count_fraction`s: a list with each `thresholds` value as a |
|
100 |
#' component, each component containing a vector for the count and fraction. |
|
101 |
#' |
|
102 |
#' @keywords internal |
|
103 |
s_count_cumulative <- function(x, |
|
104 |
thresholds, |
|
105 |
lower_tail = TRUE, |
|
106 |
include_eq = TRUE, |
|
107 |
.N_col, # nolint |
|
108 |
...) { |
|
109 | 5x |
checkmate::assert_numeric(thresholds, min.len = 1, any.missing = FALSE) |
110 | ||
111 | 5x |
count_fraction_list <- Map(function(thres) { |
112 | 10x |
result <- h_count_cumulative(x, thres, lower_tail, include_eq, .N_col = .N_col, ...) |
113 | 10x |
label <- d_count_cumulative(thres, lower_tail, include_eq) |
114 | 10x |
formatters::with_label(result, label) |
115 | 5x |
}, thresholds) |
116 | ||
117 | 5x |
names(count_fraction_list) <- thresholds |
118 | 5x |
list(count_fraction = count_fraction_list) |
119 |
} |
|
120 | ||
121 |
#' @describeIn count_cumulative Formatted analysis function which is used as `afun` |
|
122 |
#' in `count_cumulative()`. |
|
123 |
#' |
|
124 |
#' @return |
|
125 |
#' * `a_count_cumulative()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
126 |
#' |
|
127 |
#' @keywords internal |
|
128 |
a_count_cumulative <- make_afun( |
|
129 |
s_count_cumulative, |
|
130 |
.formats = c(count_fraction = format_count_fraction) |
|
131 |
) |
|
132 | ||
133 |
#' @describeIn count_cumulative Layout-creating function which can take statistics function arguments |
|
134 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
135 |
#' |
|
136 |
#' @return |
|
137 |
#' * `count_cumulative()` returns a layout object suitable for passing to further layouting functions, |
|
138 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
139 |
#' the statistics from `s_count_cumulative()` to the table layout. |
|
140 |
#' |
|
141 |
#' @examples |
|
142 |
#' basic_table() %>% |
|
143 |
#' split_cols_by("ARM") %>% |
|
144 |
#' add_colcounts() %>% |
|
145 |
#' count_cumulative( |
|
146 |
#' vars = "AGE", |
|
147 |
#' thresholds = c(40, 60) |
|
148 |
#' ) %>% |
|
149 |
#' build_table(tern_ex_adsl) |
|
150 |
#' |
|
151 |
#' @export |
|
152 |
#' @order 2 |
|
153 |
count_cumulative <- function(lyt, |
|
154 |
vars, |
|
155 |
thresholds, |
|
156 |
lower_tail = TRUE, |
|
157 |
include_eq = TRUE, |
|
158 |
var_labels = vars, |
|
159 |
show_labels = "visible", |
|
160 |
na_str = default_na_str(), |
|
161 |
nested = TRUE, |
|
162 |
..., |
|
163 |
table_names = vars, |
|
164 |
.stats = NULL, |
|
165 |
.formats = NULL, |
|
166 |
.labels = NULL, |
|
167 |
.indent_mods = NULL) { |
|
168 | 2x |
extra_args <- list(thresholds = thresholds, lower_tail = lower_tail, include_eq = include_eq, ...) |
169 | ||
170 | 2x |
afun <- make_afun( |
171 | 2x |
a_count_cumulative, |
172 | 2x |
.stats = .stats, |
173 | 2x |
.formats = .formats, |
174 | 2x |
.labels = .labels, |
175 | 2x |
.indent_mods = .indent_mods, |
176 | 2x |
.ungroup_stats = "count_fraction" |
177 |
) |
|
178 | 2x |
analyze( |
179 | 2x |
lyt, |
180 | 2x |
vars, |
181 | 2x |
afun = afun, |
182 | 2x |
na_str = na_str, |
183 | 2x |
table_names = table_names, |
184 | 2x |
var_labels = var_labels, |
185 | 2x |
show_labels = show_labels, |
186 | 2x |
nested = nested, |
187 | 2x |
extra_args = extra_args |
188 |
) |
|
189 |
} |
1 |
#' Get default statistical methods and their associated formats, labels, and indent modifiers |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("experimental")` |
|
4 |
#' |
|
5 |
#' Utility functions to get valid statistic methods for different method groups |
|
6 |
#' (`.stats`) and their associated formats (`.formats`), labels (`.labels`), and indent modifiers |
|
7 |
#' (`.indent_mods`). This utility is used across `tern`, but some of its working principles can be |
|
8 |
#' seen in [analyze_vars()]. See notes to understand why this is experimental. |
|
9 |
#' |
|
10 |
#' @param stats (`character`)\cr statistical methods to get defaults for. |
|
11 |
#' |
|
12 |
#' @details |
|
13 |
#' Current choices for `type` are `counts` and `numeric` for [analyze_vars()] and affect `get_stats()`. |
|
14 |
#' |
|
15 |
#' @note |
|
16 |
#' These defaults are experimental because we use the names of functions to retrieve the default |
|
17 |
#' statistics. This should be generalized in groups of methods according to more reasonable groupings. |
|
18 |
#' |
|
19 |
#' @name default_stats_formats_labels |
|
20 |
NULL |
|
21 | ||
22 |
#' @describeIn default_stats_formats_labels Get statistics available for a given method |
|
23 |
#' group (analyze function). |
|
24 |
#' |
|
25 |
#' @param method_groups (`character`)\cr indicates the statistical method group (`tern` analyze function) |
|
26 |
#' to retrieve default statistics for. A character vector can be used to specify more than one statistical |
|
27 |
#' method group. |
|
28 |
#' @param stats_in (`character`)\cr statistics to retrieve for the selected method group. |
|
29 |
#' @param add_pval (`flag`)\cr should `"pval"` (or `"pval_counts"` if `method_groups` contains |
|
30 |
#' `"analyze_vars_counts"`) be added to the statistical methods? |
|
31 |
#' |
|
32 |
#' @return |
|
33 |
#' * `get_stats()` returns a `character` vector of statistical methods. |
|
34 |
#' |
|
35 |
#' @examples |
|
36 |
#' # analyze_vars is numeric |
|
37 |
#' num_stats <- get_stats("analyze_vars_numeric") # also the default |
|
38 |
#' |
|
39 |
#' # Other type |
|
40 |
#' cnt_stats <- get_stats("analyze_vars_counts") |
|
41 |
#' |
|
42 |
#' # Weirdly taking the pval from count_occurrences |
|
43 |
#' only_pval <- get_stats("count_occurrences", add_pval = TRUE, stats_in = "pval") |
|
44 |
#' |
|
45 |
#' # All count_occurrences |
|
46 |
#' all_cnt_occ <- get_stats("count_occurrences") |
|
47 |
#' |
|
48 |
#' # Multiple |
|
49 |
#' get_stats(c("count_occurrences", "analyze_vars_counts")) |
|
50 |
#' |
|
51 |
#' @export |
|
52 |
get_stats <- function(method_groups = "analyze_vars_numeric", stats_in = NULL, add_pval = FALSE) { |
|
53 | 425x |
checkmate::assert_character(method_groups) |
54 | 425x |
checkmate::assert_character(stats_in, null.ok = TRUE) |
55 | 425x |
checkmate::assert_flag(add_pval) |
56 | ||
57 |
# Default is still numeric |
|
58 | 425x |
if (any(method_groups == "analyze_vars")) { |
59 | 2x |
method_groups[method_groups == "analyze_vars"] <- "analyze_vars_numeric" |
60 |
} |
|
61 | ||
62 | 425x |
type_tmp <- ifelse(any(grepl("counts", method_groups)), "counts", "numeric") # for pval checks |
63 | ||
64 |
# Defaults for loop |
|
65 | 425x |
out <- NULL |
66 | ||
67 |
# Loop for multiple method groups |
|
68 | 425x |
for (mgi in method_groups) { |
69 | 435x |
out_tmp <- if (mgi %in% names(tern_default_stats)) { |
70 | 435x |
tern_default_stats[[mgi]] |
71 |
} else { |
|
72 | ! |
stop("The selected method group (", mgi, ") has no default statistical method.") |
73 |
} |
|
74 | 435x |
out <- unique(c(out, out_tmp)) |
75 |
} |
|
76 | ||
77 |
# If you added pval to the stats_in you certainly want it |
|
78 | 425x |
if (!is.null(stats_in) && any(grepl("^pval", stats_in))) { |
79 | 24x |
stats_in_pval_value <- stats_in[grepl("^pval", stats_in)] |
80 | ||
81 |
# Must be only one value between choices |
|
82 | 24x |
checkmate::assert_choice(stats_in_pval_value, c("pval", "pval_counts")) |
83 | ||
84 |
# Mismatch with counts and numeric |
|
85 | 23x |
if (any(grepl("counts", method_groups)) && stats_in_pval_value != "pval_counts" || |
86 | 23x |
any(grepl("numeric", method_groups)) && stats_in_pval_value != "pval") { # nolint |
87 | 2x |
stop( |
88 | 2x |
"Inserted p-value (", stats_in_pval_value, ") is not valid for type ", |
89 | 2x |
type_tmp, ". Use ", paste(ifelse(stats_in_pval_value == "pval", "pval_counts", "pval")), |
90 | 2x |
" instead." |
91 |
) |
|
92 |
} |
|
93 | ||
94 |
# Lets add it even if present (thanks to unique) |
|
95 | 21x |
add_pval <- TRUE |
96 |
} |
|
97 | ||
98 |
# Mainly used in "analyze_vars" but it could be necessary elsewhere |
|
99 | 422x |
if (isTRUE(add_pval)) { |
100 | 25x |
if (any(grepl("counts", method_groups))) { |
101 | 10x |
out <- unique(c(out, "pval_counts")) |
102 |
} else { |
|
103 | 15x |
out <- unique(c(out, "pval")) |
104 |
} |
|
105 |
} |
|
106 | ||
107 |
# Filtering for stats_in (character vector) |
|
108 | 422x |
if (!is.null(stats_in)) { |
109 | 393x |
out <- intersect(stats_in, out) # It orders them too |
110 |
} |
|
111 | ||
112 |
# If intersect did not find matches (and no pval?) -> error |
|
113 | 422x |
if (length(out) == 0) { |
114 | 2x |
stop( |
115 | 2x |
"The selected method group(s) (", paste0(method_groups, collapse = ", "), ")", |
116 | 2x |
" do not have the required default statistical methods:\n", |
117 | 2x |
paste0(stats_in, collapse = " ") |
118 |
) |
|
119 |
} |
|
120 | ||
121 | 420x |
out |
122 |
} |
|
123 | ||
124 |
#' @describeIn default_stats_formats_labels Get formats corresponding to a list of statistics. |
|
125 |
#' |
|
126 |
#' @param formats_in (named `vector`) \cr inserted formats to replace defaults. It can be a |
|
127 |
#' character vector from [formatters::list_valid_format_labels()] or a custom format function. |
|
128 |
#' |
|
129 |
#' @return |
|
130 |
#' * `get_formats_from_stats()` returns a named vector of formats (if present in either |
|
131 |
#' `tern_default_formats` or `formats_in`, otherwise `NULL`). Values can be taken from |
|
132 |
#' [formatters::list_valid_format_labels()] or a custom function (e.g. [formatting_functions]). |
|
133 |
#' |
|
134 |
#' @note Formats in `tern` and `rtables` can be functions that take in the table cell value and |
|
135 |
#' return a string. This is well documented in `vignette("custom_appearance", package = "rtables")`. |
|
136 |
#' |
|
137 |
#' @examples |
|
138 |
#' # Defaults formats |
|
139 |
#' get_formats_from_stats(num_stats) |
|
140 |
#' get_formats_from_stats(cnt_stats) |
|
141 |
#' get_formats_from_stats(only_pval) |
|
142 |
#' get_formats_from_stats(all_cnt_occ) |
|
143 |
#' |
|
144 |
#' # Addition of customs |
|
145 |
#' get_formats_from_stats(all_cnt_occ, formats_in = c("fraction" = c("xx"))) |
|
146 |
#' get_formats_from_stats(all_cnt_occ, formats_in = list("fraction" = c("xx.xx", "xx"))) |
|
147 |
#' |
|
148 |
#' @seealso [formatting_functions] |
|
149 |
#' |
|
150 |
#' @export |
|
151 |
get_formats_from_stats <- function(stats, formats_in = NULL) { |
|
152 | 413x |
checkmate::assert_character(stats, min.len = 1) |
153 |
# It may be a list if there is a function in the formats |
|
154 | 413x |
if (checkmate::test_list(formats_in, null.ok = TRUE)) { |
155 | 357x |
checkmate::assert_list(formats_in, null.ok = TRUE) |
156 |
# Or it may be a vector of characters |
|
157 |
} else { |
|
158 | 56x |
checkmate::assert_character(formats_in, null.ok = TRUE) |
159 |
} |
|
160 | ||
161 |
# Extract global defaults |
|
162 | 413x |
which_fmt <- match(stats, names(tern_default_formats)) |
163 | ||
164 |
# Select only needed formats from stats |
|
165 | 413x |
ret <- vector("list", length = length(stats)) # Returning a list is simpler |
166 | 413x |
ret[!is.na(which_fmt)] <- tern_default_formats[which_fmt[!is.na(which_fmt)]] |
167 | ||
168 | 413x |
out <- setNames(ret, stats) |
169 | ||
170 |
# Modify some with custom formats |
|
171 | 413x |
if (!is.null(formats_in)) { |
172 |
# Stats is the main |
|
173 | 58x |
common_names <- intersect(names(out), names(formats_in)) |
174 | 58x |
out[common_names] <- formats_in[common_names] |
175 |
} |
|
176 | ||
177 | 413x |
out |
178 |
} |
|
179 | ||
180 |
#' @describeIn default_stats_formats_labels Get labels corresponding to a list of statistics. |
|
181 |
#' |
|
182 |
#' @param labels_in (named `vector` of `character`)\cr inserted labels to replace defaults. |
|
183 |
#' @param row_nms (`character`)\cr row names. Levels of a `factor` or `character` variable, each |
|
184 |
#' of which the statistics in `.stats` will be calculated for. If this parameter is set, these |
|
185 |
#' variable levels will be used as the defaults, and the names of the given custom values should |
|
186 |
#' correspond to levels (or have format `statistic.level`) instead of statistics. Can also be |
|
187 |
#' variable names if rows correspond to different variables instead of levels. Defaults to `NULL`. |
|
188 |
#' |
|
189 |
#' @return |
|
190 |
#' * `get_labels_from_stats()` returns a named `character` vector of labels (if present in either |
|
191 |
#' `tern_default_labels` or `labels_in`, otherwise `NULL`). |
|
192 |
#' |
|
193 |
#' @examples |
|
194 |
#' # Defaults labels |
|
195 |
#' get_labels_from_stats(num_stats) |
|
196 |
#' get_labels_from_stats(cnt_stats) |
|
197 |
#' get_labels_from_stats(only_pval) |
|
198 |
#' get_labels_from_stats(all_cnt_occ) |
|
199 |
#' |
|
200 |
#' # Addition of customs |
|
201 |
#' get_labels_from_stats(all_cnt_occ, labels_in = c("fraction" = "Fraction")) |
|
202 |
#' get_labels_from_stats(all_cnt_occ, labels_in = list("fraction" = c("Some more fractions"))) |
|
203 |
#' |
|
204 |
#' @export |
|
205 |
get_labels_from_stats <- function(stats, labels_in = NULL, row_nms = NULL) { |
|
206 | 398x |
checkmate::assert_character(stats, min.len = 1) |
207 | 398x |
checkmate::assert_character(row_nms, null.ok = TRUE) |
208 |
# It may be a list |
|
209 | 398x |
if (checkmate::test_list(labels_in, null.ok = TRUE)) { |
210 | 334x |
checkmate::assert_list(labels_in, null.ok = TRUE) |
211 |
# Or it may be a vector of characters |
|
212 |
} else { |
|
213 | 64x |
checkmate::assert_character(labels_in, null.ok = TRUE) |
214 |
} |
|
215 | ||
216 | 398x |
if (!is.null(row_nms)) { |
217 | 43x |
ret <- rep(row_nms, length(stats)) |
218 | 43x |
out <- setNames(ret, paste(rep(stats, each = length(row_nms)), ret, sep = ".")) |
219 | ||
220 | 43x |
if (!is.null(labels_in)) { |
221 | 1x |
lvl_lbls <- intersect(names(labels_in), row_nms) |
222 | 1x |
for (i in lvl_lbls) out[paste(stats, i, sep = ".")] <- labels_in[[i]] |
223 |
} |
|
224 |
} else { |
|
225 | 355x |
which_lbl <- match(stats, names(tern_default_labels)) |
226 | ||
227 | 355x |
ret <- vector("character", length = length(stats)) # it needs to be a character vector |
228 | 355x |
ret[!is.na(which_lbl)] <- tern_default_labels[which_lbl[!is.na(which_lbl)]] |
229 | ||
230 | 355x |
out <- setNames(ret, stats) |
231 |
} |
|
232 | ||
233 |
# Modify some with custom labels |
|
234 | 398x |
if (!is.null(labels_in)) { |
235 |
# Stats is the main |
|
236 | 64x |
common_names <- intersect(names(out), names(labels_in)) |
237 | 64x |
out[common_names] <- labels_in[common_names] |
238 |
} |
|
239 | ||
240 | 398x |
out |
241 |
} |
|
242 | ||
243 |
#' @describeIn default_stats_formats_labels Format indent modifiers for a given vector/list of statistics. |
|
244 |
#' |
|
245 |
#' @param indents_in (named `vector`)\cr inserted indent modifiers to replace defaults (default is `0L`). |
|
246 |
#' |
|
247 |
#' @return |
|
248 |
#' * `get_indents_from_stats()` returns a single indent modifier value to apply to all rows |
|
249 |
#' or a named numeric vector of indent modifiers (if present, otherwise `NULL`). |
|
250 |
#' |
|
251 |
#' @examples |
|
252 |
#' get_indents_from_stats(all_cnt_occ, indents_in = 3L) |
|
253 |
#' get_indents_from_stats(all_cnt_occ, indents_in = list(count = 2L, count_fraction = 5L)) |
|
254 |
#' get_indents_from_stats( |
|
255 |
#' all_cnt_occ, |
|
256 |
#' indents_in = list(a = 2L, count.a = 1L, count.b = 5L), row_nms = c("a", "b") |
|
257 |
#' ) |
|
258 |
#' |
|
259 |
#' @export |
|
260 |
get_indents_from_stats <- function(stats, indents_in = NULL, row_nms = NULL) { |
|
261 | 383x |
checkmate::assert_character(stats, min.len = 1) |
262 | 383x |
checkmate::assert_character(row_nms, null.ok = TRUE) |
263 |
# It may be a list |
|
264 | 383x |
if (checkmate::test_list(indents_in, null.ok = TRUE)) { |
265 | 334x |
checkmate::assert_list(indents_in, null.ok = TRUE) |
266 |
# Or it may be a vector of integers |
|
267 |
} else { |
|
268 | 49x |
checkmate::assert_integerish(indents_in, null.ok = TRUE) |
269 |
} |
|
270 | ||
271 | 383x |
if (is.null(names(indents_in)) && length(indents_in) == 1) { |
272 | 8x |
out <- rep(indents_in, length(stats) * if (!is.null(row_nms)) length(row_nms) else 1) |
273 | 8x |
return(out) |
274 |
} |
|
275 | ||
276 | 375x |
if (!is.null(row_nms)) { |
277 | 37x |
ret <- rep(0L, length(stats) * length(row_nms)) |
278 | 37x |
out <- setNames(ret, paste(rep(stats, each = length(row_nms)), rep(row_nms, length(stats)), sep = ".")) |
279 | ||
280 | 37x |
if (!is.null(indents_in)) { |
281 | 1x |
lvl_lbls <- intersect(names(indents_in), row_nms) |
282 | 1x |
for (i in lvl_lbls) out[paste(stats, i, sep = ".")] <- indents_in[[i]] |
283 |
} |
|
284 |
} else { |
|
285 | 338x |
ret <- rep(0L, length(stats)) |
286 | 338x |
out <- setNames(ret, stats) |
287 |
} |
|
288 | ||
289 |
# Modify some with custom labels |
|
290 | 375x |
if (!is.null(indents_in)) { |
291 |
# Stats is the main |
|
292 | 42x |
common_names <- intersect(names(out), names(indents_in)) |
293 | 42x |
out[common_names] <- indents_in[common_names] |
294 |
} |
|
295 | ||
296 | 375x |
out |
297 |
} |
|
298 | ||
299 |
#' Update Labels According to Control Specifications |
|
300 |
#' |
|
301 |
#' @description `r lifecycle::badge("stable")` |
|
302 |
#' |
|
303 |
#' Given a list of statistic labels and and a list of control parameters, updates labels with a relevant |
|
304 |
#' control specification. For example, if control has element `conf_level` set to `0.9`, the default |
|
305 |
#' label for statistic `mean_ci` will be updated to `"Mean 90% CI"`. Any labels that are supplied |
|
306 |
#' via `labels_custom` will not be updated regardless of `control`. |
|
307 |
#' |
|
308 |
#' @param labels_default (named `vector` of `character`)\cr a named vector of statistic labels to modify |
|
309 |
#' according to the control specifications. Labels that are explicitly defined in `labels_custom` will |
|
310 |
#' not be affected. |
|
311 |
#' @param labels_custom (named `vector` of `character`)\cr named vector of labels that are customized by |
|
312 |
#' the user and should not be affected by `control`. |
|
313 |
#' @param control (named `list`)\cr list of control parameters to apply to adjust default labels. |
|
314 |
#' |
|
315 |
#' @return A named character vector of labels with control specifications applied to relevant labels. |
|
316 |
#' |
|
317 |
#' @examples |
|
318 |
#' control <- list(conf_level = 0.80, quantiles = c(0.1, 0.83), test_mean = 0.57) |
|
319 |
#' get_labels_from_stats(c("mean_ci", "quantiles", "mean_pval")) %>% |
|
320 |
#' labels_use_control(control = control) |
|
321 |
#' |
|
322 |
#' @export |
|
323 |
labels_use_control <- function(labels_default, control, labels_custom = NULL) { |
|
324 | 14x |
if ("conf_level" %in% names(control)) { |
325 | 14x |
labels_default <- sapply( |
326 | 14x |
names(labels_default), |
327 | 14x |
function(x) { |
328 | 65x |
if (!x %in% names(labels_custom)) { |
329 | 64x |
gsub(labels_default[[x]], pattern = "[0-9]+% CI", replacement = f_conf_level(control[["conf_level"]])) |
330 |
} else { |
|
331 | 1x |
labels_default[[x]] |
332 |
} |
|
333 |
} |
|
334 |
) |
|
335 |
} |
|
336 | 14x |
if ("quantiles" %in% names(control) && "quantiles" %in% names(labels_default) && |
337 | 14x |
!"quantiles" %in% names(labels_custom)) { # nolint |
338 | 14x |
labels_default["quantiles"] <- gsub( |
339 | 14x |
"[0-9]+% and [0-9]+", paste0(control[["quantiles"]][1] * 100, "% and ", control[["quantiles"]][2] * 100, ""), |
340 | 14x |
labels_default["quantiles"] |
341 |
) |
|
342 |
} |
|
343 | 14x |
if ("test_mean" %in% names(control) && "mean_pval" %in% names(labels_default) && |
344 | 14x |
!"mean_pval" %in% names(labels_custom)) { # nolint |
345 | 1x |
labels_default["mean_pval"] <- gsub( |
346 | 1x |
"p-value \\(H0: mean = [0-9\\.]+\\)", f_pval(control[["test_mean"]]), labels_default["mean_pval"] |
347 |
) |
|
348 |
} |
|
349 | ||
350 | 14x |
labels_default |
351 |
} |
|
352 | ||
353 |
#' @describeIn default_stats_formats_labels Named list of available statistics by method group for `tern`. |
|
354 |
#' |
|
355 |
#' @format |
|
356 |
#' * `tern_default_stats` is a named list of available statistics, with each element |
|
357 |
#' named for their corresponding statistical method group. |
|
358 |
#' |
|
359 |
#' @export |
|
360 |
tern_default_stats <- list( |
|
361 |
abnormal = c("fraction"), |
|
362 |
abnormal_by_baseline = c("fraction"), |
|
363 |
abnormal_by_marked = c("count_fraction", "count_fraction_fixed_dp"), |
|
364 |
abnormal_by_worst_grade = c("count_fraction", "count_fraction_fixed_dp"), |
|
365 |
abnormal_by_worst_grade_worsen = c("fraction"), |
|
366 |
analyze_patients_exposure_in_cols = c("n_patients", "sum_exposure"), |
|
367 |
analyze_vars_counts = c("n", "count", "count_fraction", "count_fraction_fixed_dp", "n_blq"), |
|
368 |
analyze_vars_numeric = c( |
|
369 |
"n", "sum", "mean", "sd", "se", "mean_sd", "mean_se", "mean_ci", "mean_sei", "mean_sdi", "mean_pval", |
|
370 |
"median", "mad", "median_ci", "quantiles", "iqr", "range", "min", "max", "median_range", "cv", |
|
371 |
"geom_mean", "geom_mean_ci", "geom_cv" |
|
372 |
), |
|
373 |
count_cumulative = c("count_fraction", "count_fraction_fixed_dp"), |
|
374 |
count_missed_doses = c("n", "count_fraction", "count_fraction_fixed_dp"), |
|
375 |
count_occurrences = c("count", "count_fraction", "count_fraction_fixed_dp", "fraction"), |
|
376 |
count_occurrences_by_grade = c("count_fraction", "count_fraction_fixed_dp"), |
|
377 |
count_patients_with_event = c("n", "count", "count_fraction", "count_fraction_fixed_dp", "n_blq"), |
|
378 |
count_patients_with_flags = c("n", "count", "count_fraction", "count_fraction_fixed_dp", "n_blq"), |
|
379 |
count_values = c("n", "count", "count_fraction", "count_fraction_fixed_dp", "n_blq"), |
|
380 |
coxph_pairwise = c("pvalue", "hr", "hr_ci", "n_tot", "n_tot_events"), |
|
381 |
estimate_incidence_rate = c("person_years", "n_events", "rate", "rate_ci"), |
|
382 |
estimate_multinomial_response = c("n_prop", "prop_ci"), |
|
383 |
estimate_odds_ratio = c("or_ci", "n_tot"), |
|
384 |
estimate_proportion = c("n_prop", "prop_ci"), |
|
385 |
estimate_proportion_diff = c("diff", "diff_ci"), |
|
386 |
summarize_ancova = c("n", "lsmean", "lsmean_diff", "lsmean_diff_ci", "pval"), |
|
387 |
summarize_coxreg = c("n", "hr", "ci", "pval", "pval_inter"), |
|
388 |
summarize_glm_count = c("n", "rate", "rate_ci", "rate_ratio", "rate_ratio_ci", "pval"), |
|
389 |
summarize_num_patients = c("unique", "nonunique", "unique_count"), |
|
390 |
summarize_patients_events_in_cols = c("unique", "all"), |
|
391 |
surv_time = c("median", "median_ci", "quantiles", "range_censor", "range_event", "range"), |
|
392 |
surv_timepoint = c("pt_at_risk", "event_free_rate", "rate_se", "rate_ci", "rate_diff", "rate_diff_ci", "ztest_pval"), |
|
393 |
tabulate_rsp_biomarkers = c("n_tot", "n_rsp", "prop", "or", "ci", "pval"), |
|
394 |
tabulate_rsp_subgroups = c("n", "n_rsp", "prop", "n_tot", "or", "ci", "pval"), |
|
395 |
tabulate_survival_biomarkers = c("n_tot", "n_tot_events", "median", "hr", "ci", "pval"), |
|
396 |
tabulate_survival_subgroups = c("n_tot_events", "n_events", "n_tot", "n", "median", "hr", "ci", "pval"), |
|
397 |
test_proportion_diff = c("pval") |
|
398 |
) |
|
399 | ||
400 |
#' @describeIn default_stats_formats_labels Named vector of default formats for `tern`. |
|
401 |
#' |
|
402 |
#' @format |
|
403 |
#' * `tern_default_formats` is a named vector of available default formats, with each element |
|
404 |
#' named for their corresponding statistic. |
|
405 |
#' |
|
406 |
#' @export |
|
407 |
tern_default_formats <- c( |
|
408 |
fraction = format_fraction_fixed_dp, |
|
409 |
unique = format_count_fraction_fixed_dp, |
|
410 |
nonunique = "xx", |
|
411 |
unique_count = "xx", |
|
412 |
n = "xx.", |
|
413 |
count = "xx.", |
|
414 |
count_fraction = format_count_fraction, |
|
415 |
count_fraction_fixed_dp = format_count_fraction_fixed_dp, |
|
416 |
n_blq = "xx.", |
|
417 |
sum = "xx.x", |
|
418 |
mean = "xx.x", |
|
419 |
sd = "xx.x", |
|
420 |
se = "xx.x", |
|
421 |
mean_sd = "xx.x (xx.x)", |
|
422 |
mean_se = "xx.x (xx.x)", |
|
423 |
mean_ci = "(xx.xx, xx.xx)", |
|
424 |
mean_sei = "(xx.xx, xx.xx)", |
|
425 |
mean_sdi = "(xx.xx, xx.xx)", |
|
426 |
mean_pval = "xx.xx", |
|
427 |
median = "xx.x", |
|
428 |
mad = "xx.x", |
|
429 |
median_ci = "(xx.xx, xx.xx)", |
|
430 |
quantiles = "xx.x - xx.x", |
|
431 |
iqr = "xx.x", |
|
432 |
range = "xx.x - xx.x", |
|
433 |
min = "xx.x", |
|
434 |
max = "xx.x", |
|
435 |
median_range = "xx.x (xx.x - xx.x)", |
|
436 |
cv = "xx.x", |
|
437 |
geom_mean = "xx.x", |
|
438 |
geom_mean_ci = "(xx.xx, xx.xx)", |
|
439 |
geom_cv = "xx.x", |
|
440 |
pval = "x.xxxx | (<0.0001)", |
|
441 |
pval_counts = "x.xxxx | (<0.0001)", |
|
442 |
range_censor = "xx.x to xx.x", |
|
443 |
range_event = "xx.x to xx.x" |
|
444 |
) |
|
445 | ||
446 |
#' @describeIn default_stats_formats_labels Named `character` vector of default labels for `tern`. |
|
447 |
#' |
|
448 |
#' @format |
|
449 |
#' * `tern_default_labels` is a named `character` vector of available default labels, with each element |
|
450 |
#' named for their corresponding statistic. |
|
451 |
#' |
|
452 |
#' @export |
|
453 |
tern_default_labels <- c( |
|
454 |
fraction = "fraction", |
|
455 |
unique = "Number of patients with at least one event", |
|
456 |
nonunique = "Number of events", |
|
457 |
n = "n", |
|
458 |
count = "count", |
|
459 |
count_fraction = "count_fraction", |
|
460 |
count_fraction_fixed_dp = "count_fraction", |
|
461 |
n_blq = "n_blq", |
|
462 |
sum = "Sum", |
|
463 |
mean = "Mean", |
|
464 |
sd = "SD", |
|
465 |
se = "SE", |
|
466 |
mean_sd = "Mean (SD)", |
|
467 |
mean_se = "Mean (SE)", |
|
468 |
mean_ci = "Mean 95% CI", |
|
469 |
mean_sei = "Mean -/+ 1xSE", |
|
470 |
mean_sdi = "Mean -/+ 1xSD", |
|
471 |
mean_pval = "Mean p-value (H0: mean = 0)", |
|
472 |
median = "Median", |
|
473 |
mad = "Median Absolute Deviation", |
|
474 |
median_ci = "Median 95% CI", |
|
475 |
quantiles = "25% and 75%-ile", |
|
476 |
iqr = "IQR", |
|
477 |
range = "Min - Max", |
|
478 |
min = "Minimum", |
|
479 |
max = "Maximum", |
|
480 |
median_range = "Median (Min - Max)", |
|
481 |
cv = "CV (%)", |
|
482 |
geom_mean = "Geometric Mean", |
|
483 |
geom_mean_ci = "Geometric Mean 95% CI", |
|
484 |
geom_cv = "CV % Geometric Mean", |
|
485 |
pval = "p-value (t-test)", # Default for numeric |
|
486 |
pval_counts = "p-value (chi-squared test)" # Default for counts |
|
487 |
) |
|
488 | ||
489 |
# To deprecate --------- |
|
490 | ||
491 |
#' @describeIn default_stats_formats_labels Quick function to retrieve default formats for summary statistics: |
|
492 |
#' [analyze_vars()] and [analyze_vars_in_cols()] principally. |
|
493 |
#' |
|
494 |
#' @param type (`flag`)\cr is it going to be `"numeric"` or `"counts"`? |
|
495 |
#' |
|
496 |
#' @return |
|
497 |
#' * `summary_formats()` returns a named `vector` of default statistic formats for the given data type. |
|
498 |
#' |
|
499 |
#' @examples |
|
500 |
#' summary_formats() |
|
501 |
#' summary_formats(type = "counts", include_pval = TRUE) |
|
502 |
#' |
|
503 |
#' @export |
|
504 |
summary_formats <- function(type = "numeric", include_pval = FALSE) { |
|
505 | 3x |
met_grp <- paste0(c("analyze_vars", type), collapse = "_") |
506 | 3x |
get_formats_from_stats(get_stats(met_grp, add_pval = include_pval)) |
507 |
} |
|
508 | ||
509 |
#' @describeIn default_stats_formats_labels Quick function to retrieve default labels for summary statistics. |
|
510 |
#' Returns labels of descriptive statistics which are understood by `rtables`. Similar to `summary_formats` |
|
511 |
#' |
|
512 |
#' @param include_pval (`flag`)\cr deprecated parameter. Same as `add_pval`. |
|
513 |
#' @return |
|
514 |
#' * `summary_labels` returns a named `vector` of default statistic labels for the given data type. |
|
515 |
#' |
|
516 |
#' @examples |
|
517 |
#' summary_labels() |
|
518 |
#' summary_labels(type = "counts", include_pval = TRUE) |
|
519 |
#' |
|
520 |
#' @export |
|
521 |
summary_labels <- function(type = "numeric", include_pval = FALSE) { |
|
522 | 3x |
met_grp <- paste0(c("analyze_vars", type), collapse = "_") |
523 | 3x |
get_labels_from_stats(get_stats(met_grp, add_pval = include_pval)) |
524 |
} |
|
525 | ||
526 |
#' @describeIn default_stats_formats_labels `r lifecycle::badge("deprecated")` Function to |
|
527 |
#' configure settings for default or custom summary statistics for a given data type. In |
|
528 |
#' addition to selecting a custom subset of statistics, the user can also set custom |
|
529 |
#' formats, labels, and indent modifiers for any of these statistics. |
|
530 |
#' |
|
531 |
#' @param stats_custom (`named vector` of `character`)\cr vector of statistics to include if |
|
532 |
#' not the defaults. This argument overrides `include_pval` and other custom value arguments |
|
533 |
#' such that only settings for these statistics will be returned. |
|
534 |
#' @param formats_custom (`named vector` of `character`)\cr vector of custom statistics formats |
|
535 |
#' to use in place of the defaults defined in [`summary_formats()`]. Names should be a subset |
|
536 |
#' of the statistics defined in `stats_custom` (or default statistics if this is `NULL`). |
|
537 |
#' @param labels_custom (`named vector` of `character`)\cr vector of custom statistics labels |
|
538 |
#' to use in place of the defaults defined in [`summary_labels()`]. Names should be a subset |
|
539 |
#' of the statistics defined in `stats_custom` (or default statistics if this is `NULL`). |
|
540 |
#' @param indent_mods_custom (`integer` or `named vector` of `integer`)\cr vector of custom |
|
541 |
#' indentation modifiers for statistics to use instead of the default of `0L` for all statistics. |
|
542 |
#' Names should be a subset of the statistics defined in `stats_custom` (or default statistics |
|
543 |
#' if this is `NULL`). Alternatively, the same indentation modifier can be applied to all |
|
544 |
#' statistics by setting `indent_mods_custom` to a single integer value. |
|
545 |
#' |
|
546 |
#' @return |
|
547 |
#' * `summary_custom` returns a `list` of 4 named elements: `stats`, `formats`, `labels`, |
|
548 |
#' and `indent_mods`. |
|
549 |
#' |
|
550 |
#' @examples |
|
551 |
#' summary_custom() |
|
552 |
#' summary_custom(type = "counts", include_pval = TRUE) |
|
553 |
#' summary_custom( |
|
554 |
#' include_pval = TRUE, stats_custom = c("n", "mean", "sd", "pval"), |
|
555 |
#' labels_custom = c(sd = "Std. Dev."), indent_mods_custom = 3L |
|
556 |
#' ) |
|
557 |
#' |
|
558 |
#' @export |
|
559 |
summary_custom <- function(type = "numeric", |
|
560 |
include_pval = FALSE, |
|
561 |
stats_custom = NULL, |
|
562 |
formats_custom = NULL, |
|
563 |
labels_custom = NULL, |
|
564 |
indent_mods_custom = NULL) { |
|
565 | 1x |
lifecycle::deprecate_warn( |
566 | 1x |
"0.9.0.9001", |
567 | 1x |
"summary_custom()", |
568 | 1x |
details = "Please use `get_stats`, `get_formats_from_stats`, and `get_labels_from_stats` directly instead." |
569 |
) |
|
570 | 1x |
met_grp <- paste0(c("analyze_vars", type), collapse = "_") |
571 | 1x |
.stats <- get_stats(met_grp, stats_custom, add_pval = include_pval) |
572 | 1x |
.formats <- get_formats_from_stats(.stats, formats_custom) |
573 | 1x |
.labels <- get_labels_from_stats(.stats, labels_custom) |
574 | 1x |
.indent_mods <- stats::setNames(rep(0L, length(.stats)), .stats) |
575 | ||
576 | 1x |
if (!is.null(indent_mods_custom)) { |
577 | ! |
if (is.null(names(indent_mods_custom)) && length(indent_mods_custom) == 1) { |
578 | ! |
.indent_mods[names(.indent_mods)] <- indent_mods_custom |
579 |
} else { |
|
580 | ! |
.indent_mods[names(indent_mods_custom)] <- indent_mods_custom |
581 |
} |
|
582 |
} |
|
583 | ||
584 | 1x |
list( |
585 | 1x |
stats = .stats, |
586 | 1x |
formats = .formats, |
587 | 1x |
labels = .labels, |
588 | 1x |
indent_mods = .indent_mods[.stats] |
589 |
) |
|
590 |
} |
1 |
#' Combine Factor Levels |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Combine specified old factor Levels in a single new level. |
|
6 |
#' |
|
7 |
#' @param x factor |
|
8 |
#' @param levels level names to be combined |
|
9 |
#' @param new_level name of new level |
|
10 |
#' |
|
11 |
#' @return A `factor` with the new levels. |
|
12 |
#' |
|
13 |
#' @examples |
|
14 |
#' x <- factor(letters[1:5], levels = letters[5:1]) |
|
15 |
#' combine_levels(x, levels = c("a", "b")) |
|
16 |
#' |
|
17 |
#' combine_levels(x, c("e", "b")) |
|
18 |
#' |
|
19 |
#' @export |
|
20 |
combine_levels <- function(x, levels, new_level = paste(levels, collapse = "/")) { |
|
21 | 4x |
checkmate::assert_factor(x) |
22 | 4x |
checkmate::assert_subset(levels, levels(x)) |
23 | ||
24 | 4x |
lvls <- levels(x) |
25 | ||
26 | 4x |
lvls[lvls %in% levels] <- new_level |
27 | ||
28 | 4x |
levels(x) <- lvls |
29 | ||
30 | 4x |
x |
31 |
} |
|
32 | ||
33 |
#' Conversion of a Vector to a Factor |
|
34 |
#' |
|
35 |
#' Converts `x` to a factor and keeps its attributes. Warns appropriately such that the user |
|
36 |
#' can decide whether they prefer converting to factor manually (e.g. for full control of |
|
37 |
#' factor levels). |
|
38 |
#' |
|
39 |
#' @param x (`atomic`)\cr object to convert. |
|
40 |
#' @param x_name (`string`)\cr name of `x`. |
|
41 |
#' @param na_level (`string`)\cr the explicit missing level which should be used when converting a character vector. |
|
42 |
#' @param verbose defaults to `TRUE`. It prints out warnings and messages. |
|
43 |
#' |
|
44 |
#' @return A `factor` with same attributes (except class) as `x`. Does not modify `x` if already a `factor`. |
|
45 |
#' |
|
46 |
#' @keywords internal |
|
47 |
as_factor_keep_attributes <- function(x, |
|
48 |
x_name = deparse(substitute(x)), |
|
49 |
na_level = "<Missing>", |
|
50 |
verbose = TRUE) { |
|
51 | 168x |
checkmate::assert_atomic(x) |
52 | 168x |
checkmate::assert_string(x_name) |
53 | 168x |
checkmate::assert_string(na_level) |
54 | 168x |
checkmate::assert_flag(verbose) |
55 | 168x |
if (is.factor(x)) { |
56 | 153x |
return(x) |
57 |
} |
|
58 | 15x |
x_class <- class(x)[1] |
59 | 15x |
if (verbose) { |
60 | 15x |
warning(paste( |
61 | 15x |
"automatically converting", x_class, "variable", x_name, |
62 | 15x |
"to factor, better manually convert to factor to avoid failures" |
63 |
)) |
|
64 |
} |
|
65 | 15x |
if (identical(length(x), 0L)) { |
66 | 1x |
warning(paste( |
67 | 1x |
x_name, "has length 0, this can lead to tabulation failures, better convert to factor" |
68 |
)) |
|
69 |
} |
|
70 | 15x |
if (is.character(x)) { |
71 | 15x |
x_no_na <- explicit_na(sas_na(x), label = na_level) |
72 | 15x |
if (any(na_level %in% x_no_na)) { |
73 | 3x |
do.call( |
74 | 3x |
structure, |
75 | 3x |
c( |
76 | 3x |
list(.Data = forcats::fct_relevel(x_no_na, na_level, after = Inf)), |
77 | 3x |
attributes(x) |
78 |
) |
|
79 |
) |
|
80 |
} else { |
|
81 | 12x |
do.call(structure, c(list(.Data = as.factor(x)), attributes(x))) |
82 |
} |
|
83 |
} else { |
|
84 | ! |
do.call(structure, c(list(.Data = as.factor(x)), attributes(x))) |
85 |
} |
|
86 |
} |
|
87 | ||
88 |
#' Labels for Bins in Percent |
|
89 |
#' |
|
90 |
#' This creates labels for quantile based bins in percent. This assumes the right-closed |
|
91 |
#' intervals as produced by [cut_quantile_bins()]. |
|
92 |
#' |
|
93 |
#' @param probs (`proportion` vector)\cr the probabilities identifying the quantiles. |
|
94 |
#' This is a sorted vector of unique `proportion` values, i.e. between 0 and 1, where |
|
95 |
#' the boundaries 0 and 1 must not be included. |
|
96 |
#' @param digits (`integer`)\cr number of decimal places to round the percent numbers. |
|
97 |
#' |
|
98 |
#' @return A `character` vector with labels in the format `[0%,20%]`, `(20%,50%]`, etc. |
|
99 |
#' |
|
100 |
#' @keywords internal |
|
101 |
bins_percent_labels <- function(probs, |
|
102 |
digits = 0) { |
|
103 | 1x |
if (isFALSE(0 %in% probs)) probs <- c(0, probs) |
104 | 1x |
if (isFALSE(1 %in% probs)) probs <- c(probs, 1) |
105 | 8x |
checkmate::assert_numeric(probs, lower = 0, upper = 1, unique = TRUE, sorted = TRUE) |
106 | 8x |
percent <- round(probs * 100, digits = digits) |
107 | 8x |
left <- paste0(utils::head(percent, -1), "%") |
108 | 8x |
right <- paste0(utils::tail(percent, -1), "%") |
109 | 8x |
without_left_bracket <- paste0(left, ",", right, "]") |
110 | 8x |
with_left_bracket <- paste0("[", utils::head(without_left_bracket, 1)) |
111 | 8x |
if (length(without_left_bracket) > 1) { |
112 | 6x |
with_left_bracket <- c( |
113 | 6x |
with_left_bracket, |
114 | 6x |
paste0("(", utils::tail(without_left_bracket, -1)) |
115 |
) |
|
116 |
} |
|
117 | 8x |
with_left_bracket |
118 |
} |
|
119 | ||
120 |
#' Cutting Numeric Vector into Empirical Quantile Bins |
|
121 |
#' |
|
122 |
#' @description `r lifecycle::badge("stable")` |
|
123 |
#' |
|
124 |
#' This cuts a numeric vector into sample quantile bins. |
|
125 |
#' |
|
126 |
#' @inheritParams bins_percent_labels |
|
127 |
#' @param x (`numeric`)\cr the continuous variable values which should be cut into |
|
128 |
#' quantile bins. This may contain `NA` values, which are then |
|
129 |
#' not used for the quantile calculations, but included in the return vector. |
|
130 |
#' @param labels (`character`)\cr the unique labels for the quantile bins. When there are `n` |
|
131 |
#' probabilities in `probs`, then this must be `n + 1` long. |
|
132 |
#' @param type (`integer`)\cr type of quantiles to use, see [stats::quantile()] for details. |
|
133 |
#' @param ordered (`flag`)\cr should the result be an ordered factor. |
|
134 |
#' |
|
135 |
#' @return A `factor` variable with appropriately-labeled bins as levels. |
|
136 |
#' |
|
137 |
#' @note Intervals are closed on the right side. That is, the first bin is the interval |
|
138 |
#' `[-Inf, q1]` where `q1` is the first quantile, the second bin is then `(q1, q2]`, etc., |
|
139 |
#' and the last bin is `(qn, +Inf]` where `qn` is the last quantile. |
|
140 |
#' |
|
141 |
#' @examples |
|
142 |
#' # Default is to cut into quartile bins. |
|
143 |
#' cut_quantile_bins(cars$speed) |
|
144 |
#' |
|
145 |
#' # Use custom quantiles. |
|
146 |
#' cut_quantile_bins(cars$speed, probs = c(0.1, 0.2, 0.6, 0.88)) |
|
147 |
#' |
|
148 |
#' # Use custom labels. |
|
149 |
#' cut_quantile_bins(cars$speed, labels = paste0("Q", 1:4)) |
|
150 |
#' |
|
151 |
#' # NAs are preserved in result factor. |
|
152 |
#' ozone_binned <- cut_quantile_bins(airquality$Ozone) |
|
153 |
#' which(is.na(ozone_binned)) |
|
154 |
#' # So you might want to make these explicit. |
|
155 |
#' explicit_na(ozone_binned) |
|
156 |
#' |
|
157 |
#' @export |
|
158 |
cut_quantile_bins <- function(x, |
|
159 |
probs = c(0.25, 0.5, 0.75), |
|
160 |
labels = NULL, |
|
161 |
type = 7, |
|
162 |
ordered = TRUE) { |
|
163 | 8x |
checkmate::assert_flag(ordered) |
164 | 8x |
checkmate::assert_numeric(x) |
165 | 7x |
if (isFALSE(0 %in% probs)) probs <- c(0, probs) |
166 | 7x |
if (isFALSE(1 %in% probs)) probs <- c(probs, 1) |
167 | 8x |
checkmate::assert_numeric(probs, lower = 0, upper = 1, unique = TRUE, sorted = TRUE) |
168 | 7x |
if (is.null(labels)) labels <- bins_percent_labels(probs) |
169 | 8x |
checkmate::assert_character(labels, len = length(probs) - 1, any.missing = FALSE, unique = TRUE) |
170 | ||
171 | 8x |
if (all(is.na(x))) { |
172 |
# Early return if there are only NAs in input. |
|
173 | 1x |
return(factor(x, ordered = ordered, levels = labels)) |
174 |
} |
|
175 | ||
176 | 7x |
quantiles <- stats::quantile( |
177 | 7x |
x, |
178 | 7x |
probs = probs, |
179 | 7x |
type = type, |
180 | 7x |
na.rm = TRUE |
181 |
) |
|
182 | ||
183 | 7x |
checkmate::assert_numeric(quantiles, unique = TRUE) |
184 | ||
185 | 6x |
cut( |
186 | 6x |
x, |
187 | 6x |
breaks = quantiles, |
188 | 6x |
labels = labels, |
189 | 6x |
ordered_result = ordered, |
190 | 6x |
include.lowest = TRUE, |
191 | 6x |
right = TRUE |
192 |
) |
|
193 |
} |
|
194 | ||
195 |
#' Discard Certain Levels from a Factor |
|
196 |
#' |
|
197 |
#' @description `r lifecycle::badge("stable")` |
|
198 |
#' |
|
199 |
#' This discards the observations as well as the levels specified from a factor. |
|
200 |
#' |
|
201 |
#' @param x (`factor`)\cr the original factor. |
|
202 |
#' @param discard (`character`)\cr which levels to discard. |
|
203 |
#' |
|
204 |
#' @return A modified `factor` with observations as well as levels from `discard` dropped. |
|
205 |
#' |
|
206 |
#' @examples |
|
207 |
#' fct_discard(factor(c("a", "b", "c")), "c") |
|
208 |
#' |
|
209 |
#' @export |
|
210 |
fct_discard <- function(x, discard) { |
|
211 | 298x |
checkmate::assert_factor(x) |
212 | 298x |
checkmate::assert_character(discard, any.missing = FALSE) |
213 | 298x |
new_obs <- x[!(x %in% discard)] |
214 | 298x |
new_levels <- setdiff(levels(x), discard) |
215 | 298x |
factor(new_obs, levels = new_levels) |
216 |
} |
|
217 | ||
218 |
#' Insertion of Explicit Missings in a Factor |
|
219 |
#' |
|
220 |
#' @description `r lifecycle::badge("stable")` |
|
221 |
#' |
|
222 |
#' This inserts explicit missings in a factor based on a condition. Additionally, |
|
223 |
#' existing `NA` values will be explicitly converted to given `na_level`. |
|
224 |
#' |
|
225 |
#' @param x (`factor`)\cr the original factor. |
|
226 |
#' @param condition (`logical`)\cr where to insert missings. |
|
227 |
#' @param na_level (`string`)\cr which level to use for missings. |
|
228 |
#' |
|
229 |
#' @return A modified `factor` with inserted and existing `NA` converted to `na_level`. |
|
230 |
#' |
|
231 |
#' @seealso [forcats::fct_na_value_to_level()] which is used internally. |
|
232 |
#' |
|
233 |
#' @examples |
|
234 |
#' fct_explicit_na_if(factor(c("a", "b", NA)), c(TRUE, FALSE, FALSE)) |
|
235 |
#' |
|
236 |
#' @export |
|
237 |
fct_explicit_na_if <- function(x, condition, na_level = "<Missing>") { |
|
238 | 1x |
checkmate::assert_factor(x, len = length(condition)) |
239 | 1x |
checkmate::assert_logical(condition) |
240 | 1x |
x[condition] <- NA |
241 | 1x |
x <- forcats::fct_na_value_to_level(x, level = na_level) |
242 | 1x |
forcats::fct_drop(x, only = na_level) |
243 |
} |
|
244 | ||
245 |
#' Collapsing of Factor Levels and Keeping Only Those New Group Levels |
|
246 |
#' |
|
247 |
#' @description `r lifecycle::badge("stable")` |
|
248 |
#' |
|
249 |
#' This collapses levels and only keeps those new group levels, in the order provided. |
|
250 |
#' The returned factor has levels in the order given, with the possible missing level last (this will |
|
251 |
#' only be included if there are missing values). |
|
252 |
#' |
|
253 |
#' @param .f (`factor` or `character`)\cr original vector. |
|
254 |
#' @param ... (named `character` vectors)\cr levels in each vector provided will be collapsed into |
|
255 |
#' the new level given by the respective name. |
|
256 |
#' @param .na_level (`string`)\cr which level to use for other levels, which should be missing in the |
|
257 |
#' new factor. Note that this level must not be contained in the new levels specified in `...`. |
|
258 |
#' |
|
259 |
#' @return A modified `factor` with collapsed levels. Values and levels which are not included |
|
260 |
#' in the given `character` vector input will be set to the missing level `.na_level`. |
|
261 |
#' |
|
262 |
#' @note Any existing `NA`s in the input vector will not be replaced by the missing level. If needed, |
|
263 |
#' [explicit_na()] can be called separately on the result. |
|
264 |
#' |
|
265 |
#' @seealso [forcats::fct_collapse()], [forcats::fct_relevel()] which are used internally. |
|
266 |
#' |
|
267 |
#' @examples |
|
268 |
#' fct_collapse_only(factor(c("a", "b", "c", "d")), TRT = "b", CTRL = c("c", "d")) |
|
269 |
#' |
|
270 |
#' @export |
|
271 |
fct_collapse_only <- function(.f, ..., .na_level = "<Missing>") { |
|
272 | 4x |
new_lvls <- names(list(...)) |
273 | 4x |
if (checkmate::test_subset(.na_level, new_lvls)) { |
274 | 1x |
stop(paste0(".na_level currently set to '", .na_level, "' must not be contained in the new levels")) |
275 |
} |
|
276 | 3x |
x <- forcats::fct_collapse(.f, ..., other_level = .na_level) |
277 | 3x |
do.call(forcats::fct_relevel, args = c(list(.f = x), as.list(new_lvls))) |
278 |
} |
|
279 | ||
280 |
#' Ungroup Non-Numeric Statistics |
|
281 |
#' |
|
282 |
#' Ungroups grouped non-numeric statistics within input vectors `.formats`, `.labels`, and `.indent_mods`. |
|
283 |
#' |
|
284 |
#' @inheritParams argument_convention |
|
285 |
#' @param x (`named list` of `numeric`)\cr list of numeric statistics containing the statistics to ungroup. |
|
286 |
#' |
|
287 |
#' @return A `list` with modified elements `x`, `.formats`, `.labels`, and `.indent_mods`. |
|
288 |
#' |
|
289 |
#' @seealso [a_summary()] which uses this function internally. |
|
290 |
#' |
|
291 |
#' @keywords internal |
|
292 |
ungroup_stats <- function(x, |
|
293 |
.formats, |
|
294 |
.labels, |
|
295 |
.indent_mods) { |
|
296 | 273x |
checkmate::assert_list(x) |
297 | 273x |
empty_pval <- "pval" %in% names(x) && length(x[["pval"]]) == 0 |
298 | 273x |
empty_pval_counts <- "pval_counts" %in% names(x) && length(x[["pval_counts"]]) == 0 |
299 | 273x |
x <- unlist(x, recursive = FALSE) |
300 | ||
301 |
# If p-value is empty it is removed by unlist and needs to be re-added |
|
302 | ! |
if (empty_pval) x[["pval"]] <- character() |
303 | 3x |
if (empty_pval_counts) x[["pval_counts"]] <- character() |
304 | 273x |
.stats <- names(x) |
305 | ||
306 |
# Ungroup stats |
|
307 | 273x |
.formats <- lapply(.stats, function(x) { |
308 | 2246x |
.formats[[if (!grepl("\\.", x)) x else regmatches(x, regexpr("\\.", x), invert = TRUE)[[1]][1]]] |
309 |
}) |
|
310 | 273x |
.indent_mods <- sapply(.stats, function(x) { |
311 | 2246x |
.indent_mods[[if (!grepl("\\.", x)) x else regmatches(x, regexpr("\\.", x), invert = TRUE)[[1]][1]]] |
312 |
}) |
|
313 | 273x |
.labels <- sapply(.stats, function(x) { |
314 | 2189x |
if (!grepl("\\.", x)) .labels[[x]] else regmatches(x, regexpr("\\.", x), invert = TRUE)[[1]][2] |
315 |
}) |
|
316 | ||
317 | 273x |
list( |
318 | 273x |
x = x, |
319 | 273x |
.formats = .formats, |
320 | 273x |
.labels = .labels, |
321 | 273x |
.indent_mods = .indent_mods |
322 |
) |
|
323 |
} |
1 |
#' Additional Assertions for `checkmate` |
|
2 |
#' |
|
3 |
#' Additional assertion functions which can be used together with the `checkmate` package. |
|
4 |
#' |
|
5 |
#' @inheritParams checkmate::assert_factor |
|
6 |
#' @param x (`any`)\cr object to test. |
|
7 |
#' @param df (`data.frame`)\cr data set to test. |
|
8 |
#' @param variables (named `list` of `character`)\cr list of variables to test. |
|
9 |
#' @param include_boundaries (`logical`)\cr whether to include boundaries when testing |
|
10 |
#' for proportions. |
|
11 |
#' @param na_level (`character`)\cr the string you have been using to represent NA or |
|
12 |
#' missing data. For `NA` values please consider using directly [is.na()] or |
|
13 |
#' similar approaches. |
|
14 |
#' |
|
15 |
#' @return Nothing if assertion passes, otherwise prints the error message. |
|
16 |
#' |
|
17 |
#' @name assertions |
|
18 |
NULL |
|
19 | ||
20 |
check_list_of_variables <- function(x) { |
|
21 |
# drop NULL elements in list |
|
22 | 2376x |
x <- Filter(Negate(is.null), x) |
23 | ||
24 | 2376x |
res <- checkmate::check_list(x, |
25 | 2376x |
names = "named", |
26 | 2376x |
min.len = 1, |
27 | 2376x |
any.missing = FALSE, |
28 | 2376x |
types = "character" |
29 |
) |
|
30 |
# no empty strings allowed |
|
31 | 2376x |
if (isTRUE(res)) { |
32 | 2371x |
res <- checkmate::check_character(unlist(x), min.chars = 1) |
33 |
} |
|
34 | 2376x |
return(res) |
35 |
} |
|
36 |
#' @describeIn assertions Checks whether `x` is a valid list of variable names. |
|
37 |
#' `NULL` elements of the list `x` are dropped with `Filter(Negate(is.null), x)`. |
|
38 |
#' |
|
39 |
#' @keywords internal |
|
40 |
assert_list_of_variables <- checkmate::makeAssertionFunction(check_list_of_variables) |
|
41 | ||
42 |
check_df_with_variables <- function(df, variables, na_level = NULL) { |
|
43 | 2117x |
checkmate::assert_data_frame(df) |
44 | 2115x |
assert_list_of_variables(variables) |
45 | ||
46 |
# flag for equal variables and column names |
|
47 | 2113x |
err_flag <- all(unlist(variables) %in% colnames(df)) |
48 | 2113x |
checkmate::assert_flag(err_flag) |
49 | ||
50 | 2113x |
if (isFALSE(err_flag)) { |
51 | 5x |
vars <- setdiff(unlist(variables), colnames(df)) |
52 | 5x |
return(paste( |
53 | 5x |
deparse(substitute(df)), |
54 | 5x |
"does not contain all specified variables as column names. Missing from dataframe:", |
55 | 5x |
paste(vars, collapse = ", ") |
56 |
)) |
|
57 |
} |
|
58 |
# checking if na_level is present and in which column |
|
59 | 2108x |
if (!is.null(na_level)) { |
60 | 9x |
checkmate::assert_string(na_level) |
61 | 9x |
res <- unlist(lapply(as.list(df)[unlist(variables)], function(x) any(x == na_level))) |
62 | 9x |
if (any(res)) { |
63 | 1x |
return(paste0( |
64 | 1x |
deparse(substitute(df)), " contains explicit na_level (", na_level, |
65 | 1x |
") in the following columns: ", paste0(unlist(variables)[res], |
66 | 1x |
collapse = ", " |
67 |
) |
|
68 |
)) |
|
69 |
} |
|
70 |
} |
|
71 | 2107x |
return(TRUE) |
72 |
} |
|
73 |
#' @describeIn assertions Check whether `df` is a data frame with the analysis `variables`. |
|
74 |
#' Please notice how this produces an error when not all variables are present in the |
|
75 |
#' data.frame while the opposite is not required. |
|
76 |
#' |
|
77 |
#' @keywords internal |
|
78 |
assert_df_with_variables <- checkmate::makeAssertionFunction(check_df_with_variables) |
|
79 | ||
80 |
check_valid_factor <- function(x, |
|
81 |
min.levels = 1, # nolint |
|
82 |
max.levels = NULL, # nolint |
|
83 |
null.ok = TRUE, # nolint |
|
84 |
any.missing = TRUE, # nolint |
|
85 |
n.levels = NULL, # nolint |
|
86 |
len = NULL) { |
|
87 |
# checks on levels insertion |
|
88 | 897x |
checkmate::assert_int(min.levels, lower = 1) |
89 | ||
90 |
# main factor check |
|
91 | 897x |
res <- checkmate::check_factor(x, |
92 | 897x |
min.levels = min.levels, |
93 | 897x |
null.ok = null.ok, |
94 | 897x |
max.levels = max.levels, |
95 | 897x |
any.missing = any.missing, |
96 | 897x |
n.levels = n.levels |
97 |
) |
|
98 | ||
99 |
# no empty strings allowed |
|
100 | 897x |
if (isTRUE(res)) { |
101 | 883x |
res <- checkmate::check_character(levels(x), min.chars = 1) |
102 |
} |
|
103 | ||
104 | 897x |
return(res) |
105 |
} |
|
106 |
#' @describeIn assertions Check whether `x` is a valid factor (i.e. has levels and no empty |
|
107 |
#' string levels). Note that `NULL` and `NA` elements are allowed. |
|
108 |
#' |
|
109 |
#' @keywords internal |
|
110 |
assert_valid_factor <- checkmate::makeAssertionFunction(check_valid_factor) |
|
111 | ||
112 | ||
113 |
check_df_with_factors <- function(df, |
|
114 |
variables, |
|
115 |
min.levels = 1, # nolint |
|
116 |
max.levels = NULL, # nolint |
|
117 |
any.missing = TRUE, # nolint |
|
118 |
na_level = NULL) { |
|
119 | 206x |
res <- check_df_with_variables(df, variables, na_level) |
120 |
# checking if all the columns specified by variables are valid factors |
|
121 | 205x |
if (isTRUE(res)) { |
122 |
# searching the data.frame with selected columns (variables) as a list |
|
123 | 203x |
res <- lapply( |
124 | 203x |
X = as.list(df)[unlist(variables)], |
125 | 203x |
FUN = check_valid_factor, |
126 | 203x |
min.levels = min.levels, |
127 | 203x |
max.levels = max.levels, |
128 | 203x |
any.missing = any.missing |
129 |
) |
|
130 | 203x |
res_lo <- unlist(vapply(res, Negate(isTRUE), logical(1))) |
131 | 203x |
if (any(res_lo)) { |
132 | 6x |
return(paste0( |
133 | 6x |
deparse(substitute(df)), " does not contain only factor variables among:", |
134 | 6x |
"\n* Column `", paste0(unlist(variables)[res_lo], |
135 | 6x |
"` of the data.frame -> ", res[res_lo], |
136 | 6x |
collapse = "\n* " |
137 |
) |
|
138 |
)) |
|
139 |
} else { |
|
140 | 197x |
res <- TRUE |
141 |
} |
|
142 |
} |
|
143 | 199x |
return(res) |
144 |
} |
|
145 |
#' @describeIn assertions Check whether `df` is a data frame where the analysis `variables` |
|
146 |
#' are all factors. Note that the creation of `NA` by direct call of `factor()` will |
|
147 |
#' trim `NA` levels out of the vector list itself. |
|
148 |
#' |
|
149 |
#' @keywords internal |
|
150 |
assert_df_with_factors <- checkmate::makeAssertionFunction(check_df_with_factors) |
|
151 | ||
152 |
#' @describeIn assertions Check whether `x` is a proportion: number between 0 and 1. |
|
153 |
#' |
|
154 |
#' @keywords internal |
|
155 |
assert_proportion_value <- function(x, include_boundaries = FALSE) { |
|
156 | 7476x |
checkmate::assert_number(x, lower = 0, upper = 1) |
157 | 7464x |
checkmate::assert_flag(include_boundaries) |
158 | 7464x |
if (isFALSE(include_boundaries)) { |
159 | 3407x |
checkmate::assert_true(x > 0) |
160 | 3405x |
checkmate::assert_true(x < 1) |
161 |
} |
|
162 |
} |
1 |
#' Horizontal Waterfall Plot |
|
2 |
#' |
|
3 |
#' This basic waterfall plot visualizes a quantity `height` ordered by value with some markup. |
|
4 |
#' |
|
5 |
#' @description `r lifecycle::badge("stable")` |
|
6 |
#' |
|
7 |
#' @param height (`numeric``)\cr vector containing values to be plotted as the waterfall bars. |
|
8 |
#' @param id (`character`)\cr vector containing IDs to use as the x-axis label for the waterfall bars. |
|
9 |
#' @param col (`character`)\cr colors. |
|
10 |
#' @param col_var (`factor`, `character` or `NULL`)\cr categorical variable for bar coloring. `NULL` by default. |
|
11 |
#' @param xlab (`character`)\cr x label. Default is `"ID"`. |
|
12 |
#' @param ylab (`character`)\cr y label. Default is `"Value"`. |
|
13 |
#' @param title (`character`)\cr text to be displayed as plot title. |
|
14 |
#' @param col_legend_title (`character`)\cr text to be displayed as legend title. |
|
15 |
#' |
|
16 |
#' @return A `ggplot` waterfall plot. |
|
17 |
#' |
|
18 |
#' @examples |
|
19 |
#' library(dplyr) |
|
20 |
#' library(nestcolor) |
|
21 |
#' |
|
22 |
#' g_waterfall(height = c(3, 5, -1), id = letters[1:3]) |
|
23 |
#' |
|
24 |
#' g_waterfall( |
|
25 |
#' height = c(3, 5, -1), |
|
26 |
#' id = letters[1:3], |
|
27 |
#' col_var = letters[1:3] |
|
28 |
#' ) |
|
29 |
#' |
|
30 |
#' adsl_f <- tern_ex_adsl %>% |
|
31 |
#' select(USUBJID, STUDYID, ARM, ARMCD, SEX) |
|
32 |
#' |
|
33 |
#' adrs_f <- tern_ex_adrs %>% |
|
34 |
#' filter(PARAMCD == "OVRINV") %>% |
|
35 |
#' mutate(pchg = rnorm(n(), 10, 50)) |
|
36 |
#' |
|
37 |
#' adrs_f <- head(adrs_f, 30) |
|
38 |
#' adrs_f <- adrs_f[!duplicated(adrs_f$USUBJID), ] |
|
39 |
#' head(adrs_f) |
|
40 |
#' |
|
41 |
#' g_waterfall( |
|
42 |
#' height = adrs_f$pchg, |
|
43 |
#' id = adrs_f$USUBJID, |
|
44 |
#' col_var = adrs_f$AVALC |
|
45 |
#' ) |
|
46 |
#' |
|
47 |
#' g_waterfall( |
|
48 |
#' height = adrs_f$pchg, |
|
49 |
#' id = paste("asdfdsfdsfsd", adrs_f$USUBJID), |
|
50 |
#' col_var = adrs_f$SEX |
|
51 |
#' ) |
|
52 |
#' |
|
53 |
#' g_waterfall( |
|
54 |
#' height = adrs_f$pchg, |
|
55 |
#' id = paste("asdfdsfdsfsd", adrs_f$USUBJID), |
|
56 |
#' xlab = "ID", |
|
57 |
#' ylab = "Percentage Change", |
|
58 |
#' title = "Waterfall plot" |
|
59 |
#' ) |
|
60 |
#' |
|
61 |
#' @export |
|
62 |
g_waterfall <- function(height, |
|
63 |
id, |
|
64 |
col_var = NULL, |
|
65 |
col = getOption("ggplot2.discrete.colour"), |
|
66 |
xlab = NULL, |
|
67 |
ylab = NULL, |
|
68 |
col_legend_title = NULL, |
|
69 |
title = NULL) { |
|
70 | 2x |
if (!is.null(col_var)) { |
71 | 1x |
check_same_n(height = height, id = id, col_var = col_var) |
72 |
} else { |
|
73 | 1x |
check_same_n(height = height, id = id) |
74 |
} |
|
75 | ||
76 | 2x |
checkmate::assert_multi_class(col_var, c("character", "factor"), null.ok = TRUE) |
77 | 2x |
checkmate::assert_character(col, null.ok = TRUE) |
78 | ||
79 | 2x |
xlabel <- deparse(substitute(id)) |
80 | 2x |
ylabel <- deparse(substitute(height)) |
81 | ||
82 | 2x |
col_label <- if (!missing(col_var)) { |
83 | 1x |
deparse(substitute(col_var)) |
84 |
} |
|
85 | ||
86 | 2x |
xlab <- if (is.null(xlab)) xlabel else xlab |
87 | 2x |
ylab <- if (is.null(ylab)) ylabel else ylab |
88 | 2x |
col_legend_title <- if (is.null(col_legend_title)) col_label else col_legend_title |
89 | ||
90 | 2x |
plot_data <- data.frame( |
91 | 2x |
height = height, |
92 | 2x |
id = as.character(id), |
93 | 2x |
col_var = if (is.null(col_var)) "x" else to_n(col_var, length(height)), |
94 | 2x |
stringsAsFactors = FALSE |
95 |
) |
|
96 | ||
97 | 2x |
plot_data_ord <- plot_data[order(plot_data$height, decreasing = TRUE), ] |
98 | ||
99 | 2x |
p <- ggplot2::ggplot(plot_data_ord, ggplot2::aes(x = factor(id, levels = id), y = height)) + |
100 | 2x |
ggplot2::geom_col() + |
101 | 2x |
ggplot2::geom_text( |
102 | 2x |
label = format(plot_data_ord$height, digits = 2), |
103 | 2x |
vjust = ifelse(plot_data_ord$height >= 0, -0.5, 1.5) |
104 |
) + |
|
105 | 2x |
ggplot2::xlab(xlab) + |
106 | 2x |
ggplot2::ylab(ylab) + |
107 | 2x |
ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 90, hjust = 0, vjust = .5)) |
108 | ||
109 | 2x |
if (!is.null(col_var)) { |
110 | 1x |
p <- p + |
111 | 1x |
ggplot2::aes(fill = col_var) + |
112 | 1x |
ggplot2::labs(fill = col_legend_title) + |
113 | 1x |
ggplot2::theme( |
114 | 1x |
legend.position = "bottom", |
115 | 1x |
legend.background = ggplot2::element_blank(), |
116 | 1x |
legend.title = ggplot2::element_text(face = "bold"), |
117 | 1x |
legend.box.background = ggplot2::element_rect(colour = "black") |
118 |
) |
|
119 |
} |
|
120 | ||
121 | 2x |
if (!is.null(col)) { |
122 | 1x |
p <- p + |
123 | 1x |
ggplot2::scale_fill_manual(values = col) |
124 |
} |
|
125 | ||
126 | 2x |
if (!is.null(title)) { |
127 | 1x |
p <- p + |
128 | 1x |
ggplot2::labs(title = title) + |
129 | 1x |
ggplot2::theme(plot.title = ggplot2::element_text(face = "bold")) |
130 |
} |
|
131 | ||
132 | 2x |
p |
133 |
} |
1 |
#' Apply 1/3 or 1/2 Imputation Rule to Data |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' @inheritParams argument_convention |
|
6 |
#' @param x_stats (`named list`)\cr a named list of statistics, typically the results of [s_summary()]. |
|
7 |
#' @param stat (`character`)\cr statistic to return the value/NA level of according to the imputation |
|
8 |
#' rule applied. |
|
9 |
#' @param imp_rule (`character`)\cr imputation rule setting. Set to `"1/3"` to implement 1/3 imputation |
|
10 |
#' rule or `"1/2"` to implement 1/2 imputation rule. |
|
11 |
#' @param post (`flag`)\cr whether the data corresponds to a post-dose time-point (defaults to `FALSE`). |
|
12 |
#' This parameter is only used when `imp_rule` is set to `"1/3"`. |
|
13 |
#' @param avalcat_var (`character`)\cr name of variable that indicates whether a row in `df` corresponds |
|
14 |
#' to an analysis value in category `"BLQ"`, `"LTR"`, `"<PCLLOQ"`, or none of the above |
|
15 |
#' (defaults to `"AVALCAT1"`). Variable `avalcat_var` must be present in `df`. |
|
16 |
#' |
|
17 |
#' @return A `list` containing statistic value (`val`) and NA level (`na_str`) that should be displayed |
|
18 |
#' according to the specified imputation rule. |
|
19 |
#' |
|
20 |
#' @seealso [analyze_vars_in_cols()] where this function can be implemented by setting the `imp_rule` |
|
21 |
#' argument. |
|
22 |
#' |
|
23 |
#' @examples |
|
24 |
#' set.seed(1) |
|
25 |
#' df <- data.frame( |
|
26 |
#' AVAL = runif(50, 0, 1), |
|
27 |
#' AVALCAT1 = sample(c(1, "BLQ"), 50, replace = TRUE) |
|
28 |
#' ) |
|
29 |
#' x_stats <- s_summary(df$AVAL) |
|
30 |
#' imputation_rule(df, x_stats, "max", "1/3") |
|
31 |
#' imputation_rule(df, x_stats, "geom_mean", "1/3") |
|
32 |
#' imputation_rule(df, x_stats, "mean", "1/2") |
|
33 |
#' |
|
34 |
#' @export |
|
35 |
imputation_rule <- function(df, x_stats, stat, imp_rule, post = FALSE, avalcat_var = "AVALCAT1") { |
|
36 | 42x |
checkmate::assert_choice(avalcat_var, names(df)) |
37 | 42x |
checkmate::assert_choice(imp_rule, c("1/3", "1/2")) |
38 | 42x |
n_blq <- sum(grepl("BLQ|LTR|<[1-9]|<PCLLOQ", df[[avalcat_var]])) |
39 | 42x |
ltr_blq_ratio <- n_blq / max(1, nrow(df)) |
40 | ||
41 |
# defaults |
|
42 | 42x |
val <- x_stats[[stat]] |
43 | 42x |
na_str <- "NE" |
44 | ||
45 | 42x |
if (imp_rule == "1/3") { |
46 | 1x |
if (!post && stat == "geom_mean") val <- NA # 1/3_pre_LT, 1/3_pre_GT |
47 | 41x |
if (ltr_blq_ratio > 1 / 3) { |
48 | 29x |
if (stat != "geom_mean") na_str <- "ND" # 1/3_pre_GT, 1/3_post_GT |
49 | 4x |
if (!post && !stat %in% c("median", "max")) val <- NA # 1/3_pre_GT |
50 | 18x |
if (post && !stat %in% c("median", "max", "geom_mean")) val <- NA # 1/3_post_GT |
51 |
} |
|
52 | 1x |
} else if (imp_rule == "1/2") { |
53 | 1x |
if (ltr_blq_ratio > 1 / 2 && !stat == "max") { |
54 | ! |
val <- NA # 1/2_GT |
55 | ! |
na_str <- "ND" # 1/2_GT |
56 |
} |
|
57 |
} |
|
58 | ||
59 | 42x |
list(val = val, na_str = na_str) |
60 |
} |
1 |
#' Helper Function to create a new `SMQ` variable in `ADAE` by stacking `SMQ` and/or `CQ` records. |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Helper Function to create a new `SMQ` variable in `ADAE` that consists of all adverse events belonging to |
|
6 |
#' selected Standardized/Customized queries. The new dataset will only contain records of the adverse events |
|
7 |
#' belonging to any of the selected baskets. Remember that `na_str` must match the needed pre-processing |
|
8 |
#' done with [df_explicit_na()] to have the desired output. |
|
9 |
#' |
|
10 |
#' @inheritParams argument_convention |
|
11 |
#' @param baskets (`character`)\cr variable names of the selected Standardized/Customized queries. |
|
12 |
#' @param smq_varlabel (`string`)\cr a label for the new variable created. |
|
13 |
#' @param keys (`character`)\cr names of the key variables to be returned along with the new variable created. |
|
14 |
#' @param aag_summary (`data.frame`)\cr containing the `SMQ` baskets and the levels of interest for the final `SMQ` |
|
15 |
#' variable. This is useful when there are some levels of interest that are not observed in the `df` dataset. |
|
16 |
#' The two columns of this dataset should be named `basket` and `basket_name`. |
|
17 |
#' |
|
18 |
#' @return `data.frame` with variables in `keys` taken from `df` and new variable `SMQ` containing |
|
19 |
#' records belonging to the baskets selected via the `baskets` argument. |
|
20 |
#' |
|
21 |
#' @examples |
|
22 |
#' adae <- tern_ex_adae[1:20, ] %>% df_explicit_na() |
|
23 |
#' h_stack_by_baskets(df = adae) |
|
24 |
#' |
|
25 |
#' aag <- data.frame( |
|
26 |
#' NAMVAR = c("CQ01NAM", "CQ02NAM", "SMQ01NAM", "SMQ02NAM"), |
|
27 |
#' REFNAME = c( |
|
28 |
#' "D.2.1.5.3/A.1.1.1.1 AESI", "X.9.9.9.9/Y.8.8.8.8 AESI", |
|
29 |
#' "C.1.1.1.3/B.2.2.3.1 AESI", "C.1.1.1.3/B.3.3.3.3 AESI" |
|
30 |
#' ), |
|
31 |
#' SCOPE = c("", "", "BROAD", "BROAD"), |
|
32 |
#' stringsAsFactors = FALSE |
|
33 |
#' ) |
|
34 |
#' |
|
35 |
#' basket_name <- character(nrow(aag)) |
|
36 |
#' cq_pos <- grep("^(CQ).+NAM$", aag$NAMVAR) |
|
37 |
#' smq_pos <- grep("^(SMQ).+NAM$", aag$NAMVAR) |
|
38 |
#' basket_name[cq_pos] <- aag$REFNAME[cq_pos] |
|
39 |
#' basket_name[smq_pos] <- paste0( |
|
40 |
#' aag$REFNAME[smq_pos], "(", aag$SCOPE[smq_pos], ")" |
|
41 |
#' ) |
|
42 |
#' |
|
43 |
#' aag_summary <- data.frame( |
|
44 |
#' basket = aag$NAMVAR, |
|
45 |
#' basket_name = basket_name, |
|
46 |
#' stringsAsFactors = TRUE |
|
47 |
#' ) |
|
48 |
#' |
|
49 |
#' result <- h_stack_by_baskets(df = adae, aag_summary = aag_summary) |
|
50 |
#' all(levels(aag_summary$basket_name) %in% levels(result$SMQ)) |
|
51 |
#' |
|
52 |
#' h_stack_by_baskets( |
|
53 |
#' df = adae, |
|
54 |
#' aag_summary = NULL, |
|
55 |
#' keys = c("STUDYID", "USUBJID", "AEDECOD", "ARM"), |
|
56 |
#' baskets = "SMQ01NAM" |
|
57 |
#' ) |
|
58 |
#' |
|
59 |
#' @export |
|
60 |
h_stack_by_baskets <- function(df, |
|
61 |
baskets = grep("^(SMQ|CQ).+NAM$", names(df), value = TRUE), |
|
62 |
smq_varlabel = "Standardized MedDRA Query", |
|
63 |
keys = c("STUDYID", "USUBJID", "ASTDTM", "AEDECOD", "AESEQ"), |
|
64 |
aag_summary = NULL, |
|
65 |
na_level = lifecycle::deprecated(), |
|
66 |
na_str = "<Missing>") { |
|
67 | 5x |
if (lifecycle::is_present(na_level)) { |
68 | ! |
lifecycle::deprecate_warn("0.9.1", "h_stack_by_baskets(na_level)", "h_stack_by_baskets(na_str)") |
69 | ! |
na_str <- na_level |
70 |
} |
|
71 | ||
72 | 5x |
smq_nam <- baskets[startsWith(baskets, "SMQ")] |
73 |
# SC corresponding to NAM |
|
74 | 5x |
smq_sc <- gsub(pattern = "NAM", replacement = "SC", x = smq_nam, fixed = TRUE) |
75 | 5x |
smq <- stats::setNames(smq_sc, smq_nam) |
76 | ||
77 | 5x |
checkmate::assert_character(baskets) |
78 | 5x |
checkmate::assert_string(smq_varlabel) |
79 | 5x |
checkmate::assert_data_frame(df) |
80 | 5x |
checkmate::assert_true(all(startsWith(baskets, "SMQ") | startsWith(baskets, "CQ"))) |
81 | 4x |
checkmate::assert_true(all(endsWith(baskets, "NAM"))) |
82 | 3x |
checkmate::assert_subset(baskets, names(df)) |
83 | 3x |
checkmate::assert_subset(keys, names(df)) |
84 | 3x |
checkmate::assert_subset(smq_sc, names(df)) |
85 | 3x |
checkmate::assert_string(na_str) |
86 | ||
87 | 3x |
if (!is.null(aag_summary)) { |
88 | 1x |
assert_df_with_variables( |
89 | 1x |
df = aag_summary, |
90 | 1x |
variables = list(val = c("basket", "basket_name")) |
91 |
) |
|
92 |
# Warning in case there is no match between `aag_summary$basket` and `baskets` argument. |
|
93 |
# Honestly, I think those should completely match. Target baskets should be the same. |
|
94 | 1x |
if (length(intersect(baskets, unique(aag_summary$basket))) == 0) { |
95 | ! |
warning("There are 0 baskets in common between aag_summary$basket and `baskets` argument.") |
96 |
} |
|
97 |
} |
|
98 | ||
99 | 3x |
var_labels <- c(formatters::var_labels(df[, keys]), "SMQ" = smq_varlabel) |
100 | ||
101 |
# convert `na_str` records from baskets to NA for the later loop and from wide to long steps |
|
102 | 3x |
df[, c(baskets, smq_sc)][df[, c(baskets, smq_sc)] == na_str] <- NA |
103 | ||
104 | 3x |
if (all(is.na(df[, baskets]))) { # in case there is no level for the target baskets |
105 | 1x |
df_long <- df[-seq_len(nrow(df)), keys] # we just need an empty dataframe keeping all factor levels |
106 |
} else { |
|
107 |
# Concatenate SMQxxxNAM with corresponding SMQxxxSC |
|
108 | 2x |
df_cnct <- df[, c(keys, baskets[startsWith(baskets, "CQ")])] |
109 | ||
110 | 2x |
for (nam in names(smq)) { |
111 | 4x |
sc <- smq[nam] # SMQxxxSC corresponding to SMQxxxNAM |
112 | 4x |
nam_notna <- !is.na(df[[nam]]) |
113 | 4x |
new_colname <- paste(nam, sc, sep = "_") |
114 | 4x |
df_cnct[nam_notna, new_colname] <- paste0(df[[nam]], "(", df[[sc]], ")")[nam_notna] |
115 |
} |
|
116 | ||
117 | 2x |
df_cnct$unique_id <- seq(1, nrow(df_cnct)) |
118 | 2x |
var_cols <- names(df_cnct)[!(names(df_cnct) %in% c(keys, "unique_id"))] |
119 |
# have to convert df_cnct from tibble to dataframe |
|
120 |
# as it throws a warning otherwise about rownames. |
|
121 |
# tibble do not support rownames and reshape creates rownames |
|
122 | ||
123 | 2x |
df_long <- stats::reshape( |
124 | 2x |
data = as.data.frame(df_cnct), |
125 | 2x |
varying = var_cols, |
126 | 2x |
v.names = "SMQ", |
127 | 2x |
idvar = names(df_cnct)[names(df_cnct) %in% c(keys, "unique_id")], |
128 | 2x |
direction = "long", |
129 | 2x |
new.row.names = seq(prod(length(var_cols), nrow(df_cnct))) |
130 |
) |
|
131 | ||
132 | 2x |
df_long <- df_long[!is.na(df_long[, "SMQ"]), !(names(df_long) %in% c("time", "unique_id"))] |
133 | 2x |
df_long$SMQ <- as.factor(df_long$SMQ) |
134 |
} |
|
135 | ||
136 | 3x |
smq_levels <- setdiff(levels(df_long[["SMQ"]]), na_str) |
137 | ||
138 | 3x |
if (!is.null(aag_summary)) { |
139 |
# A warning in case there is no match between df and aag_summary records |
|
140 | 1x |
if (length(intersect(smq_levels, unique(aag_summary$basket_name))) == 0) { |
141 | 1x |
warning("There are 0 basket levels in common between aag_summary$basket_name and df.") |
142 |
} |
|
143 | 1x |
df_long[["SMQ"]] <- factor( |
144 | 1x |
df_long[["SMQ"]], |
145 | 1x |
levels = sort( |
146 | 1x |
c( |
147 | 1x |
smq_levels, |
148 | 1x |
setdiff(unique(aag_summary$basket_name), smq_levels) |
149 |
) |
|
150 |
) |
|
151 |
) |
|
152 |
} else { |
|
153 | 2x |
all_na_basket_flag <- vapply(df[, baskets], function(x) { |
154 | 6x |
all(is.na(x)) |
155 | 2x |
}, FUN.VALUE = logical(1)) |
156 | 2x |
all_na_basket <- baskets[all_na_basket_flag] |
157 | ||
158 | 2x |
df_long[["SMQ"]] <- factor( |
159 | 2x |
df_long[["SMQ"]], |
160 | 2x |
levels = sort(c(smq_levels, all_na_basket)) |
161 |
) |
|
162 |
} |
|
163 | 3x |
formatters::var_labels(df_long) <- var_labels |
164 | 3x |
tibble::tibble(df_long) |
165 |
} |
1 |
#' Patient Counts with Abnormal Range Values by Baseline Status |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Primary analysis variable `.var` indicates the abnormal range result (`character` or `factor`), and additional |
|
6 |
#' analysis variables are `id` (`character` or `factor`) and `baseline` (`character` or `factor`). For each |
|
7 |
#' direction specified in `abnormal` (e.g. high or low) we condition on baseline range result and count |
|
8 |
#' patients in the numerator and denominator as follows: |
|
9 |
#' * `Not <Abnormal>` |
|
10 |
#' * `denom`: the number of patients without abnormality at baseline (excluding those with missing baseline) |
|
11 |
#' * `num`: the number of patients in `denom` who also have at least one abnormality post-baseline |
|
12 |
#' * `<Abnormal>` |
|
13 |
#' * `denom`: the number of patients with abnormality at baseline |
|
14 |
#' * `num`: the number of patients in `denom` who also have at least one abnormality post-baseline |
|
15 |
#' * `Total` |
|
16 |
#' * `denom`: the number of patients with at least one valid measurement post-baseline |
|
17 |
#' * `num`: the number of patients in `denom` who also have at least one abnormality post-baseline |
|
18 |
#' |
|
19 |
#' @inheritParams argument_convention |
|
20 |
#' @param abnormal (`character`)\cr identifying the abnormal range level(s) in `.var`. |
|
21 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("abnormal_by_baseline")` |
|
22 |
#' to see available statistics for this function. |
|
23 |
#' |
|
24 |
#' @note |
|
25 |
#' * `df` should be filtered to include only post-baseline records. |
|
26 |
#' * If the baseline variable or analysis variable contains `NA`, it is expected that `NA` has been |
|
27 |
#' conveyed to `na_level` appropriately beforehand with [df_explicit_na()] or [explicit_na()]. |
|
28 |
#' |
|
29 |
#' @seealso Relevant description function [d_count_abnormal_by_baseline()]. |
|
30 |
#' |
|
31 |
#' @name abnormal_by_baseline |
|
32 |
#' @order 1 |
|
33 |
NULL |
|
34 | ||
35 |
#' Description Function for [s_count_abnormal_by_baseline()] |
|
36 |
#' |
|
37 |
#' @description `r lifecycle::badge("stable")` |
|
38 |
#' |
|
39 |
#' Description function that produces the labels for [s_count_abnormal_by_baseline()]. |
|
40 |
#' |
|
41 |
#' @inheritParams abnormal_by_baseline |
|
42 |
#' |
|
43 |
#' @return Abnormal category labels for [s_count_abnormal_by_baseline()]. |
|
44 |
#' |
|
45 |
#' @examples |
|
46 |
#' d_count_abnormal_by_baseline("LOW") |
|
47 |
#' |
|
48 |
#' @export |
|
49 |
d_count_abnormal_by_baseline <- function(abnormal) { |
|
50 | 7x |
not_abn_name <- paste("Not", tolower(abnormal)) |
51 | 7x |
abn_name <- paste0(toupper(substr(abnormal, 1, 1)), tolower(substring(abnormal, 2))) |
52 | 7x |
total_name <- "Total" |
53 | ||
54 | 7x |
list( |
55 | 7x |
not_abnormal = not_abn_name, |
56 | 7x |
abnormal = abn_name, |
57 | 7x |
total = total_name |
58 |
) |
|
59 |
} |
|
60 | ||
61 |
#' @describeIn abnormal_by_baseline Statistics function for a single `abnormal` level. |
|
62 |
#' |
|
63 |
#' @param na_str (`string`)\cr the explicit `na_level` argument you used in the pre-processing steps (maybe with |
|
64 |
#' [df_explicit_na()]). The default is `"<Missing>"`. |
|
65 |
#' |
|
66 |
#' @return |
|
67 |
#' * `s_count_abnormal_by_baseline()` returns statistic `fraction` which is a named list with 3 labeled elements: |
|
68 |
#' `not_abnormal`, `abnormal`, and `total`. Each element contains a vector with `num` and `denom` patient counts. |
|
69 |
#' |
|
70 |
#' @keywords internal |
|
71 |
s_count_abnormal_by_baseline <- function(df, |
|
72 |
.var, |
|
73 |
abnormal, |
|
74 |
na_level = lifecycle::deprecated(), |
|
75 |
na_str = "<Missing>", |
|
76 |
variables = list(id = "USUBJID", baseline = "BNRIND")) { |
|
77 | 5x |
if (lifecycle::is_present(na_level)) { |
78 | ! |
lifecycle::deprecate_warn("0.9.1", "s_count_abnormal_by_baseline(na_level)", "s_count_abnormal_by_baseline(na_str)") |
79 | ! |
na_str <- na_level |
80 |
} |
|
81 | ||
82 | 5x |
checkmate::assert_string(.var) |
83 | 5x |
checkmate::assert_string(abnormal) |
84 | 5x |
checkmate::assert_string(na_str) |
85 | 5x |
assert_df_with_variables(df, c(range = .var, variables)) |
86 | 5x |
checkmate::assert_subset(names(variables), c("id", "baseline")) |
87 | 5x |
checkmate::assert_multi_class(df[[variables$id]], classes = c("factor", "character")) |
88 | 5x |
checkmate::assert_multi_class(df[[variables$baseline]], classes = c("factor", "character")) |
89 | 5x |
checkmate::assert_multi_class(df[[.var]], classes = c("factor", "character")) |
90 | ||
91 |
# If input is passed as character, changed to factor |
|
92 | 5x |
df[[.var]] <- as_factor_keep_attributes(df[[.var]], na_level = na_str) |
93 | 5x |
df[[variables$baseline]] <- as_factor_keep_attributes(df[[variables$baseline]], na_level = na_str) |
94 | ||
95 | 5x |
assert_valid_factor(df[[.var]], any.missing = FALSE) |
96 | 4x |
assert_valid_factor(df[[variables$baseline]], any.missing = FALSE) |
97 | ||
98 |
# Keep only records with valid analysis value. |
|
99 | 3x |
df <- df[df[[.var]] != na_str, ] |
100 | ||
101 | 3x |
anl <- data.frame( |
102 | 3x |
id = df[[variables$id]], |
103 | 3x |
var = df[[.var]], |
104 | 3x |
baseline = df[[variables$baseline]], |
105 | 3x |
stringsAsFactors = FALSE |
106 |
) |
|
107 | ||
108 |
# Total: |
|
109 |
# - Patients in denominator: have at least one valid measurement post-baseline. |
|
110 |
# - Patients in numerator: have at least one abnormality. |
|
111 | 3x |
total_denom <- length(unique(anl$id)) |
112 | 3x |
total_num <- length(unique(anl$id[anl$var == abnormal])) |
113 | ||
114 |
# Baseline NA records are counted only in total rows. |
|
115 | 3x |
anl <- anl[anl$baseline != na_str, ] |
116 | ||
117 |
# Abnormal: |
|
118 |
# - Patients in denominator: have abnormality at baseline. |
|
119 |
# - Patients in numerator: have abnormality at baseline AND |
|
120 |
# have at least one abnormality post-baseline. |
|
121 | 3x |
abn_denom <- length(unique(anl$id[anl$baseline == abnormal])) |
122 | 3x |
abn_num <- length(unique(anl$id[anl$baseline == abnormal & anl$var == abnormal])) |
123 | ||
124 |
# Not abnormal: |
|
125 |
# - Patients in denominator: do not have abnormality at baseline. |
|
126 |
# - Patients in numerator: do not have abnormality at baseline AND |
|
127 |
# have at least one abnormality post-baseline. |
|
128 | 3x |
not_abn_denom <- length(unique(anl$id[anl$baseline != abnormal])) |
129 | 3x |
not_abn_num <- length(unique(anl$id[anl$baseline != abnormal & anl$var == abnormal])) |
130 | ||
131 | 3x |
labels <- d_count_abnormal_by_baseline(abnormal) |
132 | 3x |
list(fraction = list( |
133 | 3x |
not_abnormal = formatters::with_label(c(num = not_abn_num, denom = not_abn_denom), labels$not_abnormal), |
134 | 3x |
abnormal = formatters::with_label(c(num = abn_num, denom = abn_denom), labels$abnormal), |
135 | 3x |
total = formatters::with_label(c(num = total_num, denom = total_denom), labels$total) |
136 |
)) |
|
137 |
} |
|
138 | ||
139 |
#' @describeIn abnormal_by_baseline Formatted analysis function which is used as `afun` |
|
140 |
#' in `count_abnormal_by_baseline()`. |
|
141 |
#' |
|
142 |
#' @return |
|
143 |
#' * `a_count_abnormal_by_baseline()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
144 |
#' |
|
145 |
#' @keywords internal |
|
146 |
a_count_abnormal_by_baseline <- make_afun( |
|
147 |
s_count_abnormal_by_baseline, |
|
148 |
.formats = c(fraction = format_fraction) |
|
149 |
) |
|
150 | ||
151 |
#' @describeIn abnormal_by_baseline Layout-creating function which can take statistics function arguments |
|
152 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
153 |
#' |
|
154 |
#' @return |
|
155 |
#' * `count_abnormal_by_baseline()` returns a layout object suitable for passing to further layouting functions, |
|
156 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
157 |
#' the statistics from `s_count_abnormal_by_baseline()` to the table layout. |
|
158 |
#' |
|
159 |
#' @examples |
|
160 |
#' df <- data.frame( |
|
161 |
#' USUBJID = as.character(c(1:6)), |
|
162 |
#' ANRIND = factor(c(rep("LOW", 4), "NORMAL", "HIGH")), |
|
163 |
#' BNRIND = factor(c("LOW", "NORMAL", "HIGH", NA, "LOW", "NORMAL")) |
|
164 |
#' ) |
|
165 |
#' df <- df_explicit_na(df) |
|
166 |
#' |
|
167 |
#' # Layout creating function. |
|
168 |
#' basic_table() %>% |
|
169 |
#' count_abnormal_by_baseline(var = "ANRIND", abnormal = c(High = "HIGH")) %>% |
|
170 |
#' build_table(df) |
|
171 |
#' |
|
172 |
#' # Passing of statistics function and formatting arguments. |
|
173 |
#' df2 <- data.frame( |
|
174 |
#' ID = as.character(c(1, 2, 3, 4)), |
|
175 |
#' RANGE = factor(c("NORMAL", "LOW", "HIGH", "HIGH")), |
|
176 |
#' BLRANGE = factor(c("LOW", "HIGH", "HIGH", "NORMAL")) |
|
177 |
#' ) |
|
178 |
#' |
|
179 |
#' basic_table() %>% |
|
180 |
#' count_abnormal_by_baseline( |
|
181 |
#' var = "RANGE", |
|
182 |
#' abnormal = c(Low = "LOW"), |
|
183 |
#' variables = list(id = "ID", baseline = "BLRANGE"), |
|
184 |
#' .formats = c(fraction = "xx / xx"), |
|
185 |
#' .indent_mods = c(fraction = 2L) |
|
186 |
#' ) %>% |
|
187 |
#' build_table(df2) |
|
188 |
#' |
|
189 |
#' @export |
|
190 |
#' @order 2 |
|
191 |
count_abnormal_by_baseline <- function(lyt, |
|
192 |
var, |
|
193 |
abnormal, |
|
194 |
variables = list(id = "USUBJID", baseline = "BNRIND"), |
|
195 |
na_str = "<Missing>", |
|
196 |
nested = TRUE, |
|
197 |
..., |
|
198 |
table_names = abnormal, |
|
199 |
.stats = NULL, |
|
200 |
.formats = NULL, |
|
201 |
.labels = NULL, |
|
202 |
.indent_mods = NULL) { |
|
203 | 2x |
checkmate::assert_character(abnormal, len = length(table_names), names = "named") |
204 | 2x |
checkmate::assert_string(var) |
205 | ||
206 | 2x |
extra_args <- list(abnormal = abnormal, variables = variables, na_str = na_str, ...) |
207 | ||
208 | 2x |
afun <- make_afun( |
209 | 2x |
a_count_abnormal_by_baseline, |
210 | 2x |
.stats = .stats, |
211 | 2x |
.formats = .formats, |
212 | 2x |
.labels = .labels, |
213 | 2x |
.indent_mods = .indent_mods, |
214 | 2x |
.ungroup_stats = "fraction" |
215 |
) |
|
216 | 2x |
for (i in seq_along(abnormal)) { |
217 | 4x |
extra_args[["abnormal"]] <- abnormal[i] |
218 | ||
219 | 4x |
lyt <- analyze( |
220 | 4x |
lyt = lyt, |
221 | 4x |
vars = var, |
222 | 4x |
var_labels = names(abnormal[i]), |
223 | 4x |
afun = afun, |
224 | 4x |
na_str = na_str, |
225 | 4x |
nested = nested, |
226 | 4x |
table_names = table_names[i], |
227 | 4x |
extra_args = extra_args, |
228 | 4x |
show_labels = "visible" |
229 |
) |
|
230 |
} |
|
231 | 2x |
lyt |
232 |
} |
1 |
#' Formatting Functions |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' See below for the list of formatting functions created in `tern` to work with `rtables`. |
|
6 |
#' |
|
7 |
#' Other available formats can be listed via [`formatters::list_valid_format_labels()`]. Additional |
|
8 |
#' custom formats can be created via the [`formatters::sprintf_format()`] function. |
|
9 |
#' |
|
10 |
#' @family formatting functions |
|
11 |
#' @name formatting_functions |
|
12 |
NULL |
|
13 | ||
14 |
#' Formatting Fraction and Percentage |
|
15 |
#' |
|
16 |
#' @description `r lifecycle::badge("stable")` |
|
17 |
#' |
|
18 |
#' Formats a fraction together with ratio in percent. |
|
19 |
#' |
|
20 |
#' @param x (`integer`)\cr with elements `num` and `denom`. |
|
21 |
#' @param ... required for `rtables` interface. |
|
22 |
#' |
|
23 |
#' @return A string in the format `num / denom (ratio %)`. If `num` is 0, the format is `num / denom`. |
|
24 |
#' |
|
25 |
#' @examples |
|
26 |
#' format_fraction(x = c(num = 2L, denom = 3L)) |
|
27 |
#' format_fraction(x = c(num = 0L, denom = 3L)) |
|
28 |
#' |
|
29 |
#' @family formatting functions |
|
30 |
#' @export |
|
31 |
format_fraction <- function(x, ...) { |
|
32 | 4x |
attr(x, "label") <- NULL |
33 | ||
34 | 4x |
checkmate::assert_vector(x) |
35 | 4x |
checkmate::assert_count(x["num"]) |
36 | 2x |
checkmate::assert_count(x["denom"]) |
37 | ||
38 | 2x |
result <- if (x["num"] == 0) { |
39 | 1x |
paste0(x["num"], "/", x["denom"]) |
40 |
} else { |
|
41 | 1x |
paste0( |
42 | 1x |
x["num"], "/", x["denom"], |
43 | 1x |
" (", round(x["num"] / x["denom"] * 100, 1), "%)" |
44 |
) |
|
45 |
} |
|
46 | ||
47 | 2x |
return(result) |
48 |
} |
|
49 | ||
50 |
#' Formatting Fraction and Percentage with Fixed Single Decimal Place |
|
51 |
#' |
|
52 |
#' @description `r lifecycle::badge("stable")` |
|
53 |
#' |
|
54 |
#' Formats a fraction together with ratio in percent with fixed single decimal place. |
|
55 |
#' Includes trailing zero in case of whole number percentages to always keep one decimal place. |
|
56 |
#' |
|
57 |
#' @param x (`integer`)\cr with elements `num` and `denom`. |
|
58 |
#' @param ... required for `rtables` interface. |
|
59 |
#' |
|
60 |
#' @return A string in the format `num / denom (ratio %)`. If `num` is 0, the format is `num / denom`. |
|
61 |
#' |
|
62 |
#' @examples |
|
63 |
#' format_fraction_fixed_dp(x = c(num = 1L, denom = 2L)) |
|
64 |
#' format_fraction_fixed_dp(x = c(num = 1L, denom = 4L)) |
|
65 |
#' format_fraction_fixed_dp(x = c(num = 0L, denom = 3L)) |
|
66 |
#' |
|
67 |
#' @family formatting functions |
|
68 |
#' @export |
|
69 |
format_fraction_fixed_dp <- function(x, ...) { |
|
70 | 3x |
attr(x, "label") <- NULL |
71 | 3x |
checkmate::assert_vector(x) |
72 | 3x |
checkmate::assert_count(x["num"]) |
73 | 3x |
checkmate::assert_count(x["denom"]) |
74 | ||
75 | 3x |
result <- if (x["num"] == 0) { |
76 | 1x |
paste0(x["num"], "/", x["denom"]) |
77 |
} else { |
|
78 | 2x |
paste0( |
79 | 2x |
x["num"], "/", x["denom"], |
80 | 2x |
" (", sprintf("%.1f", round(x["num"] / x["denom"] * 100, 1)), "%)" |
81 |
) |
|
82 |
} |
|
83 | 3x |
return(result) |
84 |
} |
|
85 | ||
86 |
#' Formatting Count and Fraction |
|
87 |
#' |
|
88 |
#' @description `r lifecycle::badge("stable")` |
|
89 |
#' |
|
90 |
#' Formats a count together with fraction with special consideration when count is `0`. |
|
91 |
#' |
|
92 |
#' @param x (`integer`)\cr vector of length 2, count and fraction. |
|
93 |
#' @param ... required for `rtables` interface. |
|
94 |
#' |
|
95 |
#' @return A string in the format `count (fraction %)`. If `count` is 0, the format is `0`. |
|
96 |
#' |
|
97 |
#' @examples |
|
98 |
#' format_count_fraction(x = c(2, 0.6667)) |
|
99 |
#' format_count_fraction(x = c(0, 0)) |
|
100 |
#' |
|
101 |
#' @family formatting functions |
|
102 |
#' @export |
|
103 |
format_count_fraction <- function(x, ...) { |
|
104 | 3x |
attr(x, "label") <- NULL |
105 | ||
106 | 3x |
if (any(is.na(x))) { |
107 | 1x |
return("NA") |
108 |
} |
|
109 | ||
110 | 2x |
checkmate::assert_vector(x) |
111 | 2x |
checkmate::assert_integerish(x[1]) |
112 | 2x |
assert_proportion_value(x[2], include_boundaries = TRUE) |
113 | ||
114 | 2x |
result <- if (x[1] == 0) { |
115 | 1x |
"0" |
116 |
} else { |
|
117 | 1x |
paste0(x[1], " (", round(x[2] * 100, 1), "%)") |
118 |
} |
|
119 | ||
120 | 2x |
return(result) |
121 |
} |
|
122 | ||
123 |
#' Formatting Count and Percentage with Fixed Single Decimal Place |
|
124 |
#' |
|
125 |
#' @description `r lifecycle::badge("experimental")` |
|
126 |
#' |
|
127 |
#' Formats a count together with fraction with special consideration when count is `0`. |
|
128 |
#' |
|
129 |
#' @param x (`integer`)\cr vector of length 2, count and fraction. |
|
130 |
#' @param ... required for `rtables` interface. |
|
131 |
#' |
|
132 |
#' @return A string in the format `count (fraction %)`. If `count` is 0, the format is `0`. |
|
133 |
#' |
|
134 |
#' @examples |
|
135 |
#' format_count_fraction_fixed_dp(x = c(2, 0.6667)) |
|
136 |
#' format_count_fraction_fixed_dp(x = c(2, 0.5)) |
|
137 |
#' format_count_fraction_fixed_dp(x = c(0, 0)) |
|
138 |
#' |
|
139 |
#' @family formatting functions |
|
140 |
#' @export |
|
141 |
format_count_fraction_fixed_dp <- function(x, ...) { |
|
142 | 3x |
attr(x, "label") <- NULL |
143 | ||
144 | 3x |
if (any(is.na(x))) { |
145 | ! |
return("NA") |
146 |
} |
|
147 | ||
148 | 3x |
checkmate::assert_vector(x) |
149 | 3x |
checkmate::assert_integerish(x[1]) |
150 | 3x |
assert_proportion_value(x[2], include_boundaries = TRUE) |
151 | ||
152 | 3x |
result <- if (x[1] == 0) { |
153 | 1x |
"0" |
154 | 3x |
} else if (x[2] == 1) { |
155 | ! |
sprintf("%d (100%%)", x[1]) |
156 |
} else { |
|
157 | 2x |
sprintf("%d (%.1f%%)", x[1], x[2] * 100) |
158 |
} |
|
159 | ||
160 | 3x |
return(result) |
161 |
} |
|
162 | ||
163 |
#' Formatting Count and Fraction with Special Case for Count < 10 |
|
164 |
#' |
|
165 |
#' @description `r lifecycle::badge("stable")` |
|
166 |
#' |
|
167 |
#' Formats a count together with fraction with special consideration when count is less than 10. |
|
168 |
#' |
|
169 |
#' @inheritParams format_count_fraction |
|
170 |
#' |
|
171 |
#' @return A string in the format `count (fraction %)`. If `count` is less than 10, only `count` is printed. |
|
172 |
#' |
|
173 |
#' @examples |
|
174 |
#' format_count_fraction_lt10(x = c(275, 0.9673)) |
|
175 |
#' format_count_fraction_lt10(x = c(2, 0.6667)) |
|
176 |
#' format_count_fraction_lt10(x = c(9, 1)) |
|
177 |
#' |
|
178 |
#' @family formatting functions |
|
179 |
#' @export |
|
180 |
format_count_fraction_lt10 <- function(x, ...) { |
|
181 | 7x |
attr(x, "label") <- NULL |
182 | ||
183 | 7x |
if (any(is.na(x))) { |
184 | 1x |
return("NA") |
185 |
} |
|
186 | ||
187 | 6x |
checkmate::assert_vector(x) |
188 | 6x |
checkmate::assert_integerish(x[1]) |
189 | 6x |
assert_proportion_value(x[2], include_boundaries = TRUE) |
190 | ||
191 | 6x |
result <- if (x[1] < 10) { |
192 | 3x |
paste0(x[1]) |
193 |
} else { |
|
194 | 3x |
paste0(x[1], " (", round(x[2] * 100, 1), "%)") |
195 |
} |
|
196 | ||
197 | 6x |
return(result) |
198 |
} |
|
199 | ||
200 |
#' Formatting: XX as Formatting Function |
|
201 |
#' |
|
202 |
#' Translate a string where x and dots are interpreted as number place |
|
203 |
#' holders, and others as formatting elements. |
|
204 |
#' |
|
205 |
#' @param str (`string`)\cr template. |
|
206 |
#' |
|
207 |
#' @return An `rtables` formatting function. |
|
208 |
#' |
|
209 |
#' @examples |
|
210 |
#' test <- list(c(1.658, 0.5761), c(1e1, 785.6)) |
|
211 |
#' |
|
212 |
#' z <- format_xx("xx (xx.x)") |
|
213 |
#' sapply(test, z) |
|
214 |
#' |
|
215 |
#' z <- format_xx("xx.x - xx.x") |
|
216 |
#' sapply(test, z) |
|
217 |
#' |
|
218 |
#' z <- format_xx("xx.x, incl. xx.x% NE") |
|
219 |
#' sapply(test, z) |
|
220 |
#' |
|
221 |
#' @family formatting functions |
|
222 |
#' @export |
|
223 |
format_xx <- function(str) { |
|
224 |
# Find position in the string. |
|
225 | 1x |
positions <- gregexpr(pattern = "x+\\.x+|x+", text = str, perl = TRUE) |
226 | 1x |
x_positions <- regmatches(x = str, m = positions)[[1]] |
227 | ||
228 |
# Roundings depends on the number of x behind [.]. |
|
229 | 1x |
roundings <- lapply( |
230 | 1x |
X = x_positions, |
231 | 1x |
function(x) { |
232 | 2x |
y <- strsplit(split = "\\.", x = x)[[1]] |
233 | 2x |
rounding <- function(x) { |
234 | 4x |
round(x, digits = ifelse(length(y) > 1, nchar(y[2]), 0)) |
235 |
} |
|
236 | 2x |
return(rounding) |
237 |
} |
|
238 |
) |
|
239 | ||
240 | 1x |
rtable_format <- function(x, output) { |
241 | 2x |
values <- Map(y = x, fun = roundings, function(y, fun) fun(y)) |
242 | 2x |
regmatches(x = str, m = positions)[[1]] <- values |
243 | 2x |
return(str) |
244 |
} |
|
245 | ||
246 | 1x |
return(rtable_format) |
247 |
} |
|
248 | ||
249 |
#' Formatting Numeric Values By Significant Figures |
|
250 |
#' |
|
251 |
#' Format numeric values to print with a specified number of significant figures. |
|
252 |
#' |
|
253 |
#' @param sigfig (`integer`)\cr number of significant figures to display. |
|
254 |
#' @param format (`character`)\cr the format label (string) to apply when printing the value. Decimal |
|
255 |
#' places in string are ignored in favor of formatting by significant figures. Formats options are: |
|
256 |
#' `"xx"`, `"xx / xx"`, `"(xx, xx)"`, `"xx - xx"`, and `"xx (xx)"`. |
|
257 |
#' @param num_fmt (`character`)\cr numeric format modifiers to apply to the value. Defaults to `"fg"` for |
|
258 |
#' standard significant figures formatting - fixed (non-scientific notation) format (`"f"`) |
|
259 |
#' and `sigfig` equal to number of significant figures instead of decimal places (`"g"`). See the |
|
260 |
#' [formatC()] `format` argument for more options. |
|
261 |
#' |
|
262 |
#' @return An `rtables` formatting function. |
|
263 |
#' |
|
264 |
#' @examples |
|
265 |
#' fmt_3sf <- format_sigfig(3) |
|
266 |
#' fmt_3sf(1.658) |
|
267 |
#' fmt_3sf(1e1) |
|
268 |
#' |
|
269 |
#' fmt_5sf <- format_sigfig(5) |
|
270 |
#' fmt_5sf(0.57) |
|
271 |
#' fmt_5sf(0.000025645) |
|
272 |
#' |
|
273 |
#' @family formatting functions |
|
274 |
#' @export |
|
275 |
format_sigfig <- function(sigfig, format = "xx", num_fmt = "fg") { |
|
276 | 2x |
checkmate::assert_integerish(sigfig) |
277 | 2x |
format <- gsub("xx\\.|xx\\.x+", "xx", format) |
278 | 2x |
checkmate::assert_choice(format, c("xx", "xx / xx", "(xx, xx)", "xx - xx", "xx (xx)")) |
279 | 2x |
function(x, ...) { |
280 | ! |
if (!is.numeric(x)) stop("`format_sigfig` cannot be used for non-numeric values. Please choose another format.") |
281 | 9x |
num <- formatC(signif(x, digits = sigfig), digits = sigfig, format = num_fmt, flag = "#") |
282 | 9x |
num <- gsub("\\.$", "", num) # remove trailing "." |
283 | ||
284 | 9x |
format_value(num, format) |
285 |
} |
|
286 |
} |
|
287 | ||
288 |
#' Formatting Fraction with Lower Threshold |
|
289 |
#' |
|
290 |
#' @description `r lifecycle::badge("stable")` |
|
291 |
#' |
|
292 |
#' Formats a fraction when the second element of the input `x` is the fraction. It applies |
|
293 |
#' a lower threshold, below which it is just stated that the fraction is smaller than that. |
|
294 |
#' |
|
295 |
#' @param threshold (`proportion`)\cr lower threshold. |
|
296 |
#' |
|
297 |
#' @return An `rtables` formatting function that takes numeric input `x` where the second |
|
298 |
#' element is the fraction that is formatted. If the fraction is above or equal to the threshold, |
|
299 |
#' then it is displayed in percentage. If it is positive but below the threshold, it returns, |
|
300 |
#' e.g. "<1" if the threshold is `0.01`. If it is zero, then just "0" is returned. |
|
301 |
#' |
|
302 |
#' @examples |
|
303 |
#' format_fun <- format_fraction_threshold(0.05) |
|
304 |
#' format_fun(x = c(20, 0.1)) |
|
305 |
#' format_fun(x = c(2, 0.01)) |
|
306 |
#' format_fun(x = c(0, 0)) |
|
307 |
#' |
|
308 |
#' @family formatting functions |
|
309 |
#' @export |
|
310 |
format_fraction_threshold <- function(threshold) { |
|
311 | 1x |
assert_proportion_value(threshold) |
312 | 1x |
string_below_threshold <- paste0("<", round(threshold * 100)) |
313 | 1x |
function(x, ...) { |
314 | 3x |
assert_proportion_value(x[2], include_boundaries = TRUE) |
315 | 3x |
ifelse( |
316 | 3x |
x[2] > 0.01, |
317 | 3x |
round(x[2] * 100), |
318 | 3x |
ifelse( |
319 | 3x |
x[2] == 0, |
320 | 3x |
"0", |
321 | 3x |
string_below_threshold |
322 |
) |
|
323 |
) |
|
324 |
} |
|
325 |
} |
|
326 | ||
327 |
#' Formatting Extreme Values |
|
328 |
#' |
|
329 |
#' @description `r lifecycle::badge("stable")` |
|
330 |
#' |
|
331 |
#' `rtables` formatting functions that handle extreme values. |
|
332 |
#' |
|
333 |
#' @param digits (`integer`)\cr number of decimal places to display. |
|
334 |
#' |
|
335 |
#' @details For each input, apply a format to the specified number of `digits`. If the value is |
|
336 |
#' below a threshold, it returns "<0.01" e.g. if the number of `digits` is 2. If the value is |
|
337 |
#' above a threshold, it returns ">999.99" e.g. if the number of `digits` is 2. |
|
338 |
#' If it is zero, then returns "0.00". |
|
339 |
#' |
|
340 |
#' @family formatting functions |
|
341 |
#' @name extreme_format |
|
342 |
NULL |
|
343 | ||
344 |
#' @describeIn extreme_format Internal helper function to calculate the threshold and create formatted strings |
|
345 |
#' used in Formatting Functions. Returns a list with elements `threshold` and `format_string`. |
|
346 |
#' |
|
347 |
#' @return |
|
348 |
#' * `h_get_format_threshold()` returns a `list` of 2 elements: `threshold`, with `low` and `high` thresholds, |
|
349 |
#' and `format_string`, with thresholds formatted as strings. |
|
350 |
#' |
|
351 |
#' @examples |
|
352 |
#' h_get_format_threshold(2L) |
|
353 |
#' |
|
354 |
#' @export |
|
355 |
h_get_format_threshold <- function(digits = 2L) { |
|
356 | 1378x |
checkmate::assert_integerish(digits) |
357 | ||
358 | 1378x |
low_threshold <- 1 / (10 ^ digits) # styler: off |
359 | 1378x |
high_threshold <- 1000 - (1 / (10 ^ digits)) # styler: off |
360 | ||
361 | 1378x |
string_below_threshold <- paste0("<", low_threshold) |
362 | 1378x |
string_above_threshold <- paste0(">", high_threshold) |
363 | ||
364 | 1378x |
list( |
365 | 1378x |
"threshold" = c(low = low_threshold, high = high_threshold), |
366 | 1378x |
"format_string" = c(low = string_below_threshold, high = string_above_threshold) |
367 |
) |
|
368 |
} |
|
369 | ||
370 |
#' @describeIn extreme_format Internal helper function to apply a threshold format to a value. |
|
371 |
#' Creates a formatted string to be used in Formatting Functions. |
|
372 |
#' |
|
373 |
#' @param x (`number`)\cr value to format. |
|
374 |
#' |
|
375 |
#' @return |
|
376 |
#' * `h_format_threshold()` returns the given value, or if the value is not within the digit threshold the relation |
|
377 |
#' of the given value to the digit threshold, as a formatted string. |
|
378 |
#' |
|
379 |
#' @examples |
|
380 |
#' h_format_threshold(0.001) |
|
381 |
#' h_format_threshold(1000) |
|
382 |
#' |
|
383 |
#' @export |
|
384 |
h_format_threshold <- function(x, digits = 2L) { |
|
385 | 1381x |
if (is.na(x)) { |
386 | 4x |
return(x) |
387 |
} |
|
388 | ||
389 | 1377x |
checkmate::assert_numeric(x, lower = 0) |
390 | ||
391 | 1377x |
l_fmt <- h_get_format_threshold(digits) |
392 | ||
393 | 1377x |
result <- if (x < l_fmt$threshold["low"] && 0 < x) { |
394 | 25x |
l_fmt$format_string["low"] |
395 | 1377x |
} else if (x > l_fmt$threshold["high"]) { |
396 | 72x |
l_fmt$format_string["high"] |
397 |
} else { |
|
398 | 1280x |
sprintf(fmt = paste0("%.", digits, "f"), x) |
399 |
} |
|
400 | ||
401 | 1377x |
unname(result) |
402 |
} |
|
403 | ||
404 |
#' Formatting a Single Extreme Value |
|
405 |
#' |
|
406 |
#' @description `r lifecycle::badge("stable")` |
|
407 |
#' |
|
408 |
#' Create Formatting Function for a single extreme value. |
|
409 |
#' |
|
410 |
#' @inheritParams extreme_format |
|
411 |
#' |
|
412 |
#' @return An `rtables` formatting function that uses threshold `digits` to return a formatted extreme value. |
|
413 |
#' |
|
414 |
#' @examples |
|
415 |
#' format_fun <- format_extreme_values(2L) |
|
416 |
#' format_fun(x = 0.127) |
|
417 |
#' format_fun(x = Inf) |
|
418 |
#' format_fun(x = 0) |
|
419 |
#' format_fun(x = 0.009) |
|
420 |
#' |
|
421 |
#' @family formatting functions |
|
422 |
#' @export |
|
423 |
format_extreme_values <- function(digits = 2L) { |
|
424 | 30x |
function(x, ...) { |
425 | 383x |
checkmate::assert_scalar(x, na.ok = TRUE) |
426 | ||
427 | 383x |
h_format_threshold(x = x, digits = digits) |
428 |
} |
|
429 |
} |
|
430 | ||
431 |
#' Formatting Extreme Values Part of a Confidence Interval |
|
432 |
#' |
|
433 |
#' @description `r lifecycle::badge("stable")` |
|
434 |
#' |
|
435 |
#' Formatting Function for extreme values part of a confidence interval. Values |
|
436 |
#' are formatted as e.g. "(xx.xx, xx.xx)" if the number of `digits` is 2. |
|
437 |
#' |
|
438 |
#' @inheritParams extreme_format |
|
439 |
#' |
|
440 |
#' @return An `rtables` formatting function that uses threshold `digits` to return a formatted extreme |
|
441 |
#' values confidence interval. |
|
442 |
#' |
|
443 |
#' @examples |
|
444 |
#' format_fun <- format_extreme_values_ci(2L) |
|
445 |
#' format_fun(x = c(0.127, Inf)) |
|
446 |
#' format_fun(x = c(0, 0.009)) |
|
447 |
#' |
|
448 |
#' @family formatting functions |
|
449 |
#' @export |
|
450 |
format_extreme_values_ci <- function(digits = 2L) { |
|
451 | 38x |
function(x, ...) { |
452 | 496x |
checkmate::assert_vector(x, len = 2) |
453 | 496x |
l_result <- h_format_threshold(x = x[1], digits = digits) |
454 | 496x |
h_result <- h_format_threshold(x = x[2], digits = digits) |
455 | ||
456 | 496x |
paste0("(", l_result, ", ", h_result, ")") |
457 |
} |
|
458 |
} |
|
459 | ||
460 |
#' Automatic formats from data significant digits |
|
461 |
#' |
|
462 |
#' @description `r lifecycle::badge("stable")` |
|
463 |
#' |
|
464 |
#' Formatting function for the majority of default methods used in [analyze_vars()]. |
|
465 |
#' For non-derived values, the significant digits of data is used (e.g. range), while derived |
|
466 |
#' values have one more digits (measure of location and dispersion like mean, standard deviation). |
|
467 |
#' This function can be called internally with "auto" like, for example, |
|
468 |
#' `.formats = c("mean" = "auto")`. See details to see how this works with the inner function. |
|
469 |
#' |
|
470 |
#' @param dt_var (`numeric`) \cr all the data the statistics was created upon. Used only to find |
|
471 |
#' significant digits. In [analyze_vars] this comes from `.df_row` (see |
|
472 |
#' [rtables::additional_fun_params]), and it is the row data after the above row splits. No |
|
473 |
#' column split is considered. |
|
474 |
#' @param x_stat (`string`) \cr string indicating the current statistical method used. |
|
475 |
#' |
|
476 |
#' @return A string that `rtables` prints in a table cell. |
|
477 |
#' |
|
478 |
#' @details |
|
479 |
#' The internal function is needed to work with `rtables` default structure for |
|
480 |
#' format functions, i.e. `function(x, ...)`, where is x are results from statistical evaluation. |
|
481 |
#' It can be more than one element (e.g. for `.stats = "mean_sd"`). |
|
482 |
#' |
|
483 |
#' @examples |
|
484 |
#' x_todo <- c(0.001, 0.2, 0.0011000, 3, 4) |
|
485 |
#' res <- c(mean(x_todo[1:3]), sd(x_todo[1:3])) |
|
486 |
#' |
|
487 |
#' # x is the result coming into the formatting function -> res!! |
|
488 |
#' format_auto(dt_var = x_todo, x_stat = "mean_sd")(x = res) |
|
489 |
#' format_auto(x_todo, "range")(x = range(x_todo)) |
|
490 |
#' no_sc_x <- c(0.0000001, 1) |
|
491 |
#' format_auto(no_sc_x, "range")(x = no_sc_x) |
|
492 |
#' |
|
493 |
#' @family formatting functions |
|
494 |
#' @export |
|
495 |
format_auto <- function(dt_var, x_stat) { |
|
496 | 8x |
function(x = "", ...) { |
497 | 12x |
checkmate::assert_numeric(x, min.len = 1) |
498 | 12x |
checkmate::assert_numeric(dt_var, min.len = 1) |
499 |
# Defaults - they may be a param in the future |
|
500 | 12x |
der_stats <- c( |
501 | 12x |
"mean", "sd", "se", "median", "geom_mean", "quantiles", "iqr", |
502 | 12x |
"mean_sd", "mean_se", "mean_se", "mean_ci", "mean_sei", "mean_sdi", |
503 | 12x |
"median_ci" |
504 |
) |
|
505 | 12x |
nonder_stats <- c("n", "range", "min", "max") |
506 | ||
507 |
# Safenet for miss-modifications |
|
508 | 12x |
stopifnot(length(intersect(der_stats, nonder_stats)) == 0) # nolint |
509 | 12x |
checkmate::assert_choice(x_stat, c(der_stats, nonder_stats)) |
510 | ||
511 |
# Finds the max number of digits in data |
|
512 | 12x |
detect_dig <- vapply(dt_var, count_decimalplaces, FUN.VALUE = numeric(1)) %>% |
513 | 12x |
max() |
514 | ||
515 | 12x |
if (x_stat %in% der_stats) { |
516 | 5x |
detect_dig <- detect_dig + 1 |
517 |
} |
|
518 | ||
519 |
# Render input |
|
520 | 12x |
str_vals <- formatC(x, digits = detect_dig, format = "f") |
521 | 12x |
def_fmt <- get_formats_from_stats(x_stat)[[x_stat]] |
522 | 12x |
str_fmt <- str_extract(def_fmt, invert = FALSE)[[1]] |
523 | 12x |
if (length(str_fmt) != length(str_vals)) { |
524 | 2x |
stop( |
525 | 2x |
"Number of inserted values as result (", length(str_vals), |
526 | 2x |
") is not the same as there should be in the default tern formats for ", |
527 | 2x |
x_stat, " (-> ", def_fmt, " needs ", length(str_fmt), " values). ", |
528 | 2x |
"See tern_default_formats to check all of them." |
529 |
) |
|
530 |
} |
|
531 | ||
532 |
# Squashing them together |
|
533 | 10x |
inv_str_fmt <- str_extract(def_fmt, invert = TRUE)[[1]] |
534 | 10x |
stopifnot(length(inv_str_fmt) == length(str_vals) + 1) # nolint |
535 | ||
536 | 10x |
out <- vector("character", length = length(inv_str_fmt) + length(str_vals)) |
537 | 10x |
is_even <- seq_along(out) %% 2 == 0 |
538 | 10x |
out[is_even] <- str_vals |
539 | 10x |
out[!is_even] <- inv_str_fmt |
540 | ||
541 | 10x |
return(paste0(out, collapse = "")) |
542 |
} |
|
543 |
} |
|
544 | ||
545 |
# Utility function that could be useful in general |
|
546 |
str_extract <- function(string, pattern = "xx|xx\\.|xx\\.x+", invert = FALSE) { |
|
547 | 22x |
regmatches(string, gregexpr(pattern, string), invert = invert) |
548 |
} |
|
549 | ||
550 |
# Helper function |
|
551 |
count_decimalplaces <- function(dec) { |
|
552 | 125x |
if (abs(dec - round(dec)) > .Machine$double.eps^0.5) { # For precision |
553 | 104x |
nchar(strsplit(format(dec, scientific = FALSE, trim = FALSE), ".", fixed = TRUE)[[1]][[2]]) |
554 |
} else { |
|
555 | 21x |
return(0) |
556 |
} |
|
557 |
} |
|
558 | ||
559 |
#' Apply Auto Formatting |
|
560 |
#' |
|
561 |
#' Checks if any of the listed formats in `.formats` are `"auto"`, and replaces `"auto"` with |
|
562 |
#' the correct implementation of `format_auto` for the given statistics, data, and variable. |
|
563 |
#' |
|
564 |
#' @inheritParams argument_convention |
|
565 |
#' @param x_stats (named `list`)\cr a named list of statistics where each element corresponds |
|
566 |
#' to an element in `.formats`, with matching names. |
|
567 |
#' |
|
568 |
#' @keywords internal |
|
569 |
apply_auto_formatting <- function(.formats, x_stats, .df_row, .var) { |
|
570 | 382x |
is_auto_fmt <- vapply(.formats, function(ii) is.character(ii) && ii == "auto", logical(1)) |
571 | 382x |
if (any(is_auto_fmt)) { |
572 | 2x |
auto_stats <- x_stats[is_auto_fmt] |
573 | 2x |
var_df <- .df_row[[.var]] # xxx this can be extended for the WHOLE data or single facets |
574 | 2x |
.formats[is_auto_fmt] <- lapply(names(auto_stats), format_auto, dt_var = var_df) |
575 |
} |
|
576 | 382x |
.formats |
577 |
} |
1 |
#' Proportion Difference |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' @inheritParams prop_diff_strat_nc |
|
6 |
#' @inheritParams argument_convention |
|
7 |
#' @param method (`string`)\cr the method used for the confidence interval estimation. |
|
8 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("estimate_proportion_diff")` |
|
9 |
#' to see available statistics for this function. |
|
10 |
#' |
|
11 |
#' @seealso [d_proportion_diff()] |
|
12 |
#' |
|
13 |
#' @name prop_diff |
|
14 |
#' @order 1 |
|
15 |
NULL |
|
16 | ||
17 |
#' @describeIn prop_diff Statistics function estimating the difference |
|
18 |
#' in terms of responder proportion. |
|
19 |
#' |
|
20 |
#' @return |
|
21 |
#' * `s_proportion_diff()` returns a named list of elements `diff` and `diff_ci`. |
|
22 |
#' |
|
23 |
#' @note When performing an unstratified analysis, methods `"cmh"`, `"strat_newcombe"`, and `"strat_newcombecc"` are |
|
24 |
#' not permitted. |
|
25 |
#' |
|
26 |
#' @examples |
|
27 |
#' s_proportion_diff( |
|
28 |
#' df = subset(dta, grp == "A"), |
|
29 |
#' .var = "rsp", |
|
30 |
#' .ref_group = subset(dta, grp == "B"), |
|
31 |
#' .in_ref_col = FALSE, |
|
32 |
#' conf_level = 0.90, |
|
33 |
#' method = "ha" |
|
34 |
#' ) |
|
35 |
#' |
|
36 |
#' # CMH example with strata |
|
37 |
#' s_proportion_diff( |
|
38 |
#' df = subset(dta, grp == "A"), |
|
39 |
#' .var = "rsp", |
|
40 |
#' .ref_group = subset(dta, grp == "B"), |
|
41 |
#' .in_ref_col = FALSE, |
|
42 |
#' variables = list(strata = c("f1", "f2")), |
|
43 |
#' conf_level = 0.90, |
|
44 |
#' method = "cmh" |
|
45 |
#' ) |
|
46 |
#' |
|
47 |
#' @export |
|
48 |
s_proportion_diff <- function(df, |
|
49 |
.var, |
|
50 |
.ref_group, |
|
51 |
.in_ref_col, |
|
52 |
variables = list(strata = NULL), |
|
53 |
conf_level = 0.95, |
|
54 |
method = c( |
|
55 |
"waldcc", "wald", "cmh", |
|
56 |
"ha", "newcombe", "newcombecc", |
|
57 |
"strat_newcombe", "strat_newcombecc" |
|
58 |
), |
|
59 |
weights_method = "cmh") { |
|
60 | 2x |
method <- match.arg(method) |
61 | 2x |
if (is.null(variables$strata) && checkmate::test_subset(method, c("cmh", "strat_newcombe", "strat_newcombecc"))) { |
62 | ! |
stop(paste( |
63 | ! |
"When performing an unstratified analysis, methods 'cmh', 'strat_newcombe', and 'strat_newcombecc' are not", |
64 | ! |
"permitted. Please choose a different method." |
65 |
)) |
|
66 |
} |
|
67 | 2x |
y <- list(diff = "", diff_ci = "") |
68 | ||
69 | 2x |
if (!.in_ref_col) { |
70 | 2x |
rsp <- c(.ref_group[[.var]], df[[.var]]) |
71 | 2x |
grp <- factor( |
72 | 2x |
rep( |
73 | 2x |
c("ref", "Not-ref"), |
74 | 2x |
c(nrow(.ref_group), nrow(df)) |
75 |
), |
|
76 | 2x |
levels = c("ref", "Not-ref") |
77 |
) |
|
78 | ||
79 | 2x |
if (!is.null(variables$strata)) { |
80 | 1x |
strata_colnames <- variables$strata |
81 | 1x |
checkmate::assert_character(strata_colnames, null.ok = FALSE) |
82 | 1x |
strata_vars <- stats::setNames(as.list(strata_colnames), strata_colnames) |
83 | ||
84 | 1x |
assert_df_with_variables(df, strata_vars) |
85 | 1x |
assert_df_with_variables(.ref_group, strata_vars) |
86 | ||
87 |
# Merging interaction strata for reference group rows data and remaining |
|
88 | 1x |
strata <- c( |
89 | 1x |
interaction(.ref_group[strata_colnames]), |
90 | 1x |
interaction(df[strata_colnames]) |
91 |
) |
|
92 | 1x |
strata <- as.factor(strata) |
93 |
} |
|
94 | ||
95 |
# Defining the std way to calculate weights for strat_newcombe |
|
96 | 2x |
if (!is.null(variables$weights_method)) { |
97 | ! |
weights_method <- variables$weights_method |
98 |
} else { |
|
99 | 2x |
weights_method <- "cmh" |
100 |
} |
|
101 | ||
102 | 2x |
y <- switch(method, |
103 | 2x |
"wald" = prop_diff_wald(rsp, grp, conf_level, correct = FALSE), |
104 | 2x |
"waldcc" = prop_diff_wald(rsp, grp, conf_level, correct = TRUE), |
105 | 2x |
"ha" = prop_diff_ha(rsp, grp, conf_level), |
106 | 2x |
"newcombe" = prop_diff_nc(rsp, grp, conf_level, correct = FALSE), |
107 | 2x |
"newcombecc" = prop_diff_nc(rsp, grp, conf_level, correct = TRUE), |
108 | 2x |
"strat_newcombe" = prop_diff_strat_nc(rsp, |
109 | 2x |
grp, |
110 | 2x |
strata, |
111 | 2x |
weights_method, |
112 | 2x |
conf_level, |
113 | 2x |
correct = FALSE |
114 |
), |
|
115 | 2x |
"strat_newcombecc" = prop_diff_strat_nc(rsp, |
116 | 2x |
grp, |
117 | 2x |
strata, |
118 | 2x |
weights_method, |
119 | 2x |
conf_level, |
120 | 2x |
correct = TRUE |
121 |
), |
|
122 | 2x |
"cmh" = prop_diff_cmh(rsp, grp, strata, conf_level)[c("diff", "diff_ci")] |
123 |
) |
|
124 | ||
125 | 2x |
y$diff <- y$diff * 100 |
126 | 2x |
y$diff_ci <- y$diff_ci * 100 |
127 |
} |
|
128 | ||
129 | 2x |
attr(y$diff, "label") <- "Difference in Response rate (%)" |
130 | 2x |
attr(y$diff_ci, "label") <- d_proportion_diff( |
131 | 2x |
conf_level, method, |
132 | 2x |
long = FALSE |
133 |
) |
|
134 | ||
135 | 2x |
y |
136 |
} |
|
137 | ||
138 |
#' @describeIn prop_diff Formatted analysis function which is used as `afun` in `estimate_proportion_diff()`. |
|
139 |
#' |
|
140 |
#' @return |
|
141 |
#' * `a_proportion_diff()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
142 |
#' |
|
143 |
#' @examples |
|
144 |
#' a_proportion_diff( |
|
145 |
#' df = subset(dta, grp == "A"), |
|
146 |
#' .var = "rsp", |
|
147 |
#' .ref_group = subset(dta, grp == "B"), |
|
148 |
#' .in_ref_col = FALSE, |
|
149 |
#' conf_level = 0.90, |
|
150 |
#' method = "ha" |
|
151 |
#' ) |
|
152 |
#' |
|
153 |
#' @export |
|
154 |
a_proportion_diff <- make_afun( |
|
155 |
s_proportion_diff, |
|
156 |
.formats = c(diff = "xx.x", diff_ci = "(xx.x, xx.x)"), |
|
157 |
.indent_mods = c(diff = 0L, diff_ci = 1L) |
|
158 |
) |
|
159 | ||
160 |
#' @describeIn prop_diff Layout-creating function which can take statistics function arguments |
|
161 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
162 |
#' |
|
163 |
#' @return |
|
164 |
#' * `estimate_proportion_diff()` returns a layout object suitable for passing to further layouting functions, |
|
165 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
166 |
#' the statistics from `s_proportion_diff()` to the table layout. |
|
167 |
#' |
|
168 |
#' @examples |
|
169 |
#' ## "Mid" case: 4/4 respond in group A, 1/2 respond in group B. |
|
170 |
#' nex <- 100 # Number of example rows |
|
171 |
#' dta <- data.frame( |
|
172 |
#' "rsp" = sample(c(TRUE, FALSE), nex, TRUE), |
|
173 |
#' "grp" = sample(c("A", "B"), nex, TRUE), |
|
174 |
#' "f1" = sample(c("a1", "a2"), nex, TRUE), |
|
175 |
#' "f2" = sample(c("x", "y", "z"), nex, TRUE), |
|
176 |
#' stringsAsFactors = TRUE |
|
177 |
#' ) |
|
178 |
#' |
|
179 |
#' l <- basic_table() %>% |
|
180 |
#' split_cols_by(var = "grp", ref_group = "B") %>% |
|
181 |
#' estimate_proportion_diff( |
|
182 |
#' vars = "rsp", |
|
183 |
#' conf_level = 0.90, |
|
184 |
#' method = "ha" |
|
185 |
#' ) |
|
186 |
#' |
|
187 |
#' build_table(l, df = dta) |
|
188 |
#' |
|
189 |
#' @export |
|
190 |
#' @order 2 |
|
191 |
estimate_proportion_diff <- function(lyt, |
|
192 |
vars, |
|
193 |
variables = list(strata = NULL), |
|
194 |
conf_level = 0.95, |
|
195 |
method = c( |
|
196 |
"waldcc", "wald", "cmh", |
|
197 |
"ha", "newcombe", "newcombecc", |
|
198 |
"strat_newcombe", "strat_newcombecc" |
|
199 |
), |
|
200 |
weights_method = "cmh", |
|
201 |
na_str = default_na_str(), |
|
202 |
nested = TRUE, |
|
203 |
..., |
|
204 |
var_labels = vars, |
|
205 |
show_labels = "hidden", |
|
206 |
table_names = vars, |
|
207 |
.stats = NULL, |
|
208 |
.formats = NULL, |
|
209 |
.labels = NULL, |
|
210 |
.indent_mods = NULL) { |
|
211 | 4x |
extra_args <- list( |
212 | 4x |
variables = variables, conf_level = conf_level, method = method, weights_method = weights_method, ... |
213 |
) |
|
214 | ||
215 | 4x |
afun <- make_afun( |
216 | 4x |
a_proportion_diff, |
217 | 4x |
.stats = .stats, |
218 | 4x |
.formats = .formats, |
219 | 4x |
.labels = .labels, |
220 | 4x |
.indent_mods = .indent_mods |
221 |
) |
|
222 | ||
223 | 4x |
analyze( |
224 | 4x |
lyt, |
225 | 4x |
vars, |
226 | 4x |
afun = afun, |
227 | 4x |
var_labels = var_labels, |
228 | 4x |
na_str = na_str, |
229 | 4x |
nested = nested, |
230 | 4x |
extra_args = extra_args, |
231 | 4x |
show_labels = show_labels, |
232 | 4x |
table_names = table_names |
233 |
) |
|
234 |
} |
|
235 | ||
236 |
#' Check: Proportion Difference Arguments |
|
237 |
#' |
|
238 |
#' Verifies that and/or convert arguments into valid values to be used in the |
|
239 |
#' estimation of difference in responder proportions. |
|
240 |
#' |
|
241 |
#' @inheritParams prop_diff |
|
242 |
#' @inheritParams prop_diff_wald |
|
243 |
#' |
|
244 |
#' @keywords internal |
|
245 |
check_diff_prop_ci <- function(rsp, |
|
246 |
grp, |
|
247 |
strata = NULL, |
|
248 |
conf_level, |
|
249 |
correct = NULL) { |
|
250 | 19x |
checkmate::assert_logical(rsp, any.missing = FALSE) |
251 | 19x |
checkmate::assert_factor(grp, len = length(rsp), any.missing = FALSE, n.levels = 2) |
252 | 19x |
checkmate::assert_number(conf_level, lower = 0, upper = 1) |
253 | 19x |
checkmate::assert_flag(correct, null.ok = TRUE) |
254 | ||
255 | 19x |
if (!is.null(strata)) { |
256 | 11x |
checkmate::assert_factor(strata, len = length(rsp)) |
257 |
} |
|
258 | ||
259 | 19x |
invisible() |
260 |
} |
|
261 | ||
262 |
#' Description of Method Used for Proportion Comparison |
|
263 |
#' |
|
264 |
#' @description `r lifecycle::badge("stable")` |
|
265 |
#' |
|
266 |
#' This is an auxiliary function that describes the analysis in |
|
267 |
#' `s_proportion_diff`. |
|
268 |
#' |
|
269 |
#' @inheritParams s_proportion_diff |
|
270 |
#' @param long (`logical`)\cr Whether a long or a short (default) description is required. |
|
271 |
#' |
|
272 |
#' @return A `string` describing the analysis. |
|
273 |
#' |
|
274 |
#' @seealso [prop_diff] |
|
275 |
#' |
|
276 |
#' @export |
|
277 |
d_proportion_diff <- function(conf_level, |
|
278 |
method, |
|
279 |
long = FALSE) { |
|
280 | 11x |
label <- paste0(conf_level * 100, "% CI") |
281 | 11x |
if (long) { |
282 | ! |
label <- paste( |
283 | ! |
label, |
284 | ! |
ifelse( |
285 | ! |
method == "cmh", |
286 | ! |
"for adjusted difference", |
287 | ! |
"for difference" |
288 |
) |
|
289 |
) |
|
290 |
} |
|
291 | ||
292 | 11x |
method_part <- switch(method, |
293 | 11x |
"cmh" = "CMH, without correction", |
294 | 11x |
"waldcc" = "Wald, with correction", |
295 | 11x |
"wald" = "Wald, without correction", |
296 | 11x |
"ha" = "Anderson-Hauck", |
297 | 11x |
"newcombe" = "Newcombe, without correction", |
298 | 11x |
"newcombecc" = "Newcombe, with correction", |
299 | 11x |
"strat_newcombe" = "Stratified Newcombe, without correction", |
300 | 11x |
"strat_newcombecc" = "Stratified Newcombe, with correction", |
301 | 11x |
stop(paste(method, "does not have a description")) |
302 |
) |
|
303 | 11x |
paste0(label, " (", method_part, ")") |
304 |
} |
|
305 | ||
306 |
#' Helper Functions to Calculate Proportion Difference |
|
307 |
#' |
|
308 |
#' @description `r lifecycle::badge("stable")` |
|
309 |
#' |
|
310 |
#' @inheritParams argument_convention |
|
311 |
#' @inheritParams prop_diff |
|
312 |
#' @param grp (`factor`)\cr vector assigning observations to one out of two groups |
|
313 |
#' (e.g. reference and treatment group). |
|
314 |
#' |
|
315 |
#' @return A named `list` of elements `diff` (proportion difference) and `diff_ci` |
|
316 |
#' (proportion difference confidence interval). |
|
317 |
#' |
|
318 |
#' @seealso [prop_diff()] for implementation of these helper functions. |
|
319 |
#' |
|
320 |
#' @name h_prop_diff |
|
321 |
NULL |
|
322 | ||
323 |
#' @describeIn h_prop_diff The Wald interval follows the usual textbook |
|
324 |
#' definition for a single proportion confidence interval using the normal |
|
325 |
#' approximation. It is possible to include a continuity correction for Wald's |
|
326 |
#' interval. |
|
327 |
#' |
|
328 |
#' @param correct (`logical`)\cr whether to include the continuity correction. For further |
|
329 |
#' information, see [stats::prop.test()]. |
|
330 |
#' |
|
331 |
#' @examples |
|
332 |
#' # Wald confidence interval |
|
333 |
#' set.seed(2) |
|
334 |
#' rsp <- sample(c(TRUE, FALSE), replace = TRUE, size = 20) |
|
335 |
#' grp <- factor(c(rep("A", 10), rep("B", 10))) |
|
336 |
#' |
|
337 |
#' prop_diff_wald(rsp = rsp, grp = grp, conf_level = 0.95, correct = FALSE) |
|
338 |
#' |
|
339 |
#' @export |
|
340 |
prop_diff_wald <- function(rsp, |
|
341 |
grp, |
|
342 |
conf_level = 0.95, |
|
343 |
correct = FALSE) { |
|
344 | 4x |
if (isTRUE(correct)) { |
345 | 3x |
mthd <- "waldcc" |
346 |
} else { |
|
347 | 1x |
mthd <- "wald" |
348 |
} |
|
349 | 4x |
grp <- as_factor_keep_attributes(grp) |
350 | 4x |
check_diff_prop_ci( |
351 | 4x |
rsp = rsp, grp = grp, conf_level = conf_level, correct = correct |
352 |
) |
|
353 | ||
354 |
# check if binary response is coded as logical |
|
355 | 4x |
checkmate::assert_logical(rsp, any.missing = FALSE) |
356 | 4x |
checkmate::assert_factor(grp, len = length(rsp), any.missing = FALSE, n.levels = 2) |
357 | ||
358 | 4x |
tbl <- table(grp, factor(rsp, levels = c(TRUE, FALSE))) |
359 |
# x1 and n1 are non-reference groups. |
|
360 | 4x |
diff_ci <- desctools_binom( |
361 | 4x |
x1 = tbl[2], n1 = sum(tbl[2], tbl[4]), |
362 | 4x |
x2 = tbl[1], n2 = sum(tbl[1], tbl[3]), |
363 | 4x |
conf.level = conf_level, |
364 | 4x |
method = mthd |
365 |
) |
|
366 | ||
367 | 4x |
list( |
368 | 4x |
"diff" = unname(diff_ci[, "est"]), |
369 | 4x |
"diff_ci" = unname(diff_ci[, c("lwr.ci", "upr.ci")]) |
370 |
) |
|
371 |
} |
|
372 | ||
373 |
#' @describeIn h_prop_diff Anderson-Hauck confidence interval. |
|
374 |
#' |
|
375 |
#' @examples |
|
376 |
#' # Anderson-Hauck confidence interval |
|
377 |
#' ## "Mid" case: 3/4 respond in group A, 1/2 respond in group B. |
|
378 |
#' rsp <- c(TRUE, FALSE, FALSE, TRUE, TRUE, TRUE) |
|
379 |
#' grp <- factor(c("A", "B", "A", "B", "A", "A"), levels = c("B", "A")) |
|
380 |
#' |
|
381 |
#' prop_diff_ha(rsp = rsp, grp = grp, conf_level = 0.90) |
|
382 |
#' |
|
383 |
#' ## Edge case: Same proportion of response in A and B. |
|
384 |
#' rsp <- c(TRUE, FALSE, TRUE, FALSE) |
|
385 |
#' grp <- factor(c("A", "A", "B", "B"), levels = c("A", "B")) |
|
386 |
#' |
|
387 |
#' prop_diff_ha(rsp = rsp, grp = grp, conf_level = 0.6) |
|
388 |
#' |
|
389 |
#' @export |
|
390 |
prop_diff_ha <- function(rsp, |
|
391 |
grp, |
|
392 |
conf_level) { |
|
393 | 3x |
grp <- as_factor_keep_attributes(grp) |
394 | 3x |
check_diff_prop_ci(rsp = rsp, grp = grp, conf_level = conf_level) |
395 | ||
396 | 3x |
tbl <- table(grp, factor(rsp, levels = c(TRUE, FALSE))) |
397 |
# x1 and n1 are non-reference groups. |
|
398 | 3x |
ci <- desctools_binom( |
399 | 3x |
x1 = tbl[2], n1 = sum(tbl[2], tbl[4]), |
400 | 3x |
x2 = tbl[1], n2 = sum(tbl[1], tbl[3]), |
401 | 3x |
conf.level = conf_level, |
402 | 3x |
method = "ha" |
403 |
) |
|
404 | 3x |
list( |
405 | 3x |
"diff" = unname(ci[, "est"]), |
406 | 3x |
"diff_ci" = unname(ci[, c("lwr.ci", "upr.ci")]) |
407 |
) |
|
408 |
} |
|
409 | ||
410 |
#' @describeIn h_prop_diff `Newcombe` confidence interval. It is based on |
|
411 |
#' the Wilson score confidence interval for a single binomial proportion. |
|
412 |
#' |
|
413 |
#' @examples |
|
414 |
#' # `Newcombe` confidence interval |
|
415 |
#' |
|
416 |
#' set.seed(1) |
|
417 |
#' rsp <- c( |
|
418 |
#' sample(c(TRUE, FALSE), size = 40, prob = c(3 / 4, 1 / 4), replace = TRUE), |
|
419 |
#' sample(c(TRUE, FALSE), size = 40, prob = c(1 / 2, 1 / 2), replace = TRUE) |
|
420 |
#' ) |
|
421 |
#' grp <- factor(rep(c("A", "B"), each = 40), levels = c("B", "A")) |
|
422 |
#' table(rsp, grp) |
|
423 |
#' |
|
424 |
#' prop_diff_nc(rsp = rsp, grp = grp, conf_level = 0.9) |
|
425 |
#' |
|
426 |
#' @export |
|
427 |
prop_diff_nc <- function(rsp, |
|
428 |
grp, |
|
429 |
conf_level, |
|
430 |
correct = FALSE) { |
|
431 | 1x |
if (isTRUE(correct)) { |
432 | ! |
mthd <- "scorecc" |
433 |
} else { |
|
434 | 1x |
mthd <- "score" |
435 |
} |
|
436 | 1x |
grp <- as_factor_keep_attributes(grp) |
437 | 1x |
check_diff_prop_ci(rsp = rsp, grp = grp, conf_level = conf_level) |
438 | ||
439 | 1x |
p_grp <- tapply(rsp, grp, mean) |
440 | 1x |
diff_p <- unname(diff(p_grp)) |
441 | 1x |
tbl <- table(grp, factor(rsp, levels = c(TRUE, FALSE))) |
442 | 1x |
ci <- desctools_binom( |
443 |
# x1 and n1 are non-reference groups. |
|
444 | 1x |
x1 = tbl[2], n1 = sum(tbl[2], tbl[4]), |
445 | 1x |
x2 = tbl[1], n2 = sum(tbl[1], tbl[3]), |
446 | 1x |
conf.level = conf_level, |
447 | 1x |
method = mthd |
448 |
) |
|
449 | 1x |
list( |
450 | 1x |
"diff" = unname(ci[, "est"]), |
451 | 1x |
"diff_ci" = unname(ci[, c("lwr.ci", "upr.ci")]) |
452 |
) |
|
453 |
} |
|
454 | ||
455 |
#' @describeIn h_prop_diff Calculates the weighted difference. This is defined as the difference in |
|
456 |
#' response rates between the experimental treatment group and the control treatment group, adjusted |
|
457 |
#' for stratification factors by applying `Cochran-Mantel-Haenszel` (`CMH`) weights. For the `CMH` chi-squared |
|
458 |
#' test, use [stats::mantelhaen.test()]. |
|
459 |
#' |
|
460 |
#' @param strata (`factor`)\cr variable with one level per stratum and same length as `rsp`. |
|
461 |
#' |
|
462 |
#' @examples |
|
463 |
#' # Cochran-Mantel-Haenszel confidence interval |
|
464 |
#' |
|
465 |
#' set.seed(2) |
|
466 |
#' rsp <- sample(c(TRUE, FALSE), 100, TRUE) |
|
467 |
#' grp <- sample(c("Placebo", "Treatment"), 100, TRUE) |
|
468 |
#' grp <- factor(grp, levels = c("Placebo", "Treatment")) |
|
469 |
#' strata_data <- data.frame( |
|
470 |
#' "f1" = sample(c("a", "b"), 100, TRUE), |
|
471 |
#' "f2" = sample(c("x", "y", "z"), 100, TRUE), |
|
472 |
#' stringsAsFactors = TRUE |
|
473 |
#' ) |
|
474 |
#' |
|
475 |
#' prop_diff_cmh( |
|
476 |
#' rsp = rsp, grp = grp, strata = interaction(strata_data), |
|
477 |
#' conf_level = 0.90 |
|
478 |
#' ) |
|
479 |
#' |
|
480 |
#' @export |
|
481 |
prop_diff_cmh <- function(rsp, |
|
482 |
grp, |
|
483 |
strata, |
|
484 |
conf_level = 0.95) { |
|
485 | 7x |
grp <- as_factor_keep_attributes(grp) |
486 | 7x |
strata <- as_factor_keep_attributes(strata) |
487 | 7x |
check_diff_prop_ci( |
488 | 7x |
rsp = rsp, grp = grp, conf_level = conf_level, strata = strata |
489 |
) |
|
490 | ||
491 | 7x |
if (any(tapply(rsp, strata, length) < 5)) { |
492 | ! |
warning("Less than 5 observations in some strata.") |
493 |
} |
|
494 | ||
495 |
# first dimension: FALSE, TRUE |
|
496 |
# 2nd dimension: CONTROL, TX |
|
497 |
# 3rd dimension: levels of strat |
|
498 |
# rsp as factor rsp to handle edge case of no FALSE (or TRUE) rsp records |
|
499 | 7x |
t_tbl <- table( |
500 | 7x |
factor(rsp, levels = c("FALSE", "TRUE")), |
501 | 7x |
grp, |
502 | 7x |
strata |
503 |
) |
|
504 | 7x |
n1 <- colSums(t_tbl[1:2, 1, ]) |
505 | 7x |
n2 <- colSums(t_tbl[1:2, 2, ]) |
506 | 7x |
p1 <- t_tbl[2, 1, ] / n1 |
507 | 7x |
p2 <- t_tbl[2, 2, ] / n2 |
508 |
# CMH weights |
|
509 | 7x |
use_stratum <- (n1 > 0) & (n2 > 0) |
510 | 7x |
n1 <- n1[use_stratum] |
511 | 7x |
n2 <- n2[use_stratum] |
512 | 7x |
p1 <- p1[use_stratum] |
513 | 7x |
p2 <- p2[use_stratum] |
514 | 7x |
wt <- (n1 * n2 / (n1 + n2)) |
515 | 7x |
wt_normalized <- wt / sum(wt) |
516 | 7x |
est1 <- sum(wt_normalized * p1) |
517 | 7x |
est2 <- sum(wt_normalized * p2) |
518 | 7x |
estimate <- c(est1, est2) |
519 | 7x |
names(estimate) <- levels(grp) |
520 | 7x |
se1 <- sqrt(sum(wt_normalized^2 * p1 * (1 - p1) / n1)) |
521 | 7x |
se2 <- sqrt(sum(wt_normalized^2 * p2 * (1 - p2) / n2)) |
522 | 7x |
z <- stats::qnorm((1 + conf_level) / 2) |
523 | 7x |
err1 <- z * se1 |
524 | 7x |
err2 <- z * se2 |
525 | 7x |
ci1 <- c((est1 - err1), (est1 + err1)) |
526 | 7x |
ci2 <- c((est2 - err2), (est2 + err2)) |
527 | 7x |
estimate_ci <- list(ci1, ci2) |
528 | 7x |
names(estimate_ci) <- levels(grp) |
529 | 7x |
diff_est <- est2 - est1 |
530 | 7x |
se_diff <- sqrt(sum(((p1 * (1 - p1) / n1) + (p2 * (1 - p2) / n2)) * wt_normalized^2)) |
531 | 7x |
diff_ci <- c(diff_est - z * se_diff, diff_est + z * se_diff) |
532 | ||
533 | 7x |
list( |
534 | 7x |
prop = estimate, |
535 | 7x |
prop_ci = estimate_ci, |
536 | 7x |
diff = diff_est, |
537 | 7x |
diff_ci = diff_ci, |
538 | 7x |
weights = wt_normalized, |
539 | 7x |
n1 = n1, |
540 | 7x |
n2 = n2 |
541 |
) |
|
542 |
} |
|
543 | ||
544 |
#' @describeIn h_prop_diff Calculates the stratified `Newcombe` confidence interval and difference in response |
|
545 |
#' rates between the experimental treatment group and the control treatment group, adjusted for stratification |
|
546 |
#' factors. This implementation follows closely the one proposed by \insertCite{Yan2010-jt;textual}{tern}. |
|
547 |
#' Weights can be estimated from the heuristic proposed in [prop_strat_wilson()] or from `CMH`-derived weights |
|
548 |
#' (see [prop_diff_cmh()]). |
|
549 |
#' |
|
550 |
#' @param strata (`factor`)\cr variable with one level per stratum and same length as `rsp`. |
|
551 |
#' @param weights_method (`string`)\cr weights method. Can be either `"cmh"` or `"heuristic"` |
|
552 |
#' and directs the way weights are estimated. |
|
553 |
#' |
|
554 |
#' @references |
|
555 |
#' \insertRef{Yan2010-jt}{tern} |
|
556 |
#' |
|
557 |
#' @examples |
|
558 |
#' # Stratified `Newcombe` confidence interval |
|
559 |
#' |
|
560 |
#' set.seed(2) |
|
561 |
#' data_set <- data.frame( |
|
562 |
#' "rsp" = sample(c(TRUE, FALSE), 100, TRUE), |
|
563 |
#' "f1" = sample(c("a", "b"), 100, TRUE), |
|
564 |
#' "f2" = sample(c("x", "y", "z"), 100, TRUE), |
|
565 |
#' "grp" = sample(c("Placebo", "Treatment"), 100, TRUE), |
|
566 |
#' stringsAsFactors = TRUE |
|
567 |
#' ) |
|
568 |
#' |
|
569 |
#' prop_diff_strat_nc( |
|
570 |
#' rsp = data_set$rsp, grp = data_set$grp, strata = interaction(data_set[2:3]), |
|
571 |
#' weights_method = "cmh", |
|
572 |
#' conf_level = 0.90 |
|
573 |
#' ) |
|
574 |
#' |
|
575 |
#' prop_diff_strat_nc( |
|
576 |
#' rsp = data_set$rsp, grp = data_set$grp, strata = interaction(data_set[2:3]), |
|
577 |
#' weights_method = "wilson_h", |
|
578 |
#' conf_level = 0.90 |
|
579 |
#' ) |
|
580 |
#' |
|
581 |
#' @export |
|
582 |
prop_diff_strat_nc <- function(rsp, |
|
583 |
grp, |
|
584 |
strata, |
|
585 |
weights_method = c("cmh", "wilson_h"), |
|
586 |
conf_level = 0.95, |
|
587 |
correct = FALSE) { |
|
588 | 4x |
weights_method <- match.arg(weights_method) |
589 | 4x |
grp <- as_factor_keep_attributes(grp) |
590 | 4x |
strata <- as_factor_keep_attributes(strata) |
591 | 4x |
check_diff_prop_ci( |
592 | 4x |
rsp = rsp, grp = grp, conf_level = conf_level, strata = strata |
593 |
) |
|
594 | 4x |
checkmate::assert_number(conf_level, lower = 0, upper = 1) |
595 | 4x |
checkmate::assert_flag(correct) |
596 | 4x |
if (any(tapply(rsp, strata, length) < 5)) { |
597 | ! |
warning("Less than 5 observations in some strata.") |
598 |
} |
|
599 | ||
600 | 4x |
rsp_by_grp <- split(rsp, f = grp) |
601 | 4x |
strata_by_grp <- split(strata, f = grp) |
602 | ||
603 |
# Finding the weights |
|
604 | 4x |
weights <- if (identical(weights_method, "cmh")) { |
605 | 3x |
prop_diff_cmh(rsp = rsp, grp = grp, strata = strata)$weights |
606 | 4x |
} else if (identical(weights_method, "wilson_h")) { |
607 | 1x |
prop_strat_wilson(rsp, strata, conf_level = conf_level, correct = correct)$weights |
608 |
} |
|
609 | 4x |
weights[levels(strata)[!levels(strata) %in% names(weights)]] <- 0 |
610 | ||
611 |
# Calculating lower (`l`) and upper (`u`) confidence bounds per group. |
|
612 | 4x |
strat_wilson_by_grp <- Map( |
613 | 4x |
prop_strat_wilson, |
614 | 4x |
rsp = rsp_by_grp, |
615 | 4x |
strata = strata_by_grp, |
616 | 4x |
weights = list(weights, weights), |
617 | 4x |
conf_level = conf_level, |
618 | 4x |
correct = correct |
619 |
) |
|
620 | ||
621 | 4x |
ci_ref <- strat_wilson_by_grp[[1]] |
622 | 4x |
ci_trt <- strat_wilson_by_grp[[2]] |
623 | 4x |
l_ref <- as.numeric(ci_ref$conf_int[1]) |
624 | 4x |
u_ref <- as.numeric(ci_ref$conf_int[2]) |
625 | 4x |
l_trt <- as.numeric(ci_trt$conf_int[1]) |
626 | 4x |
u_trt <- as.numeric(ci_trt$conf_int[2]) |
627 | ||
628 |
# Estimating the diff and n_ref, n_trt (it allows different weights to be used) |
|
629 | 4x |
t_tbl <- table( |
630 | 4x |
factor(rsp, levels = c("FALSE", "TRUE")), |
631 | 4x |
grp, |
632 | 4x |
strata |
633 |
) |
|
634 | 4x |
n_ref <- colSums(t_tbl[1:2, 1, ]) |
635 | 4x |
n_trt <- colSums(t_tbl[1:2, 2, ]) |
636 | 4x |
use_stratum <- (n_ref > 0) & (n_trt > 0) |
637 | 4x |
n_ref <- n_ref[use_stratum] |
638 | 4x |
n_trt <- n_trt[use_stratum] |
639 | 4x |
p_ref <- t_tbl[2, 1, use_stratum] / n_ref |
640 | 4x |
p_trt <- t_tbl[2, 2, use_stratum] / n_trt |
641 | 4x |
est1 <- sum(weights * p_ref) |
642 | 4x |
est2 <- sum(weights * p_trt) |
643 | 4x |
diff_est <- est2 - est1 |
644 | ||
645 | 4x |
lambda1 <- sum(weights^2 / n_ref) |
646 | 4x |
lambda2 <- sum(weights^2 / n_trt) |
647 | 4x |
z <- stats::qnorm((1 + conf_level) / 2) |
648 | ||
649 | 4x |
lower <- diff_est - z * sqrt(lambda2 * l_trt * (1 - l_trt) + lambda1 * u_ref * (1 - u_ref)) |
650 | 4x |
upper <- diff_est + z * sqrt(lambda1 * l_ref * (1 - l_ref) + lambda2 * u_trt * (1 - u_trt)) |
651 | ||
652 | 4x |
list( |
653 | 4x |
"diff" = diff_est, |
654 | 4x |
"diff_ci" = c("lower" = lower, "upper" = upper) |
655 |
) |
|
656 |
} |
1 |
#' Occurrence Table Sorting |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Functions to score occurrence table subtables and rows which can be used in the |
|
6 |
#' sorting of occurrence tables. |
|
7 |
#' |
|
8 |
#' @name score_occurrences |
|
9 |
NULL |
|
10 | ||
11 |
#' @describeIn score_occurrences Scoring function which sums the counts across all |
|
12 |
#' columns. It will fail if anything else but counts are used. |
|
13 |
#' |
|
14 |
#' @inheritParams rtables_access |
|
15 |
#' |
|
16 |
#' @return |
|
17 |
#' * `score_occurrences()` returns the sum of counts across all columns of a table row. |
|
18 |
#' |
|
19 |
#' @seealso [h_row_first_values()] |
|
20 |
#' |
|
21 |
#' @examples |
|
22 |
#' lyt <- basic_table() %>% |
|
23 |
#' split_cols_by("ARM") %>% |
|
24 |
#' add_colcounts() %>% |
|
25 |
#' analyze_num_patients( |
|
26 |
#' vars = "USUBJID", |
|
27 |
#' .stats = c("unique"), |
|
28 |
#' .labels = c("Total number of patients with at least one event") |
|
29 |
#' ) %>% |
|
30 |
#' split_rows_by("AEBODSYS", child_labels = "visible", nested = FALSE) %>% |
|
31 |
#' summarize_num_patients( |
|
32 |
#' var = "USUBJID", |
|
33 |
#' .stats = c("unique", "nonunique"), |
|
34 |
#' .labels = c( |
|
35 |
#' "Total number of patients with at least one event", |
|
36 |
#' "Total number of events" |
|
37 |
#' ) |
|
38 |
#' ) %>% |
|
39 |
#' count_occurrences(vars = "AEDECOD") |
|
40 |
#' |
|
41 |
#' tbl <- build_table(lyt, tern_ex_adae, alt_counts_df = tern_ex_adsl) %>% |
|
42 |
#' prune_table() |
|
43 |
#' |
|
44 |
#' tbl_sorted <- tbl %>% |
|
45 |
#' sort_at_path(path = c("AEBODSYS", "*", "AEDECOD"), scorefun = score_occurrences) |
|
46 |
#' |
|
47 |
#' tbl_sorted |
|
48 |
#' |
|
49 |
#' @export |
|
50 |
score_occurrences <- function(table_row) { |
|
51 | 37x |
row_counts <- h_row_counts(table_row) |
52 | 37x |
sum(row_counts) |
53 |
} |
|
54 | ||
55 |
#' @describeIn score_occurrences Scoring functions can be produced by this constructor to only include |
|
56 |
#' specific columns in the scoring. See [h_row_counts()] for further information. |
|
57 |
#' |
|
58 |
#' @inheritParams has_count_in_cols |
|
59 |
#' |
|
60 |
#' @return |
|
61 |
#' * `score_occurrences_cols()` returns a function that sums counts across all specified columns |
|
62 |
#' of a table row. |
|
63 |
#' |
|
64 |
#' @seealso [h_row_counts()] |
|
65 |
#' |
|
66 |
#' @examples |
|
67 |
#' score_cols_a_and_b <- score_occurrences_cols(col_names = c("A: Drug X", "B: Placebo")) |
|
68 |
#' |
|
69 |
#' # Note that this here just sorts the AEDECOD inside the AEBODSYS. The AEBODSYS are not sorted. |
|
70 |
#' # That would require a second pass of `sort_at_path`. |
|
71 |
#' tbl_sorted <- tbl %>% |
|
72 |
#' sort_at_path(path = c("AEBODSYS", "*", "AEDECOD"), scorefun = score_cols_a_and_b) |
|
73 |
#' |
|
74 |
#' tbl_sorted |
|
75 |
#' |
|
76 |
#' @export |
|
77 |
score_occurrences_cols <- function(...) { |
|
78 | 4x |
function(table_row) { |
79 | 20x |
row_counts <- h_row_counts(table_row, ...) |
80 | 20x |
sum(row_counts) |
81 |
} |
|
82 |
} |
|
83 | ||
84 |
#' @describeIn score_occurrences Scoring functions produced by this constructor can be used on |
|
85 |
#' subtables: They sum up all specified column counts in the subtable. This is useful when |
|
86 |
#' there is no available content row summing up these counts. |
|
87 |
#' |
|
88 |
#' @return |
|
89 |
#' * `score_occurrences_subtable()` returns a function that sums counts in each subtable |
|
90 |
#' across all specified columns. |
|
91 |
#' |
|
92 |
#' @examples |
|
93 |
#' score_subtable_all <- score_occurrences_subtable(col_names = names(tbl)) |
|
94 |
#' |
|
95 |
#' # Note that this code just sorts the AEBODSYS, not the AEDECOD within AEBODSYS. That |
|
96 |
#' # would require a second pass of `sort_at_path`. |
|
97 |
#' tbl_sorted <- tbl %>% |
|
98 |
#' sort_at_path(path = c("AEBODSYS"), scorefun = score_subtable_all, decreasing = FALSE) |
|
99 |
#' |
|
100 |
#' tbl_sorted |
|
101 |
#' |
|
102 |
#' @export |
|
103 |
score_occurrences_subtable <- function(...) { |
|
104 | 1x |
score_table_row <- score_occurrences_cols(...) |
105 | 1x |
function(table_tree) { |
106 | 2x |
table_rows <- collect_leaves(table_tree) |
107 | 2x |
counts <- vapply(table_rows, score_table_row, numeric(1)) |
108 | 2x |
sum(counts) |
109 |
} |
|
110 |
} |
|
111 | ||
112 |
#' @describeIn score_occurrences Produce score function for sorting table by summing the first content row in |
|
113 |
#' specified columns. Note that this is extending [rtables::cont_n_onecol()] and [rtables::cont_n_allcols()]. |
|
114 |
#' |
|
115 |
#' @return |
|
116 |
#' * `score_occurrences_cont_cols()` returns a function that sums counts in the first content row in |
|
117 |
#' specified columns. |
|
118 |
#' |
|
119 |
#' @export |
|
120 |
score_occurrences_cont_cols <- function(...) { |
|
121 | 1x |
score_table_row <- score_occurrences_cols(...) |
122 | 1x |
function(table_tree) { |
123 | 2x |
if (inherits(table_tree, "ContentRow")) { |
124 | ! |
return(NA) |
125 |
} |
|
126 | 2x |
content_row <- h_content_first_row(table_tree) |
127 | 2x |
score_table_row(content_row) |
128 |
} |
|
129 |
} |
1 |
#' Individual Patient Plots |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Line plot(s) displaying trend in patients' parameter values over time is rendered. |
|
6 |
#' Patients' individual baseline values can be added to the plot(s) as reference. |
|
7 |
#' |
|
8 |
#' @inheritParams argument_convention |
|
9 |
#' @param xvar (`string`)\cr time point variable to be plotted on x-axis. |
|
10 |
#' @param yvar (`string`)\cr continuous analysis variable to be plotted on y-axis. |
|
11 |
#' @param xlab (`string`)\cr plot label for x-axis. |
|
12 |
#' @param ylab (`string`)\cr plot label for y-axis. |
|
13 |
#' @param id_var (`string`)\cr variable used as patient identifier. |
|
14 |
#' @param title (`string`)\cr title for plot. |
|
15 |
#' @param subtitle (`string`)\cr subtitle for plot. |
|
16 |
#' @param add_baseline_hline (`flag`)\cr adds horizontal line at baseline y-value on |
|
17 |
#' plot when TRUE. |
|
18 |
#' @param yvar_baseline (`string`)\cr variable with baseline values only. |
|
19 |
#' Ignored when `add_baseline_hline` is FALSE. |
|
20 |
#' @param ggtheme (`theme`)\cr optional graphical theme function as provided |
|
21 |
#' by `ggplot2` to control outlook of plot. Use `ggplot2::theme()` to tweak the display. |
|
22 |
#' @param plotting_choices (`character`)\cr specifies options for displaying |
|
23 |
#' plots. Must be one of "all_in_one", "split_by_max_obs", "separate_by_obs". |
|
24 |
#' @param max_obs_per_plot (`count`)\cr Number of observations to be plotted on one |
|
25 |
#' plot. Ignored when `plotting_choices` is not "separate_by_obs". |
|
26 |
#' @param caption (`character` scalar)\cr optional caption below the plot. |
|
27 |
#' @param col (`character`)\cr lines colors. |
|
28 |
#' |
|
29 |
#' @seealso Relevant helper function [h_g_ipp()]. |
|
30 |
#' |
|
31 |
#' @name individual_patient_plot |
|
32 |
NULL |
|
33 | ||
34 |
#' Helper Function To Create Simple Line Plot over Time |
|
35 |
#' |
|
36 |
#' @description `r lifecycle::badge("stable")` |
|
37 |
#' |
|
38 |
#' Function that generates a simple line plot displaying parameter trends over time. |
|
39 |
#' |
|
40 |
#' @inheritParams argument_convention |
|
41 |
#' @inheritParams g_ipp |
|
42 |
#' |
|
43 |
#' @return A `ggplot` line plot. |
|
44 |
#' |
|
45 |
#' @seealso [g_ipp()] which uses this function. |
|
46 |
#' |
|
47 |
#' @examples |
|
48 |
#' library(dplyr) |
|
49 |
#' library(nestcolor) |
|
50 |
#' |
|
51 |
#' # Select a small sample of data to plot. |
|
52 |
#' adlb <- tern_ex_adlb %>% |
|
53 |
#' filter(PARAMCD == "ALT", !(AVISIT %in% c("SCREENING", "BASELINE"))) %>% |
|
54 |
#' slice(1:36) |
|
55 |
#' |
|
56 |
#' p <- h_g_ipp( |
|
57 |
#' df = adlb, |
|
58 |
#' xvar = "AVISIT", |
|
59 |
#' yvar = "AVAL", |
|
60 |
#' xlab = "Visit", |
|
61 |
#' id_var = "USUBJID", |
|
62 |
#' ylab = "SGOT/ALT (U/L)", |
|
63 |
#' add_baseline_hline = TRUE |
|
64 |
#' ) |
|
65 |
#' p |
|
66 |
#' |
|
67 |
#' @export |
|
68 |
h_g_ipp <- function(df, |
|
69 |
xvar, |
|
70 |
yvar, |
|
71 |
xlab, |
|
72 |
ylab, |
|
73 |
id_var, |
|
74 |
title = "Individual Patient Plots", |
|
75 |
subtitle = "", |
|
76 |
caption = NULL, |
|
77 |
add_baseline_hline = FALSE, |
|
78 |
yvar_baseline = "BASE", |
|
79 |
ggtheme = nestcolor::theme_nest(), |
|
80 |
col = NULL) { |
|
81 | 13x |
checkmate::assert_string(xvar) |
82 | 13x |
checkmate::assert_string(yvar) |
83 | 13x |
checkmate::assert_string(yvar_baseline) |
84 | 13x |
checkmate::assert_string(id_var) |
85 | 13x |
checkmate::assert_string(xlab) |
86 | 13x |
checkmate::assert_string(ylab) |
87 | 13x |
checkmate::assert_string(title) |
88 | 13x |
checkmate::assert_string(subtitle) |
89 | 13x |
checkmate::assert_subset(c(xvar, yvar, yvar_baseline, id_var), colnames(df)) |
90 | 13x |
checkmate::assert_data_frame(df) |
91 | 13x |
checkmate::assert_flag(add_baseline_hline) |
92 | 13x |
checkmate::assert_character(col, null.ok = TRUE) |
93 | ||
94 | 13x |
p <- ggplot2::ggplot( |
95 | 13x |
data = df, |
96 | 13x |
mapping = ggplot2::aes( |
97 | 13x |
x = .data[[xvar]], |
98 | 13x |
y = .data[[yvar]], |
99 | 13x |
group = .data[[id_var]], |
100 | 13x |
colour = .data[[id_var]] |
101 |
) |
|
102 |
) + |
|
103 | 13x |
ggplot2::geom_line(linewidth = 0.4) + |
104 | 13x |
ggplot2::geom_point(size = 2) + |
105 | 13x |
ggplot2::labs( |
106 | 13x |
x = xlab, |
107 | 13x |
y = ylab, |
108 | 13x |
title = title, |
109 | 13x |
subtitle = subtitle, |
110 | 13x |
caption = caption |
111 |
) + |
|
112 | 13x |
ggtheme |
113 | ||
114 | 13x |
if (add_baseline_hline) { |
115 | 12x |
baseline_df <- df[, c(id_var, yvar_baseline)] |
116 | 12x |
baseline_df <- unique(baseline_df) |
117 | ||
118 | 12x |
p <- p + |
119 | 12x |
ggplot2::geom_hline( |
120 | 12x |
data = baseline_df, |
121 | 12x |
mapping = ggplot2::aes( |
122 | 12x |
yintercept = .data[[yvar_baseline]], |
123 | 12x |
colour = .data[[id_var]] |
124 |
), |
|
125 | 12x |
linetype = "dotdash", |
126 | 12x |
linewidth = 0.4 |
127 |
) + |
|
128 | 12x |
ggplot2::geom_text( |
129 | 12x |
data = baseline_df, |
130 | 12x |
mapping = ggplot2::aes( |
131 | 12x |
x = 1, |
132 | 12x |
y = .data[[yvar_baseline]], |
133 | 12x |
label = .data[[id_var]], |
134 | 12x |
colour = .data[[id_var]] |
135 |
), |
|
136 | 12x |
nudge_y = 0.025 * (max(df[, yvar], na.rm = TRUE) - min(df[, yvar], na.rm = TRUE)), |
137 | 12x |
vjust = "right", |
138 | 12x |
size = 2 |
139 |
) |
|
140 | ||
141 | 12x |
if (!is.null(col)) { |
142 | 1x |
p <- p + |
143 | 1x |
ggplot2::scale_color_manual(values = col) |
144 |
} |
|
145 |
} |
|
146 | 13x |
p |
147 |
} |
|
148 | ||
149 |
#' @describeIn individual_patient_plot Plotting function for individual patient plots which, depending on user |
|
150 |
#' preference, renders a single graphic or compiles a list of graphics that show trends in individual's parameter |
|
151 |
#' values over time. |
|
152 |
#' |
|
153 |
#' @return A `ggplot` object or a list of `ggplot` objects. |
|
154 |
#' |
|
155 |
#' @examples |
|
156 |
#' library(dplyr) |
|
157 |
#' library(nestcolor) |
|
158 |
#' |
|
159 |
#' # Select a small sample of data to plot. |
|
160 |
#' adlb <- tern_ex_adlb %>% |
|
161 |
#' filter(PARAMCD == "ALT", !(AVISIT %in% c("SCREENING", "BASELINE"))) %>% |
|
162 |
#' slice(1:36) |
|
163 |
#' |
|
164 |
#' plot_list <- g_ipp( |
|
165 |
#' df = adlb, |
|
166 |
#' xvar = "AVISIT", |
|
167 |
#' yvar = "AVAL", |
|
168 |
#' xlab = "Visit", |
|
169 |
#' ylab = "SGOT/ALT (U/L)", |
|
170 |
#' title = "Individual Patient Plots", |
|
171 |
#' add_baseline_hline = TRUE, |
|
172 |
#' plotting_choices = "split_by_max_obs", |
|
173 |
#' max_obs_per_plot = 5 |
|
174 |
#' ) |
|
175 |
#' plot_list |
|
176 |
#' |
|
177 |
#' @export |
|
178 |
g_ipp <- function(df, |
|
179 |
xvar, |
|
180 |
yvar, |
|
181 |
xlab, |
|
182 |
ylab, |
|
183 |
id_var = "USUBJID", |
|
184 |
title = "Individual Patient Plots", |
|
185 |
subtitle = "", |
|
186 |
caption = NULL, |
|
187 |
add_baseline_hline = FALSE, |
|
188 |
yvar_baseline = "BASE", |
|
189 |
ggtheme = nestcolor::theme_nest(), |
|
190 |
plotting_choices = c("all_in_one", "split_by_max_obs", "separate_by_obs"), |
|
191 |
max_obs_per_plot = 4, |
|
192 |
col = NULL) { |
|
193 | 3x |
checkmate::assert_count(max_obs_per_plot) |
194 | 3x |
checkmate::assert_subset(plotting_choices, c("all_in_one", "split_by_max_obs", "separate_by_obs")) |
195 | 3x |
checkmate::assert_character(col, null.ok = TRUE) |
196 | ||
197 | 3x |
plotting_choices <- match.arg(plotting_choices) |
198 | ||
199 | 3x |
if (plotting_choices == "all_in_one") { |
200 | 1x |
p <- h_g_ipp( |
201 | 1x |
df = df, |
202 | 1x |
xvar = xvar, |
203 | 1x |
yvar = yvar, |
204 | 1x |
xlab = xlab, |
205 | 1x |
ylab = ylab, |
206 | 1x |
id_var = id_var, |
207 | 1x |
title = title, |
208 | 1x |
subtitle = subtitle, |
209 | 1x |
caption = caption, |
210 | 1x |
add_baseline_hline = add_baseline_hline, |
211 | 1x |
yvar_baseline = yvar_baseline, |
212 | 1x |
ggtheme = ggtheme, |
213 | 1x |
col = col |
214 |
) |
|
215 | ||
216 | 1x |
return(p) |
217 | 2x |
} else if (plotting_choices == "split_by_max_obs") { |
218 | 1x |
id_vec <- unique(df[[id_var]]) |
219 | 1x |
id_list <- split( |
220 | 1x |
id_vec, |
221 | 1x |
rep(1:ceiling(length(id_vec) / max_obs_per_plot), |
222 | 1x |
each = max_obs_per_plot, |
223 | 1x |
length.out = length(id_vec) |
224 |
) |
|
225 |
) |
|
226 | ||
227 | 1x |
df_list <- list() |
228 | 1x |
plot_list <- list() |
229 | ||
230 | 1x |
for (i in seq_along(id_list)) { |
231 | 2x |
df_list[[i]] <- df[df[[id_var]] %in% id_list[[i]], ] |
232 | ||
233 | 2x |
plots <- h_g_ipp( |
234 | 2x |
df = df_list[[i]], |
235 | 2x |
xvar = xvar, |
236 | 2x |
yvar = yvar, |
237 | 2x |
xlab = xlab, |
238 | 2x |
ylab = ylab, |
239 | 2x |
id_var = id_var, |
240 | 2x |
title = title, |
241 | 2x |
subtitle = subtitle, |
242 | 2x |
caption = caption, |
243 | 2x |
add_baseline_hline = add_baseline_hline, |
244 | 2x |
yvar_baseline = yvar_baseline, |
245 | 2x |
ggtheme = ggtheme, |
246 | 2x |
col = col |
247 |
) |
|
248 | ||
249 | 2x |
plot_list[[i]] <- plots |
250 |
} |
|
251 | 1x |
return(plot_list) |
252 |
} else { |
|
253 | 1x |
ind_df <- split(df, df[[id_var]]) |
254 | 1x |
plot_list <- lapply( |
255 | 1x |
ind_df, |
256 | 1x |
function(x) { |
257 | 8x |
h_g_ipp( |
258 | 8x |
df = x, |
259 | 8x |
xvar = xvar, |
260 | 8x |
yvar = yvar, |
261 | 8x |
xlab = xlab, |
262 | 8x |
ylab = ylab, |
263 | 8x |
id_var = id_var, |
264 | 8x |
title = title, |
265 | 8x |
subtitle = subtitle, |
266 | 8x |
caption = caption, |
267 | 8x |
add_baseline_hline = add_baseline_hline, |
268 | 8x |
yvar_baseline = yvar_baseline, |
269 | 8x |
ggtheme = ggtheme, |
270 | 8x |
col = col |
271 |
) |
|
272 |
} |
|
273 |
) |
|
274 | ||
275 | 1x |
return(plot_list) |
276 |
} |
|
277 |
} |
1 |
#' Patient Counts with the Most Extreme Post-baseline Toxicity Grade per Direction of Abnormality |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Primary analysis variable `.var` indicates the toxicity grade (`factor`), and additional |
|
6 |
#' analysis variables are `id` (`character` or `factor`), `param` (`factor`) and `grade_dir` (`factor`). |
|
7 |
#' The pre-processing steps are crucial when using this function. |
|
8 |
#' For a certain direction (e.g. high or low) this function counts |
|
9 |
#' patients in the denominator as number of patients with at least one valid measurement during treatment, |
|
10 |
#' and patients in the numerator as follows: |
|
11 |
#' * `1` to `4`: Numerator is number of patients with worst grades 1-4 respectively; |
|
12 |
#' * `Any`: Numerator is number of patients with at least one abnormality, which means grade is different from 0. |
|
13 |
#' |
|
14 |
#' Pre-processing is crucial when using this function and can be done automatically using the |
|
15 |
#' [h_adlb_abnormal_by_worst_grade()] helper function. See the description of this function for details on the |
|
16 |
#' necessary pre-processing steps. |
|
17 |
#' |
|
18 |
#' @inheritParams argument_convention |
|
19 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("abnormal_by_worst_grade")` |
|
20 |
#' to see available statistics for this function. |
|
21 |
#' |
|
22 |
#' @seealso [h_adlb_abnormal_by_worst_grade()] which pre-processes `ADLB` data frames to be used in |
|
23 |
#' [count_abnormal_by_worst_grade()]. |
|
24 |
#' |
|
25 |
#' @name abnormal_by_worst_grade |
|
26 |
#' @order 1 |
|
27 |
NULL |
|
28 | ||
29 |
#' @describeIn abnormal_by_worst_grade Statistics function which counts patients by worst grade. |
|
30 |
#' |
|
31 |
#' @return |
|
32 |
#' * `s_count_abnormal_by_worst_grade()` returns the single statistic `count_fraction` with grades 1 to 4 and |
|
33 |
#' "Any" results. |
|
34 |
#' |
|
35 |
#' @keywords internal |
|
36 |
s_count_abnormal_by_worst_grade <- function(df, # nolint |
|
37 |
.var = "GRADE_ANL", |
|
38 |
.spl_context, |
|
39 |
variables = list( |
|
40 |
id = "USUBJID", |
|
41 |
param = "PARAM", |
|
42 |
grade_dir = "GRADE_DIR" |
|
43 |
)) { |
|
44 | 1x |
checkmate::assert_string(.var) |
45 | 1x |
assert_valid_factor(df[[.var]]) |
46 | 1x |
assert_valid_factor(df[[variables$param]]) |
47 | 1x |
assert_valid_factor(df[[variables$grade_dir]]) |
48 | 1x |
assert_df_with_variables(df, c(a = .var, variables)) |
49 | 1x |
checkmate::assert_multi_class(df[[variables$id]], classes = c("factor", "character")) |
50 | ||
51 |
# To verify that the `split_rows_by` are performed with correct variables. |
|
52 | 1x |
checkmate::assert_subset(c(variables[["param"]], variables[["grade_dir"]]), .spl_context$split) |
53 | 1x |
first_row <- .spl_context[.spl_context$split == variables[["param"]], ] |
54 | 1x |
x_lvls <- c(setdiff(levels(df[[.var]]), "0"), "Any") |
55 | 1x |
result <- split(numeric(0), factor(x_lvls)) |
56 | ||
57 | 1x |
subj <- first_row$full_parent_df[[1]][[variables[["id"]]]] |
58 | 1x |
subj_cur_col <- subj[first_row$cur_col_subset[[1]]] |
59 |
# Some subjects may have a record for high and low directions but |
|
60 |
# should be counted only once. |
|
61 | 1x |
denom <- length(unique(subj_cur_col)) |
62 | ||
63 | 1x |
for (lvl in x_lvls) { |
64 | 5x |
if (lvl != "Any") { |
65 | 4x |
df_lvl <- df[df[[.var]] == lvl, ] |
66 |
} else { |
|
67 | 1x |
df_lvl <- df[df[[.var]] != 0, ] |
68 |
} |
|
69 | 5x |
num <- length(unique(df_lvl[[variables[["id"]]]])) |
70 | 5x |
fraction <- ifelse(denom == 0, 0, num / denom) |
71 | 5x |
result[[lvl]] <- formatters::with_label(c(count = num, fraction = fraction), lvl) |
72 |
} |
|
73 | ||
74 | 1x |
result <- list(count_fraction = result) |
75 | 1x |
result |
76 |
} |
|
77 | ||
78 |
#' @describeIn abnormal_by_worst_grade Formatted analysis function which is used as `afun` |
|
79 |
#' in `count_abnormal_by_worst_grade()`. |
|
80 |
#' |
|
81 |
#' @return |
|
82 |
#' * `a_count_abnormal_by_worst_grade()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
83 |
#' |
|
84 |
#' @keywords internal |
|
85 |
a_count_abnormal_by_worst_grade <- make_afun( # nolint |
|
86 |
s_count_abnormal_by_worst_grade, |
|
87 |
.formats = c(count_fraction = format_count_fraction) |
|
88 |
) |
|
89 | ||
90 |
#' @describeIn abnormal_by_worst_grade Layout-creating function which can take statistics function arguments |
|
91 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
92 |
#' |
|
93 |
#' @return |
|
94 |
#' * `count_abnormal_by_worst_grade()` returns a layout object suitable for passing to further layouting functions, |
|
95 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
96 |
#' the statistics from `s_count_abnormal_by_worst_grade()` to the table layout. |
|
97 |
#' |
|
98 |
#' @examples |
|
99 |
#' library(dplyr) |
|
100 |
#' library(forcats) |
|
101 |
#' adlb <- tern_ex_adlb |
|
102 |
#' |
|
103 |
#' # Data is modified in order to have some parameters with grades only in one direction |
|
104 |
#' # and simulate the real data. |
|
105 |
#' adlb$ATOXGR[adlb$PARAMCD == "ALT" & adlb$ATOXGR %in% c("1", "2", "3", "4")] <- "-1" |
|
106 |
#' adlb$ANRIND[adlb$PARAMCD == "ALT" & adlb$ANRIND == "HIGH"] <- "LOW" |
|
107 |
#' adlb$WGRHIFL[adlb$PARAMCD == "ALT"] <- "" |
|
108 |
#' |
|
109 |
#' adlb$ATOXGR[adlb$PARAMCD == "IGA" & adlb$ATOXGR %in% c("-1", "-2", "-3", "-4")] <- "1" |
|
110 |
#' adlb$ANRIND[adlb$PARAMCD == "IGA" & adlb$ANRIND == "LOW"] <- "HIGH" |
|
111 |
#' adlb$WGRLOFL[adlb$PARAMCD == "IGA"] <- "" |
|
112 |
#' |
|
113 |
#' # Pre-processing |
|
114 |
#' adlb_f <- adlb %>% h_adlb_abnormal_by_worst_grade() |
|
115 |
#' |
|
116 |
#' # Map excludes records without abnormal grade since they should not be displayed |
|
117 |
#' # in the table. |
|
118 |
#' map <- unique(adlb_f[adlb_f$GRADE_DIR != "ZERO", c("PARAM", "GRADE_DIR", "GRADE_ANL")]) %>% |
|
119 |
#' lapply(as.character) %>% |
|
120 |
#' as.data.frame() %>% |
|
121 |
#' arrange(PARAM, desc(GRADE_DIR), GRADE_ANL) |
|
122 |
#' |
|
123 |
#' basic_table() %>% |
|
124 |
#' split_cols_by("ARMCD") %>% |
|
125 |
#' split_rows_by("PARAM") %>% |
|
126 |
#' split_rows_by("GRADE_DIR", split_fun = trim_levels_to_map(map)) %>% |
|
127 |
#' count_abnormal_by_worst_grade( |
|
128 |
#' var = "GRADE_ANL", |
|
129 |
#' variables = list(id = "USUBJID", param = "PARAM", grade_dir = "GRADE_DIR") |
|
130 |
#' ) %>% |
|
131 |
#' build_table(df = adlb_f) |
|
132 |
#' |
|
133 |
#' @export |
|
134 |
#' @order 2 |
|
135 |
count_abnormal_by_worst_grade <- function(lyt, |
|
136 |
var, |
|
137 |
variables = list( |
|
138 |
id = "USUBJID", |
|
139 |
param = "PARAM", |
|
140 |
grade_dir = "GRADE_DIR" |
|
141 |
), |
|
142 |
na_str = default_na_str(), |
|
143 |
nested = TRUE, |
|
144 |
..., |
|
145 |
.stats = NULL, |
|
146 |
.formats = NULL, |
|
147 |
.labels = NULL, |
|
148 |
.indent_mods = NULL) { |
|
149 | 2x |
extra_args <- list(variables = variables, ...) |
150 | ||
151 | 2x |
afun <- make_afun( |
152 | 2x |
a_count_abnormal_by_worst_grade, |
153 | 2x |
.stats = .stats, |
154 | 2x |
.formats = .formats, |
155 | 2x |
.labels = .labels, |
156 | 2x |
.indent_mods = .indent_mods, |
157 | 2x |
.ungroup_stats = "count_fraction" |
158 |
) |
|
159 | 2x |
analyze( |
160 | 2x |
lyt = lyt, |
161 | 2x |
vars = var, |
162 | 2x |
afun = afun, |
163 | 2x |
na_str = na_str, |
164 | 2x |
nested = nested, |
165 | 2x |
extra_args = extra_args, |
166 | 2x |
show_labels = "hidden" |
167 |
) |
|
168 |
} |
|
169 | ||
170 |
#' Helper function to prepare `ADLB` for [count_abnormal_by_worst_grade()] |
|
171 |
#' |
|
172 |
#' @description `r lifecycle::badge("stable")` |
|
173 |
#' |
|
174 |
#' Helper function to prepare an `ADLB` data frame to be used as input in |
|
175 |
#' [count_abnormal_by_worst_grade()]. The following pre-processing steps are applied: |
|
176 |
#' |
|
177 |
#' 1. `adlb` is filtered on variable `avisit` to only include post-baseline visits. |
|
178 |
#' 2. `adlb` is filtered on variables `worst_flag_low` and `worst_flag_high` so that only |
|
179 |
#' worst grades (in either direction) are included. |
|
180 |
#' 3. From the standard lab grade variable `atoxgr`, the following two variables are derived |
|
181 |
#' and added to `adlb`: |
|
182 |
#' * A grade direction variable (e.g. `GRADE_DIR`). The variable takes value `"HIGH"` when |
|
183 |
#' `atoxgr > 0`, `"LOW"` when `atoxgr < 0`, and `"ZERO"` otherwise. |
|
184 |
#' * A toxicity grade variable (e.g. `GRADE_ANL`) where all negative values from `atoxgr` are |
|
185 |
#' replaced by their absolute values. |
|
186 |
#' 4. Unused factor levels are dropped from `adlb` via [droplevels()]. |
|
187 |
#' |
|
188 |
#' @param adlb (`data.frame`)\cr `ADLB` dataframe. |
|
189 |
#' @param atoxgr (`character`)\cr Analysis toxicity grade variable. This must be a `factor` |
|
190 |
#' variable. |
|
191 |
#' @param avisit (`character`)\cr Analysis visit variable. |
|
192 |
#' @param worst_flag_low (`character`)\cr Worst low lab grade flag variable. This variable is |
|
193 |
#' set to `"Y"` when indicating records of worst low lab grades. |
|
194 |
#' @param worst_flag_high (`character`)\cr Worst high lab grade flag variable. This variable is |
|
195 |
#' set to `"Y"` when indicating records of worst high lab grades. |
|
196 |
#' |
|
197 |
#' @return `h_adlb_abnormal_by_worst_grade()` returns the `adlb` data frame with two new |
|
198 |
#' variables: `GRADE_DIR` and `GRADE_ANL`. |
|
199 |
#' |
|
200 |
#' @seealso [abnormal_by_worst_grade] |
|
201 |
#' |
|
202 |
#' @examples |
|
203 |
#' h_adlb_abnormal_by_worst_grade(tern_ex_adlb) %>% |
|
204 |
#' dplyr::select(ATOXGR, GRADE_DIR, GRADE_ANL) %>% |
|
205 |
#' head(10) |
|
206 |
#' |
|
207 |
#' @export |
|
208 |
h_adlb_abnormal_by_worst_grade <- function(adlb, |
|
209 |
atoxgr = "ATOXGR", |
|
210 |
avisit = "AVISIT", |
|
211 |
worst_flag_low = "WGRLOFL", |
|
212 |
worst_flag_high = "WGRHIFL") { |
|
213 | 1x |
adlb %>% |
214 | 1x |
dplyr::filter( |
215 | 1x |
!.data[[avisit]] %in% c("SCREENING", "BASELINE"), |
216 | 1x |
.data[[worst_flag_low]] == "Y" | .data[[worst_flag_high]] == "Y" |
217 |
) %>% |
|
218 | 1x |
dplyr::mutate( |
219 | 1x |
GRADE_DIR = factor( |
220 | 1x |
dplyr::case_when( |
221 | 1x |
.data[[atoxgr]] %in% c("-1", "-2", "-3", "-4") ~ "LOW", |
222 | 1x |
.data[[atoxgr]] == "0" ~ "ZERO", |
223 | 1x |
.data[[atoxgr]] %in% c("1", "2", "3", "4") ~ "HIGH" |
224 |
), |
|
225 | 1x |
levels = c("LOW", "ZERO", "HIGH") |
226 |
), |
|
227 | 1x |
GRADE_ANL = forcats::fct_relevel( |
228 | 1x |
forcats::fct_recode(.data[[atoxgr]], `1` = "-1", `2` = "-2", `3` = "-3", `4` = "-4"), |
229 | 1x |
c("0", "1", "2", "3", "4") |
230 |
) |
|
231 |
) %>% |
|
232 | 1x |
droplevels() |
233 |
} |
1 |
#' Sort Data by `PK PARAM` Variable |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' @param pk_data (`data.frame`)\cr `Pharmacokinetics` dataframe |
|
6 |
#' @param key_var (`character`)\cr key variable used to merge pk_data and metadata created by `d_pkparam()` |
|
7 |
#' |
|
8 |
#' @return A PK `data.frame` sorted by a `PARAM` variable. |
|
9 |
#' |
|
10 |
#' @examples |
|
11 |
#' library(dplyr) |
|
12 |
#' |
|
13 |
#' adpp <- tern_ex_adpp %>% mutate(PKPARAM = factor(paste0(PARAM, " (", AVALU, ")"))) |
|
14 |
#' pk_ordered_data <- h_pkparam_sort(adpp) |
|
15 |
#' |
|
16 |
#' @export |
|
17 |
h_pkparam_sort <- function(pk_data, key_var = "PARAMCD") { |
|
18 | 4x |
assert_df_with_variables(pk_data, list(key_var = key_var)) |
19 | 4x |
pk_data$PARAMCD <- pk_data[[key_var]] |
20 | ||
21 | 4x |
ordered_pk_data <- d_pkparam() |
22 | ||
23 |
# Add the numeric values from ordered_pk_data to pk_data |
|
24 | 4x |
joined_data <- merge(pk_data, ordered_pk_data, by = "PARAMCD", suffix = c("", ".y")) |
25 | ||
26 | 4x |
joined_data <- joined_data[, -grep(".*.y$", colnames(joined_data))] |
27 | ||
28 | 4x |
joined_data$TLG_ORDER <- as.numeric(joined_data$TLG_ORDER) |
29 | ||
30 |
# Then order PARAM based on this column |
|
31 | 4x |
joined_data$PARAM <- factor(joined_data$PARAM, |
32 | 4x |
levels = unique(joined_data$PARAM[order(joined_data$TLG_ORDER)]), |
33 | 4x |
ordered = TRUE |
34 |
) |
|
35 | ||
36 | 4x |
joined_data$TLG_DISPLAY <- factor(joined_data$TLG_DISPLAY, |
37 | 4x |
levels = unique(joined_data$TLG_DISPLAY[order(joined_data$TLG_ORDER)]), |
38 | 4x |
ordered = TRUE |
39 |
) |
|
40 | ||
41 | 4x |
joined_data |
42 |
} |
1 |
#' Control Function for `CoxPH` Model |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' This is an auxiliary function for controlling arguments for `CoxPH` model, typically used internally to specify |
|
6 |
#' details of `CoxPH` model for [s_coxph_pairwise()]. `conf_level` refers to Hazard Ratio estimation. |
|
7 |
#' |
|
8 |
#' @inheritParams argument_convention |
|
9 |
#' @param pval_method (`string`)\cr p-value method for testing hazard ratio = 1. |
|
10 |
#' Default method is `"log-rank"`, can also be set to `"wald"` or `"likelihood"`. |
|
11 |
#' @param ties (`string`)\cr specifying the method for tie handling. Default is `"efron"`, |
|
12 |
#' can also be set to `"breslow"` or `"exact"`. See more in [survival::coxph()]. |
|
13 |
#' |
|
14 |
#' @return A list of components with the same names as the arguments |
|
15 |
#' |
|
16 |
#' @export |
|
17 |
control_coxph <- function(pval_method = c("log-rank", "wald", "likelihood"), |
|
18 |
ties = c("efron", "breslow", "exact"), |
|
19 |
conf_level = 0.95) { |
|
20 | 45x |
pval_method <- match.arg(pval_method) |
21 | 44x |
ties <- match.arg(ties) |
22 | 44x |
assert_proportion_value(conf_level) |
23 | ||
24 | 43x |
list(pval_method = pval_method, ties = ties, conf_level = conf_level) |
25 |
} |
|
26 | ||
27 |
#' Control Function for `survfit` Model for Survival Time |
|
28 |
#' |
|
29 |
#' @description `r lifecycle::badge("stable")` |
|
30 |
#' |
|
31 |
#' This is an auxiliary function for controlling arguments for `survfit` model, typically used internally to specify |
|
32 |
#' details of `survfit` model for [s_surv_time()]. `conf_level` refers to survival time estimation. |
|
33 |
#' |
|
34 |
#' @inheritParams argument_convention |
|
35 |
#' @param conf_type (`string`)\cr confidence interval type. Options are "plain" (default), "log", "log-log", |
|
36 |
#' see more in [survival::survfit()]. Note option "none" is no longer supported. |
|
37 |
#' @param quantiles (`numeric`)\cr of length two to specify the quantiles of survival time. |
|
38 |
#' |
|
39 |
#' @return A list of components with the same names as the arguments |
|
40 |
#' |
|
41 |
#' @export |
|
42 |
control_surv_time <- function(conf_level = 0.95, |
|
43 |
conf_type = c("plain", "log", "log-log"), |
|
44 |
quantiles = c(0.25, 0.75)) { |
|
45 | 179x |
conf_type <- match.arg(conf_type) |
46 | 178x |
checkmate::assert_numeric(quantiles, lower = 0, upper = 1, len = 2, unique = TRUE, sorted = TRUE) |
47 | 177x |
nullo <- lapply(quantiles, assert_proportion_value) |
48 | 177x |
assert_proportion_value(conf_level) |
49 | 176x |
list(conf_level = conf_level, conf_type = conf_type, quantiles = quantiles) |
50 |
} |
|
51 | ||
52 |
#' Control Function for `survfit` Model for Patient's Survival Rate at time point |
|
53 |
#' |
|
54 |
#' @description `r lifecycle::badge("stable")` |
|
55 |
#' |
|
56 |
#' This is an auxiliary function for controlling arguments for `survfit` model, typically used internally to specify |
|
57 |
#' details of `survfit` model for [s_surv_timepoint()]. `conf_level` refers to patient risk estimation at a time point. |
|
58 |
#' |
|
59 |
#' @inheritParams argument_convention |
|
60 |
#' @inheritParams control_surv_time |
|
61 |
#' |
|
62 |
#' @return A list of components with the same names as the arguments |
|
63 |
#' |
|
64 |
#' @export |
|
65 |
control_surv_timepoint <- function(conf_level = 0.95, |
|
66 |
conf_type = c("plain", "log", "log-log")) { |
|
67 | 23x |
conf_type <- match.arg(conf_type) |
68 | 22x |
assert_proportion_value(conf_level) |
69 | 21x |
list( |
70 | 21x |
conf_level = conf_level, |
71 | 21x |
conf_type = conf_type |
72 |
) |
|
73 |
} |
1 |
#' Occurrence Table Pruning |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Family of constructor and condition functions to flexibly prune occurrence tables. |
|
6 |
#' The condition functions always return whether the row result is higher than the threshold. |
|
7 |
#' Since they are of class [CombinationFunction()] they can be logically combined with other condition |
|
8 |
#' functions. |
|
9 |
#' |
|
10 |
#' @note Since most table specifications are worded positively, we name our constructor and condition |
|
11 |
#' functions positively, too. However, note that the result of [keep_rows()] says what |
|
12 |
#' should be pruned, to conform with the [rtables::prune_table()] interface. |
|
13 |
#' |
|
14 |
#' @examples |
|
15 |
#' \donttest{ |
|
16 |
#' tab <- basic_table() %>% |
|
17 |
#' split_cols_by("ARM") %>% |
|
18 |
#' split_rows_by("RACE") %>% |
|
19 |
#' split_rows_by("STRATA1") %>% |
|
20 |
#' summarize_row_groups() %>% |
|
21 |
#' analyze_vars("COUNTRY", .stats = "count_fraction") %>% |
|
22 |
#' build_table(DM) |
|
23 |
#' } |
|
24 |
#' |
|
25 |
#' @name prune_occurrences |
|
26 |
NULL |
|
27 | ||
28 |
#' @describeIn prune_occurrences Constructor for creating pruning functions based on |
|
29 |
#' a row condition function. This removes all analysis rows (`TableRow`) that should be |
|
30 |
#' pruned, i.e., don't fulfill the row condition. It removes the sub-tree if there are no |
|
31 |
#' children left. |
|
32 |
#' |
|
33 |
#' @param row_condition (`CombinationFunction`)\cr condition function which works on individual |
|
34 |
#' analysis rows and flags whether these should be kept in the pruned table. |
|
35 |
#' |
|
36 |
#' @return |
|
37 |
#' * `keep_rows()` returns a pruning function that can be used with [rtables::prune_table()] |
|
38 |
#' to prune an `rtables` table. |
|
39 |
#' |
|
40 |
#' @examples |
|
41 |
#' \donttest{ |
|
42 |
#' # `keep_rows` |
|
43 |
#' is_non_empty <- !CombinationFunction(all_zero_or_na) |
|
44 |
#' prune_table(tab, keep_rows(is_non_empty)) |
|
45 |
#' } |
|
46 |
#' |
|
47 |
#' @export |
|
48 |
keep_rows <- function(row_condition) { |
|
49 | 6x |
checkmate::assert_function(row_condition) |
50 | 6x |
function(table_tree) { |
51 | 2256x |
if (inherits(table_tree, "TableRow")) { |
52 | 1872x |
return(!row_condition(table_tree)) |
53 |
} |
|
54 | 384x |
children <- tree_children(table_tree) |
55 | 384x |
identical(length(children), 0L) |
56 |
} |
|
57 |
} |
|
58 | ||
59 |
#' @describeIn prune_occurrences Constructor for creating pruning functions based on |
|
60 |
#' a condition for the (first) content row in leaf tables. This removes all leaf tables where |
|
61 |
#' the first content row does not fulfill the condition. It does not check individual rows. |
|
62 |
#' It then proceeds recursively by removing the sub tree if there are no children left. |
|
63 |
#' |
|
64 |
#' @param content_row_condition (`CombinationFunction`)\cr condition function which works on individual |
|
65 |
#' first content rows of leaf tables and flags whether these leaf tables should be kept in the pruned table. |
|
66 |
#' |
|
67 |
#' @return |
|
68 |
#' * `keep_content_rows()` returns a pruning function that checks the condition on the first content |
|
69 |
#' row of leaf tables in the table. |
|
70 |
#' |
|
71 |
#' @examples |
|
72 |
#' # `keep_content_rows` |
|
73 |
#' \donttest{ |
|
74 |
#' more_than_twenty <- has_count_in_cols(atleast = 20L, col_names = names(tab)) |
|
75 |
#' prune_table(tab, keep_content_rows(more_than_twenty)) |
|
76 |
#' } |
|
77 |
#' |
|
78 |
#' @export |
|
79 |
keep_content_rows <- function(content_row_condition) { |
|
80 | 1x |
checkmate::assert_function(content_row_condition) |
81 | 1x |
function(table_tree) { |
82 | 166x |
if (is_leaf_table(table_tree)) { |
83 | 24x |
content_row <- h_content_first_row(table_tree) |
84 | 24x |
return(!content_row_condition(content_row)) |
85 |
} |
|
86 | 142x |
if (inherits(table_tree, "DataRow")) { |
87 | 120x |
return(FALSE) |
88 |
} |
|
89 | 22x |
children <- tree_children(table_tree) |
90 | 22x |
identical(length(children), 0L) |
91 |
} |
|
92 |
} |
|
93 | ||
94 |
#' @describeIn prune_occurrences Constructor for creating condition functions on total counts in the specified columns. |
|
95 |
#' |
|
96 |
#' @param atleast (`count` or `proportion`)\cr threshold which should be met in order to keep the row. |
|
97 |
#' @param ... arguments for row or column access, see [`rtables_access`]: either `col_names` (`character`) including |
|
98 |
#' the names of the columns which should be used, or alternatively `col_indices` (`integer`) giving the indices |
|
99 |
#' directly instead. |
|
100 |
#' |
|
101 |
#' @return |
|
102 |
#' * `has_count_in_cols()` returns a condition function that sums the counts in the specified column. |
|
103 |
#' |
|
104 |
#' @examples |
|
105 |
#' \donttest{ |
|
106 |
#' more_than_one <- has_count_in_cols(atleast = 1L, col_names = names(tab)) |
|
107 |
#' prune_table(tab, keep_rows(more_than_one)) |
|
108 |
#' } |
|
109 |
#' |
|
110 |
#' @export |
|
111 |
has_count_in_cols <- function(atleast, ...) { |
|
112 | 3x |
checkmate::assert_count(atleast) |
113 | 3x |
CombinationFunction(function(table_row) { |
114 | 334x |
row_counts <- h_row_counts(table_row, ...) |
115 | 334x |
total_count <- sum(row_counts) |
116 | 334x |
total_count >= atleast |
117 |
}) |
|
118 |
} |
|
119 | ||
120 |
#' @describeIn prune_occurrences Constructor for creating condition functions on any of the counts in |
|
121 |
#' the specified columns satisfying a threshold. |
|
122 |
#' |
|
123 |
#' @param atleast (`count` or `proportion`)\cr threshold which should be met in order to keep the row. |
|
124 |
#' |
|
125 |
#' @return |
|
126 |
#' * `has_count_in_any_col()` returns a condition function that compares the counts in the |
|
127 |
#' specified columns with the threshold. |
|
128 |
#' |
|
129 |
#' @examples |
|
130 |
#' \donttest{ |
|
131 |
#' # `has_count_in_any_col` |
|
132 |
#' any_more_than_one <- has_count_in_any_col(atleast = 1L, col_names = names(tab)) |
|
133 |
#' prune_table(tab, keep_rows(any_more_than_one)) |
|
134 |
#' } |
|
135 |
#' |
|
136 |
#' @export |
|
137 |
has_count_in_any_col <- function(atleast, ...) { |
|
138 | ! |
checkmate::assert_count(atleast) |
139 | ! |
CombinationFunction(function(table_row) { |
140 | ! |
row_counts <- h_row_counts(table_row, ...) |
141 | ! |
any(row_counts >= atleast) |
142 |
}) |
|
143 |
} |
|
144 | ||
145 |
#' @describeIn prune_occurrences Constructor for creating condition functions on total fraction in |
|
146 |
#' the specified columns. |
|
147 |
#' |
|
148 |
#' @return |
|
149 |
#' * `has_fraction_in_cols()` returns a condition function that sums the counts in the |
|
150 |
#' specified column, and computes the fraction by dividing by the total column counts. |
|
151 |
#' |
|
152 |
#' @examples |
|
153 |
#' \donttest{ |
|
154 |
#' # `has_fraction_in_cols` |
|
155 |
#' more_than_five_percent <- has_fraction_in_cols(atleast = 0.05, col_names = names(tab)) |
|
156 |
#' prune_table(tab, keep_rows(more_than_five_percent)) |
|
157 |
#' } |
|
158 |
#' |
|
159 |
#' @export |
|
160 |
has_fraction_in_cols <- function(atleast, ...) { |
|
161 | 1x |
assert_proportion_value(atleast, include_boundaries = TRUE) |
162 | 1x |
CombinationFunction(function(table_row) { |
163 | 303x |
row_counts <- h_row_counts(table_row, ...) |
164 | 303x |
total_count <- sum(row_counts) |
165 | 303x |
col_counts <- h_col_counts(table_row, ...) |
166 | 303x |
total_n <- sum(col_counts) |
167 | 303x |
total_percent <- total_count / total_n |
168 | 303x |
total_percent >= atleast |
169 |
}) |
|
170 |
} |
|
171 | ||
172 |
#' @describeIn prune_occurrences Constructor for creating condition functions on any fraction in |
|
173 |
#' the specified columns. |
|
174 |
#' |
|
175 |
#' @return |
|
176 |
#' * `has_fraction_in_any_col()` returns a condition function that looks at the fractions |
|
177 |
#' in the specified columns and checks whether any of them fulfill the threshold. |
|
178 |
#' |
|
179 |
#' @examples |
|
180 |
#' \donttest{ |
|
181 |
#' # `has_fraction_in_any_col` |
|
182 |
#' any_atleast_five_percent <- has_fraction_in_any_col(atleast = 0.05, col_names = names(tab)) |
|
183 |
#' prune_table(tab, keep_rows(more_than_five_percent)) |
|
184 |
#' } |
|
185 |
#' |
|
186 |
#' @export |
|
187 |
has_fraction_in_any_col <- function(atleast, ...) { |
|
188 | ! |
assert_proportion_value(atleast, include_boundaries = TRUE) |
189 | ! |
CombinationFunction(function(table_row) { |
190 | ! |
row_fractions <- h_row_fractions(table_row, ...) |
191 | ! |
any(row_fractions >= atleast) |
192 |
}) |
|
193 |
} |
|
194 | ||
195 |
#' @describeIn prune_occurrences Constructor for creating condition function that checks the difference |
|
196 |
#' between the fractions reported in each specified column. |
|
197 |
#' |
|
198 |
#' @return |
|
199 |
#' * `has_fractions_difference()` returns a condition function that extracts the fractions of each |
|
200 |
#' specified column, and computes the difference of the minimum and maximum. |
|
201 |
#' |
|
202 |
#' @examples |
|
203 |
#' \donttest{ |
|
204 |
#' # `has_fractions_difference` |
|
205 |
#' more_than_five_percent_diff <- has_fractions_difference(atleast = 0.05, col_names = names(tab)) |
|
206 |
#' prune_table(tab, keep_rows(more_than_five_percent_diff)) |
|
207 |
#' } |
|
208 |
#' |
|
209 |
#' @export |
|
210 |
has_fractions_difference <- function(atleast, ...) { |
|
211 | 1x |
assert_proportion_value(atleast, include_boundaries = TRUE) |
212 | 1x |
CombinationFunction(function(table_row) { |
213 | 243x |
fractions <- h_row_fractions(table_row, ...) |
214 | 243x |
difference <- diff(range(fractions)) |
215 | 243x |
difference >= atleast |
216 |
}) |
|
217 |
} |
|
218 | ||
219 |
#' @describeIn prune_occurrences Constructor for creating condition function that checks the difference |
|
220 |
#' between the counts reported in each specified column. |
|
221 |
#' |
|
222 |
#' @return |
|
223 |
#' * `has_counts_difference()` returns a condition function that extracts the counts of each |
|
224 |
#' specified column, and computes the difference of the minimum and maximum. |
|
225 |
#' |
|
226 |
#' @examples |
|
227 |
#' \donttest{ |
|
228 |
#' more_than_one_diff <- has_counts_difference(atleast = 1L, col_names = names(tab)) |
|
229 |
#' prune_table(tab, keep_rows(more_than_one_diff)) |
|
230 |
#' } |
|
231 |
#' |
|
232 |
#' @export |
|
233 |
has_counts_difference <- function(atleast, ...) { |
|
234 | 1x |
checkmate::assert_count(atleast) |
235 | 1x |
CombinationFunction(function(table_row) { |
236 | 27x |
counts <- h_row_counts(table_row, ...) |
237 | 27x |
difference <- diff(range(counts)) |
238 | 27x |
difference >= atleast |
239 |
}) |
|
240 |
} |
1 |
#' Custom Split Functions |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Collection of useful functions that are expanding on the core list of functions |
|
6 |
#' provided by `rtables`. See [rtables::custom_split_funs] and [rtables::make_split_fun()] |
|
7 |
#' for more information on how to make a custom split function. All these functions |
|
8 |
#' work with [split_rows_by()] argument `split_fun` to modify the way the split |
|
9 |
#' happens. For other split functions, consider consulting [`rtables::split_funcs`]. |
|
10 |
#' |
|
11 |
#' @seealso [rtables::make_split_fun()] |
|
12 |
#' |
|
13 |
#' @name utils_split_funs |
|
14 |
NULL |
|
15 | ||
16 |
#' @describeIn utils_split_funs split function to place reference group facet at a specific position |
|
17 |
#' during post-processing stage. |
|
18 |
#' |
|
19 |
#' @param position (`string` or `integer`)\cr should it be `"first"` or `"last"` or in a specific position? |
|
20 |
#' |
|
21 |
#' @return |
|
22 |
#' * `ref_group_position` returns an utility function that puts the reference group |
|
23 |
#' as first, last or at a certain position and needs to be assigned to `split_fun`. |
|
24 |
#' |
|
25 |
#' @examples |
|
26 |
#' library(dplyr) |
|
27 |
#' |
|
28 |
#' dat <- data.frame( |
|
29 |
#' x = factor(letters[1:5], levels = letters[5:1]), |
|
30 |
#' y = 1:5 |
|
31 |
#' ) |
|
32 |
#' |
|
33 |
#' # With rtables layout functions |
|
34 |
#' basic_table() %>% |
|
35 |
#' split_cols_by("x", ref_group = "c", split_fun = ref_group_position("last")) %>% |
|
36 |
#' analyze("y") %>% |
|
37 |
#' build_table(dat) |
|
38 |
#' |
|
39 |
#' # With tern layout funcitons |
|
40 |
#' adtte_f <- tern_ex_adtte %>% |
|
41 |
#' filter(PARAMCD == "OS") %>% |
|
42 |
#' mutate( |
|
43 |
#' AVAL = day2month(AVAL), |
|
44 |
#' is_event = CNSR == 0 |
|
45 |
#' ) |
|
46 |
#' |
|
47 |
#' basic_table() %>% |
|
48 |
#' split_cols_by(var = "ARMCD", ref_group = "ARM B", split_fun = ref_group_position("first")) %>% |
|
49 |
#' add_colcounts() %>% |
|
50 |
#' surv_time( |
|
51 |
#' vars = "AVAL", |
|
52 |
#' var_labels = "Survival Time (Months)", |
|
53 |
#' is_event = "is_event", |
|
54 |
#' ) %>% |
|
55 |
#' build_table(df = adtte_f) |
|
56 |
#' |
|
57 |
#' basic_table() %>% |
|
58 |
#' split_cols_by(var = "ARMCD", ref_group = "ARM B", split_fun = ref_group_position(2)) %>% |
|
59 |
#' add_colcounts() %>% |
|
60 |
#' surv_time( |
|
61 |
#' vars = "AVAL", |
|
62 |
#' var_labels = "Survival Time (Months)", |
|
63 |
#' is_event = "is_event", |
|
64 |
#' ) %>% |
|
65 |
#' build_table(df = adtte_f) |
|
66 |
#' |
|
67 |
#' @export |
|
68 |
ref_group_position <- function(position = "first") { |
|
69 | 19x |
make_split_fun( |
70 | 19x |
post = list( |
71 | 19x |
function(splret, spl, fulldf) { |
72 | 54x |
if (!"ref_group_value" %in% methods::slotNames(spl)) { |
73 | 1x |
stop("Reference group is undefined.") |
74 |
} |
|
75 | ||
76 | 53x |
spl_var <- rtables:::spl_payload(spl) |
77 | 53x |
fulldf[[spl_var]] <- factor(fulldf[[spl_var]]) |
78 | 53x |
init_lvls <- levels(fulldf[[spl_var]]) |
79 | ||
80 | 53x |
if (!all(names(splret$values) %in% init_lvls)) { |
81 | ! |
stop("This split function does not work with combination facets.") |
82 |
} |
|
83 | ||
84 | 53x |
ref_group_pos <- which(init_lvls == rtables:::spl_ref_group(spl)) |
85 | 53x |
pos_choices <- c("first", "last") |
86 | 53x |
if (checkmate::test_choice(position, pos_choices) && position == "first") { |
87 | 38x |
pos <- 0 |
88 | 15x |
} else if (checkmate::test_choice(position, pos_choices) && position == "last") { |
89 | 12x |
pos <- length(init_lvls) |
90 | 3x |
} else if (checkmate::test_int(position, lower = 1, upper = length(init_lvls))) { |
91 | 3x |
pos <- position - 1 |
92 |
} else { |
|
93 | ! |
stop("Wrong input for ref group position. It must be 'first', 'last', or a integer.") |
94 |
} |
|
95 | ||
96 | 53x |
reord_lvls <- append(init_lvls[-ref_group_pos], init_lvls[ref_group_pos], after = pos) |
97 | 53x |
ord <- match(reord_lvls, names(splret$values)) |
98 | ||
99 | 53x |
make_split_result( |
100 | 53x |
splret$values[ord], |
101 | 53x |
splret$datasplit[ord], |
102 | 53x |
splret$labels[ord] |
103 |
) |
|
104 |
} |
|
105 |
) |
|
106 |
) |
|
107 |
} |
|
108 | ||
109 |
#' @describeIn utils_split_funs split function to change level order based on a `integer` |
|
110 |
#' vector or a `character` vector that represent the split variable's factor levels. |
|
111 |
#' |
|
112 |
#' @param order (`character` or `integer`)\cr vector of ordering indexes for the split facets. |
|
113 |
#' |
|
114 |
#' @return |
|
115 |
#' * `level_order` returns an utility function that changes the original levels' order, |
|
116 |
#' depending on input `order` and split levels. |
|
117 |
#' |
|
118 |
#' @examples |
|
119 |
#' # level_order -------- |
|
120 |
#' # Even if default would bring ref_group first, the original order puts it last |
|
121 |
#' basic_table() %>% |
|
122 |
#' split_cols_by("Species", split_fun = level_order(c(1, 3, 2))) %>% |
|
123 |
#' analyze("Sepal.Length") %>% |
|
124 |
#' build_table(iris) |
|
125 |
#' |
|
126 |
#' # character vector |
|
127 |
#' new_order <- level_order(levels(iris$Species)[c(1, 3, 2)]) |
|
128 |
#' basic_table() %>% |
|
129 |
#' split_cols_by("Species", ref_group = "virginica", split_fun = new_order) %>% |
|
130 |
#' analyze("Sepal.Length") %>% |
|
131 |
#' build_table(iris) |
|
132 |
#' |
|
133 |
#' @export |
|
134 |
level_order <- function(order) { |
|
135 | 2x |
make_split_fun( |
136 | 2x |
post = list( |
137 | 2x |
function(splret, spl, fulldf) { |
138 | 4x |
if (checkmate::test_integerish(order)) { |
139 | 1x |
checkmate::assert_integerish(order, lower = 1, upper = length(splret$values)) |
140 | 1x |
ord <- order |
141 |
} else { |
|
142 | 3x |
checkmate::assert_character(order, len = length(splret$values)) |
143 | 3x |
checkmate::assert_set_equal(order, names(splret$values), ordered = FALSE) |
144 | 3x |
ord <- match(order, names(splret$values)) |
145 |
} |
|
146 | 4x |
make_split_result( |
147 | 4x |
splret$values[ord], |
148 | 4x |
splret$datasplit[ord], |
149 | 4x |
splret$labels[ord] |
150 |
) |
|
151 |
} |
|
152 |
) |
|
153 |
) |
|
154 |
} |
1 |
#' Counting Patients Summing Exposure Across All Patients in Columns |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Counting the number of patients and summing analysis value (i.e exposure values) across all patients |
|
6 |
#' when a column table layout is required. |
|
7 |
#' |
|
8 |
#' @inheritParams argument_convention |
|
9 |
#' @param ex_var (`character`)\cr name of the variable within `df` containing exposure values. |
|
10 |
#' @param custom_label (`string` or `NULL`)\cr if provided and `labelstr` is empty then this will be used as label. |
|
11 |
#' @param .stats (`character`)\cr statistics to select for the table. Run |
|
12 |
#' `get_stats("analyze_patients_exposure_in_cols")` to see available statistics for this function. |
|
13 |
#' |
|
14 |
#' @name summarize_patients_exposure_in_cols |
|
15 |
#' @order 1 |
|
16 |
NULL |
|
17 | ||
18 |
#' @describeIn summarize_patients_exposure_in_cols Statistics function which counts numbers |
|
19 |
#' of patients and the sum of exposure across all patients. |
|
20 |
#' |
|
21 |
#' @return |
|
22 |
#' * `s_count_patients_sum_exposure()` returns a named `list` with the statistics: |
|
23 |
#' * `n_patients`: Number of unique patients in `df`. |
|
24 |
#' * `sum_exposure`: Sum of `ex_var` across all patients in `df`. |
|
25 |
#' |
|
26 |
#' @keywords internal |
|
27 |
s_count_patients_sum_exposure <- function(df, |
|
28 |
ex_var = "AVAL", |
|
29 |
id = "USUBJID", |
|
30 |
labelstr = "", |
|
31 |
.stats = c("n_patients", "sum_exposure"), |
|
32 |
.N_col, # nolint |
|
33 |
custom_label = NULL) { |
|
34 | 56x |
assert_df_with_variables(df, list(ex_var = ex_var, id = id)) |
35 | 56x |
checkmate::assert_string(id) |
36 | 56x |
checkmate::assert_string(labelstr) |
37 | 56x |
checkmate::assert_string(custom_label, null.ok = TRUE) |
38 | 56x |
checkmate::assert_numeric(df[[ex_var]]) |
39 | 56x |
checkmate::assert_true(all(.stats %in% c("n_patients", "sum_exposure"))) |
40 | ||
41 | 56x |
row_label <- if (labelstr != "") { |
42 | ! |
labelstr |
43 | 56x |
} else if (!is.null(custom_label)) { |
44 | 48x |
custom_label |
45 |
} else { |
|
46 | 8x |
"Total patients numbers/person time" |
47 |
} |
|
48 | ||
49 | 56x |
y <- list() |
50 | ||
51 | 56x |
if ("n_patients" %in% .stats) { |
52 | 23x |
y$n_patients <- |
53 | 23x |
formatters::with_label( |
54 | 23x |
s_num_patients_content( |
55 | 23x |
df = df, |
56 | 23x |
.N_col = .N_col, # nolint |
57 | 23x |
.var = id, |
58 | 23x |
labelstr = "" |
59 | 23x |
)$unique, |
60 | 23x |
row_label |
61 |
) |
|
62 |
} |
|
63 | 56x |
if ("sum_exposure" %in% .stats) { |
64 | 34x |
y$sum_exposure <- formatters::with_label(sum(df[[ex_var]]), row_label) |
65 |
} |
|
66 | 56x |
y |
67 |
} |
|
68 | ||
69 |
#' @describeIn summarize_patients_exposure_in_cols Analysis function which is used as `afun` in |
|
70 |
#' [rtables::analyze_colvars()] within `analyze_patients_exposure_in_cols()` and as `cfun` in |
|
71 |
#' [rtables::summarize_row_groups()] within `summarize_patients_exposure_in_cols()`. |
|
72 |
#' |
|
73 |
#' @return |
|
74 |
#' * `a_count_patients_sum_exposure()` returns formatted [rtables::CellValue()]. |
|
75 |
#' |
|
76 |
#' @examples |
|
77 |
#' a_count_patients_sum_exposure( |
|
78 |
#' df = df, |
|
79 |
#' var = "SEX", |
|
80 |
#' .N_col = nrow(df), |
|
81 |
#' .stats = "n_patients" |
|
82 |
#' ) |
|
83 |
#' |
|
84 |
#' @export |
|
85 |
a_count_patients_sum_exposure <- function(df, |
|
86 |
var = NULL, |
|
87 |
ex_var = "AVAL", |
|
88 |
id = "USUBJID", |
|
89 |
add_total_level = FALSE, |
|
90 |
custom_label = NULL, |
|
91 |
labelstr = "", |
|
92 |
.N_col, # nolint |
|
93 |
.stats, |
|
94 |
.formats = list(n_patients = "xx (xx.x%)", sum_exposure = "xx")) { |
|
95 | 32x |
checkmate::assert_flag(add_total_level) |
96 | ||
97 | 32x |
if (!is.null(var)) { |
98 | 21x |
assert_df_with_variables(df, list(var = var)) |
99 | 21x |
df[[var]] <- as.factor(df[[var]]) |
100 |
} |
|
101 | ||
102 | 32x |
y <- list() |
103 | 32x |
if (is.null(var)) { |
104 | 11x |
y[[.stats]] <- list(Total = s_count_patients_sum_exposure( |
105 | 11x |
df = df, |
106 | 11x |
ex_var = ex_var, |
107 | 11x |
id = id, |
108 | 11x |
labelstr = labelstr, |
109 | 11x |
.N_col = .N_col, |
110 | 11x |
.stats = .stats, |
111 | 11x |
custom_label = custom_label |
112 | 11x |
)[[.stats]]) |
113 |
} else { |
|
114 | 21x |
for (lvl in levels(df[[var]])) { |
115 | 42x |
y[[.stats]][[lvl]] <- s_count_patients_sum_exposure( |
116 | 42x |
df = subset(df, get(var) == lvl), |
117 | 42x |
ex_var = ex_var, |
118 | 42x |
id = id, |
119 | 42x |
labelstr = labelstr, |
120 | 42x |
.N_col = .N_col, |
121 | 42x |
.stats = .stats, |
122 | 42x |
custom_label = lvl |
123 | 42x |
)[[.stats]] |
124 |
} |
|
125 | 21x |
if (add_total_level) { |
126 | 2x |
y[[.stats]][["Total"]] <- s_count_patients_sum_exposure( |
127 | 2x |
df = df, |
128 | 2x |
ex_var = ex_var, |
129 | 2x |
id = id, |
130 | 2x |
labelstr = labelstr, |
131 | 2x |
.N_col = .N_col, |
132 | 2x |
.stats = .stats, |
133 | 2x |
custom_label = custom_label |
134 | 2x |
)[[.stats]] |
135 |
} |
|
136 |
} |
|
137 | ||
138 | 32x |
in_rows(.list = y[[.stats]], .formats = .formats[[.stats]]) |
139 |
} |
|
140 | ||
141 |
#' @describeIn summarize_patients_exposure_in_cols Layout-creating function which can take statistics |
|
142 |
#' function arguments and additional format arguments. This function is a wrapper for |
|
143 |
#' [rtables::split_cols_by_multivar()] and [rtables::summarize_row_groups()]. |
|
144 |
#' |
|
145 |
#' @return |
|
146 |
#' * `summarize_patients_exposure_in_cols()` returns a layout object suitable for passing to further |
|
147 |
#' layouting functions, or to [rtables::build_table()]. Adding this function to an `rtable` layout will |
|
148 |
#' add formatted content rows, with the statistics from `s_count_patients_sum_exposure()` arranged in |
|
149 |
#' columns, to the table layout. |
|
150 |
#' |
|
151 |
#' @examples |
|
152 |
#' lyt5 <- basic_table() %>% |
|
153 |
#' summarize_patients_exposure_in_cols(var = "AVAL", col_split = TRUE) |
|
154 |
#' |
|
155 |
#' result5 <- build_table(lyt5, df = df, alt_counts_df = adsl) |
|
156 |
#' result5 |
|
157 |
#' |
|
158 |
#' lyt6 <- basic_table() %>% |
|
159 |
#' summarize_patients_exposure_in_cols(var = "AVAL", col_split = TRUE, .stats = "sum_exposure") |
|
160 |
#' |
|
161 |
#' result6 <- build_table(lyt6, df = df, alt_counts_df = adsl) |
|
162 |
#' result6 |
|
163 |
#' |
|
164 |
#' @export |
|
165 |
#' @order 3 |
|
166 |
summarize_patients_exposure_in_cols <- function(lyt, # nolint |
|
167 |
var, |
|
168 |
ex_var = "AVAL", |
|
169 |
id = "USUBJID", |
|
170 |
add_total_level = FALSE, |
|
171 |
custom_label = NULL, |
|
172 |
col_split = TRUE, |
|
173 |
na_str = default_na_str(), |
|
174 |
..., |
|
175 |
.stats = c("n_patients", "sum_exposure"), |
|
176 |
.labels = c(n_patients = "Patients", sum_exposure = "Person time"), |
|
177 |
.indent_mods = NULL) { |
|
178 | 3x |
extra_args <- list(ex_var = ex_var, id = id, add_total_level = add_total_level, custom_label = custom_label, ...) |
179 | ||
180 | 3x |
if (col_split) { |
181 | 3x |
lyt <- split_cols_by_multivar( |
182 | 3x |
lyt = lyt, |
183 | 3x |
vars = rep(var, length(.stats)), |
184 | 3x |
varlabels = .labels[.stats], |
185 | 3x |
extra_args = list(.stats = .stats) |
186 |
) |
|
187 |
} |
|
188 | 3x |
summarize_row_groups( |
189 | 3x |
lyt = lyt, |
190 | 3x |
var = var, |
191 | 3x |
cfun = a_count_patients_sum_exposure, |
192 | 3x |
na_str = na_str, |
193 | 3x |
extra_args = extra_args |
194 |
) |
|
195 |
} |
|
196 | ||
197 |
#' @describeIn summarize_patients_exposure_in_cols Layout-creating function which can take statistics |
|
198 |
#' function arguments and additional format arguments. This function is a wrapper for |
|
199 |
#' [rtables::split_cols_by_multivar()] and [rtables::analyze_colvars()]. |
|
200 |
#' |
|
201 |
#' @param col_split (`flag`)\cr whether the columns should be split. Set to `FALSE` when the required |
|
202 |
#' column split has been done already earlier in the layout pipe. |
|
203 |
#' |
|
204 |
#' @return |
|
205 |
#' * `analyze_patients_exposure_in_cols()` returns a layout object suitable for passing to further |
|
206 |
#' layouting functions, or to [rtables::build_table()]. Adding this function to an `rtable` layout will |
|
207 |
#' add formatted data rows, with the statistics from `s_count_patients_sum_exposure()` arranged in |
|
208 |
#' columns, to the table layout. |
|
209 |
#' |
|
210 |
#' @note As opposed to [summarize_patients_exposure_in_cols()] which generates content rows, |
|
211 |
#' `analyze_patients_exposure_in_cols()` generates data rows which will _not_ be repeated on multiple |
|
212 |
#' pages when pagination is used. |
|
213 |
#' |
|
214 |
#' @examples |
|
215 |
#' set.seed(1) |
|
216 |
#' df <- data.frame( |
|
217 |
#' USUBJID = c(paste("id", seq(1, 12), sep = "")), |
|
218 |
#' ARMCD = c(rep("ARM A", 6), rep("ARM B", 6)), |
|
219 |
#' SEX = c(rep("Female", 6), rep("Male", 6)), |
|
220 |
#' AVAL = as.numeric(sample(seq(1, 20), 12)), |
|
221 |
#' stringsAsFactors = TRUE |
|
222 |
#' ) |
|
223 |
#' adsl <- data.frame( |
|
224 |
#' USUBJID = c(paste("id", seq(1, 12), sep = "")), |
|
225 |
#' ARMCD = c(rep("ARM A", 2), rep("ARM B", 2)), |
|
226 |
#' SEX = c(rep("Female", 2), rep("Male", 2)), |
|
227 |
#' stringsAsFactors = TRUE |
|
228 |
#' ) |
|
229 |
#' |
|
230 |
#' lyt <- basic_table() %>% |
|
231 |
#' split_cols_by("ARMCD", split_fun = add_overall_level("Total", first = FALSE)) %>% |
|
232 |
#' summarize_patients_exposure_in_cols(var = "AVAL", col_split = TRUE) %>% |
|
233 |
#' analyze_patients_exposure_in_cols(var = "SEX", col_split = FALSE) |
|
234 |
#' result <- build_table(lyt, df = df, alt_counts_df = adsl) |
|
235 |
#' result |
|
236 |
#' |
|
237 |
#' lyt2 <- basic_table() %>% |
|
238 |
#' split_cols_by("ARMCD", split_fun = add_overall_level("Total", first = FALSE)) %>% |
|
239 |
#' summarize_patients_exposure_in_cols( |
|
240 |
#' var = "AVAL", col_split = TRUE, |
|
241 |
#' .stats = "n_patients", custom_label = "some custom label" |
|
242 |
#' ) %>% |
|
243 |
#' analyze_patients_exposure_in_cols(var = "SEX", col_split = FALSE, ex_var = "AVAL") |
|
244 |
#' result2 <- build_table(lyt2, df = df, alt_counts_df = adsl) |
|
245 |
#' result2 |
|
246 |
#' |
|
247 |
#' lyt3 <- basic_table() %>% |
|
248 |
#' analyze_patients_exposure_in_cols(var = "SEX", col_split = TRUE, ex_var = "AVAL") |
|
249 |
#' result3 <- build_table(lyt3, df = df, alt_counts_df = adsl) |
|
250 |
#' result3 |
|
251 |
#' |
|
252 |
#' # Adding total levels and custom label |
|
253 |
#' lyt4 <- basic_table( |
|
254 |
#' show_colcounts = TRUE |
|
255 |
#' ) %>% |
|
256 |
#' analyze_patients_exposure_in_cols( |
|
257 |
#' var = "ARMCD", |
|
258 |
#' col_split = TRUE, |
|
259 |
#' add_total_level = TRUE, |
|
260 |
#' custom_label = "TOTAL" |
|
261 |
#' ) %>% |
|
262 |
#' append_topleft(c("", "Sex")) |
|
263 |
#' |
|
264 |
#' result4 <- build_table(lyt4, df = df, alt_counts_df = adsl) |
|
265 |
#' result4 |
|
266 |
#' |
|
267 |
#' @export |
|
268 |
#' @order 2 |
|
269 |
analyze_patients_exposure_in_cols <- function(lyt, # nolint |
|
270 |
var = NULL, |
|
271 |
ex_var = "AVAL", |
|
272 |
id = "USUBJID", |
|
273 |
add_total_level = FALSE, |
|
274 |
custom_label = NULL, |
|
275 |
col_split = TRUE, |
|
276 |
na_str = default_na_str(), |
|
277 |
.stats = c("n_patients", "sum_exposure"), |
|
278 |
.labels = c(n_patients = "Patients", sum_exposure = "Person time"), |
|
279 |
.indent_mods = 0L, |
|
280 |
...) { |
|
281 | 6x |
extra_args <- list( |
282 | 6x |
var = var, ex_var = ex_var, id = id, add_total_level = add_total_level, custom_label = custom_label, ... |
283 |
) |
|
284 | ||
285 | 6x |
if (col_split) { |
286 | 4x |
lyt <- split_cols_by_multivar( |
287 | 4x |
lyt = lyt, |
288 | 4x |
vars = rep(ex_var, length(.stats)), |
289 | 4x |
varlabels = .labels[.stats], |
290 | 4x |
extra_args = list(.stats = .stats) |
291 |
) |
|
292 |
} |
|
293 | 6x |
lyt <- lyt %>% analyze_colvars( |
294 | 6x |
afun = a_count_patients_sum_exposure, |
295 | 6x |
indent_mod = .indent_mods, |
296 | 6x |
na_str = na_str, |
297 | 6x |
extra_args = extra_args |
298 |
) |
|
299 | 6x |
lyt |
300 |
} |
1 |
#' Summarize the Change from Baseline or Absolute Baseline Values |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' The primary analysis variable `.var` indicates the numerical change from baseline results, |
|
6 |
#' and additional required secondary analysis variables are `value` and `baseline_flag`. |
|
7 |
#' Depending on the baseline flag, either the absolute baseline values (at baseline) |
|
8 |
#' or the change from baseline values (post-baseline) are then summarized. |
|
9 |
#' |
|
10 |
#' @inheritParams argument_convention |
|
11 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("analyze_vars_numeric)` |
|
12 |
#' to see available statistics for this function. |
|
13 |
#' |
|
14 |
#' @name summarize_change |
|
15 |
#' @order 1 |
|
16 |
NULL |
|
17 | ||
18 |
#' @describeIn summarize_change Statistics function that summarizes baseline or post-baseline visits. |
|
19 |
#' |
|
20 |
#' @return |
|
21 |
#' * `s_change_from_baseline()` returns the same values returned by [s_summary.numeric()]. |
|
22 |
#' |
|
23 |
#' @note The data in `df` must be either all be from baseline or post-baseline visits. Otherwise |
|
24 |
#' an error will be thrown. |
|
25 |
#' |
|
26 |
#' @keywords internal |
|
27 |
s_change_from_baseline <- function(df, |
|
28 |
.var, |
|
29 |
variables, |
|
30 |
na.rm = TRUE, # nolint |
|
31 |
...) { |
|
32 | 4x |
checkmate::assert_numeric(df[[variables$value]]) |
33 | 4x |
checkmate::assert_numeric(df[[.var]]) |
34 | 4x |
checkmate::assert_logical(df[[variables$baseline_flag]]) |
35 | 4x |
checkmate::assert_vector(unique(df[[variables$baseline_flag]]), max.len = 1) |
36 | 4x |
assert_df_with_variables(df, c(variables, list(chg = .var))) |
37 | ||
38 | 4x |
combined <- ifelse( |
39 | 4x |
df[[variables$baseline_flag]], |
40 | 4x |
df[[variables$value]], |
41 | 4x |
df[[.var]] |
42 |
) |
|
43 | 4x |
if (is.logical(combined) && identical(length(combined), 0L)) { |
44 | 1x |
combined <- numeric(0) |
45 |
} |
|
46 | 4x |
s_summary(combined, na.rm = na.rm, ...) |
47 |
} |
|
48 | ||
49 |
#' @describeIn summarize_change Formatted analysis function which is used as `afun` in `summarize_change()`. |
|
50 |
#' |
|
51 |
#' @return |
|
52 |
#' * `a_change_from_baseline()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
53 |
#' |
|
54 |
#' @keywords internal |
|
55 |
a_change_from_baseline <- make_afun( |
|
56 |
s_change_from_baseline, |
|
57 |
.formats = c( |
|
58 |
n = "xx", |
|
59 |
mean_sd = "xx.xx (xx.xx)", |
|
60 |
mean_se = "xx.xx (xx.xx)", |
|
61 |
median = "xx.xx", |
|
62 |
range = "xx.xx - xx.xx", |
|
63 |
mean_ci = "(xx.xx, xx.xx)", |
|
64 |
median_ci = "(xx.xx, xx.xx)", |
|
65 |
mean_pval = "xx.xx" |
|
66 |
), |
|
67 |
.labels = c( |
|
68 |
mean_sd = "Mean (SD)", |
|
69 |
mean_se = "Mean (SE)", |
|
70 |
median = "Median", |
|
71 |
range = "Min - Max" |
|
72 |
) |
|
73 |
) |
|
74 | ||
75 |
#' @describeIn summarize_change Layout-creating function which can take statistics function arguments |
|
76 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
77 |
#' |
|
78 |
#' @return |
|
79 |
#' * `summarize_change()` returns a layout object suitable for passing to further layouting functions, |
|
80 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
81 |
#' the statistics from `s_change_from_baseline()` to the table layout. |
|
82 |
#' |
|
83 |
#' @note To be used after a split on visits in the layout, such that each data subset only contains |
|
84 |
#' either baseline or post-baseline data. |
|
85 |
#' |
|
86 |
#' @examples |
|
87 |
#' library(dplyr) |
|
88 |
#' |
|
89 |
#' ## Fabricate dataset |
|
90 |
#' dta_test <- data.frame( |
|
91 |
#' USUBJID = rep(1:6, each = 3), |
|
92 |
#' AVISIT = rep(paste0("V", 1:3), 6), |
|
93 |
#' ARM = rep(LETTERS[1:3], rep(6, 3)), |
|
94 |
#' AVAL = c(9:1, rep(NA, 9)) |
|
95 |
#' ) %>% |
|
96 |
#' mutate(ABLFLL = AVISIT == "V1") %>% |
|
97 |
#' group_by(USUBJID) %>% |
|
98 |
#' mutate( |
|
99 |
#' BLVAL = AVAL[ABLFLL], |
|
100 |
#' CHG = AVAL - BLVAL |
|
101 |
#' ) %>% |
|
102 |
#' ungroup() |
|
103 |
#' |
|
104 |
#' results <- basic_table() %>% |
|
105 |
#' split_cols_by("ARM") %>% |
|
106 |
#' split_rows_by("AVISIT") %>% |
|
107 |
#' summarize_change("CHG", variables = list(value = "AVAL", baseline_flag = "ABLFLL")) %>% |
|
108 |
#' build_table(dta_test) |
|
109 |
#' |
|
110 |
#' results |
|
111 |
#' |
|
112 |
#' @export |
|
113 |
#' @order 2 |
|
114 |
summarize_change <- function(lyt, |
|
115 |
vars, |
|
116 |
variables, |
|
117 |
na_str = default_na_str(), |
|
118 |
nested = TRUE, |
|
119 |
..., |
|
120 |
table_names = vars, |
|
121 |
.stats = c("n", "mean_sd", "median", "range"), |
|
122 |
.formats = NULL, |
|
123 |
.labels = NULL, |
|
124 |
.indent_mods = NULL) { |
|
125 | 1x |
extra_args <- list(variables = variables, ...) |
126 | ||
127 | 1x |
afun <- make_afun( |
128 | 1x |
a_change_from_baseline, |
129 | 1x |
.stats = .stats, |
130 | 1x |
.formats = .formats, |
131 | 1x |
.labels = .labels, |
132 | 1x |
.indent_mods = .indent_mods |
133 |
) |
|
134 | ||
135 | 1x |
analyze( |
136 | 1x |
lyt, |
137 | 1x |
vars, |
138 | 1x |
afun = afun, |
139 | 1x |
na_str = na_str, |
140 | 1x |
nested = nested, |
141 | 1x |
extra_args = extra_args, |
142 | 1x |
table_names = table_names |
143 |
) |
|
144 |
} |
1 |
#' Patient Counts with Abnormal Range Values |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Primary analysis variable `.var` indicates the abnormal range result (`character` or `factor`) |
|
6 |
#' and additional analysis variables are `id` (`character` or `factor`) and `baseline` (`character` or |
|
7 |
#' `factor`). For each direction specified in `abnormal` (e.g. high or low) count patients in the |
|
8 |
#' numerator and denominator as follows: |
|
9 |
#' * `num` : The number of patients with this abnormality recorded while on treatment. |
|
10 |
#' * `denom`: The number of patients with at least one post-baseline assessment. |
|
11 |
#' |
|
12 |
#' @inheritParams argument_convention |
|
13 |
#' @param abnormal (named `list`)\cr list identifying the abnormal range level(s) in `var`. Defaults to |
|
14 |
#' `list(Low = "LOW", High = "HIGH")` but you can also group different levels into the named list, |
|
15 |
#' for example, `abnormal = list(Low = c("LOW", "LOW LOW"), High = c("HIGH", "HIGH HIGH"))`. |
|
16 |
#' @param exclude_base_abn (`flag`)\cr whether to exclude subjects with baseline abnormality |
|
17 |
#' from numerator and denominator. |
|
18 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("abnormal")` |
|
19 |
#' to see available statistics for this function. |
|
20 |
#' |
|
21 |
#' @note |
|
22 |
#' * `count_abnormal()` only works with a single variable containing multiple abnormal levels. |
|
23 |
#' * `df` should be filtered to include only post-baseline records. |
|
24 |
#' * the denominator includes patients that might have other abnormal levels at baseline, |
|
25 |
#' and patients with missing baseline. Patients with these abnormalities at |
|
26 |
#' baseline can be optionally excluded from numerator and denominator. |
|
27 |
#' |
|
28 |
#' @name abnormal |
|
29 |
#' @include formatting_functions.R |
|
30 |
#' @order 1 |
|
31 |
NULL |
|
32 | ||
33 |
#' @describeIn abnormal Statistics function which counts patients with abnormal range values |
|
34 |
#' for a single `abnormal` level. |
|
35 |
#' |
|
36 |
#' @return |
|
37 |
#' * `s_count_abnormal()` returns the statistic `fraction` which is a vector with `num` and `denom` counts of patients. |
|
38 |
#' |
|
39 |
#' @keywords internal |
|
40 |
s_count_abnormal <- function(df, |
|
41 |
.var, |
|
42 |
abnormal = list(Low = "LOW", High = "HIGH"), |
|
43 |
variables = list(id = "USUBJID", baseline = "BNRIND"), |
|
44 |
exclude_base_abn = FALSE) { |
|
45 | 4x |
checkmate::assert_list(abnormal, types = "character", names = "named", len = 2, any.missing = FALSE) |
46 | 4x |
checkmate::assert_true(any(unlist(abnormal) %in% levels(df[[.var]]))) |
47 | 4x |
checkmate::assert_factor(df[[.var]]) |
48 | 4x |
checkmate::assert_flag(exclude_base_abn) |
49 | 4x |
assert_df_with_variables(df, c(range = .var, variables)) |
50 | 4x |
checkmate::assert_multi_class(df[[variables$baseline]], classes = c("factor", "character")) |
51 | 4x |
checkmate::assert_multi_class(df[[variables$id]], classes = c("factor", "character")) |
52 | ||
53 | 4x |
count_abnormal_single <- function(abn_name, abn) { |
54 |
# Patients in the denominator fulfill: |
|
55 |
# - have at least one post-baseline visit |
|
56 |
# - their baseline must not be abnormal if `exclude_base_abn`. |
|
57 | 8x |
if (exclude_base_abn) { |
58 | 4x |
denom_select <- !(df[[variables$baseline]] %in% abn) |
59 |
} else { |
|
60 | 4x |
denom_select <- TRUE |
61 |
} |
|
62 | 8x |
denom <- length(unique(df[denom_select, variables$id, drop = TRUE])) |
63 | ||
64 |
# Patients in the numerator fulfill: |
|
65 |
# - have at least one post-baseline visit with the required abnormality level |
|
66 |
# - are part of the denominator patients. |
|
67 | 8x |
num_select <- (df[[.var]] %in% abn) & denom_select |
68 | 8x |
num <- length(unique(df[num_select, variables$id, drop = TRUE])) |
69 | ||
70 | 8x |
formatters::with_label(c(num = num, denom = denom), abn_name) |
71 |
} |
|
72 | ||
73 |
# This will define the abnormal levels theoretically possible for a specific lab parameter |
|
74 |
# within a split level of a layout. |
|
75 | 4x |
abnormal_lev <- lapply(abnormal, intersect, levels(df[[.var]])) |
76 | 4x |
abnormal_lev <- abnormal_lev[vapply(abnormal_lev, function(x) length(x) > 0, logical(1))] |
77 | ||
78 | 4x |
result <- sapply(names(abnormal_lev), function(i) count_abnormal_single(i, abnormal_lev[[i]]), simplify = FALSE) |
79 | 4x |
result <- list(fraction = result) |
80 | 4x |
result |
81 |
} |
|
82 | ||
83 |
#' @describeIn abnormal Formatted analysis function which is used as `afun` in `count_abnormal()`. |
|
84 |
#' |
|
85 |
#' @return |
|
86 |
#' * `a_count_abnormal()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
87 |
#' |
|
88 |
#' @keywords internal |
|
89 |
a_count_abnormal <- make_afun( |
|
90 |
s_count_abnormal, |
|
91 |
.formats = c(fraction = format_fraction) |
|
92 |
) |
|
93 | ||
94 |
#' @describeIn abnormal Layout-creating function which can take statistics function arguments |
|
95 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
96 |
#' |
|
97 |
#' @return |
|
98 |
#' * `count_abnormal()` returns a layout object suitable for passing to further layouting functions, |
|
99 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
100 |
#' the statistics from `s_count_abnormal()` to the table layout. |
|
101 |
#' |
|
102 |
#' @examples |
|
103 |
#' library(dplyr) |
|
104 |
#' |
|
105 |
#' df <- data.frame( |
|
106 |
#' USUBJID = as.character(c(1, 1, 2, 2)), |
|
107 |
#' ANRIND = factor(c("NORMAL", "LOW", "HIGH", "HIGH")), |
|
108 |
#' BNRIND = factor(c("NORMAL", "NORMAL", "HIGH", "HIGH")), |
|
109 |
#' ONTRTFL = c("", "Y", "", "Y"), |
|
110 |
#' stringsAsFactors = FALSE |
|
111 |
#' ) |
|
112 |
#' |
|
113 |
#' # Select only post-baseline records. |
|
114 |
#' df <- df %>% |
|
115 |
#' filter(ONTRTFL == "Y") |
|
116 |
#' |
|
117 |
#' # Layout creating function. |
|
118 |
#' basic_table() %>% |
|
119 |
#' count_abnormal(var = "ANRIND", abnormal = list(high = "HIGH", low = "LOW")) %>% |
|
120 |
#' build_table(df) |
|
121 |
#' |
|
122 |
#' # Passing of statistics function and formatting arguments. |
|
123 |
#' df2 <- data.frame( |
|
124 |
#' ID = as.character(c(1, 1, 2, 2)), |
|
125 |
#' RANGE = factor(c("NORMAL", "LOW", "HIGH", "HIGH")), |
|
126 |
#' BL_RANGE = factor(c("NORMAL", "NORMAL", "HIGH", "HIGH")), |
|
127 |
#' ONTRTFL = c("", "Y", "", "Y"), |
|
128 |
#' stringsAsFactors = FALSE |
|
129 |
#' ) |
|
130 |
#' |
|
131 |
#' # Select only post-baseline records. |
|
132 |
#' df2 <- df2 %>% |
|
133 |
#' filter(ONTRTFL == "Y") |
|
134 |
#' |
|
135 |
#' basic_table() %>% |
|
136 |
#' count_abnormal( |
|
137 |
#' var = "RANGE", |
|
138 |
#' abnormal = list(low = "LOW", high = "HIGH"), |
|
139 |
#' variables = list(id = "ID", baseline = "BL_RANGE") |
|
140 |
#' ) %>% |
|
141 |
#' build_table(df2) |
|
142 |
#' |
|
143 |
#' @export |
|
144 |
#' @order 2 |
|
145 |
count_abnormal <- function(lyt, |
|
146 |
var, |
|
147 |
abnormal = list(Low = "LOW", High = "HIGH"), |
|
148 |
variables = list(id = "USUBJID", baseline = "BNRIND"), |
|
149 |
exclude_base_abn = FALSE, |
|
150 |
na_str = default_na_str(), |
|
151 |
nested = TRUE, |
|
152 |
..., |
|
153 |
table_names = var, |
|
154 |
.stats = NULL, |
|
155 |
.formats = NULL, |
|
156 |
.labels = NULL, |
|
157 |
.indent_mods = NULL) { |
|
158 | 3x |
extra_args <- list(abnormal = abnormal, variables = variables, exclude_base_abn = exclude_base_abn, ...) |
159 | ||
160 | 3x |
afun <- make_afun( |
161 | 3x |
a_count_abnormal, |
162 | 3x |
.stats = .stats, |
163 | 3x |
.formats = .formats, |
164 | 3x |
.labels = .labels, |
165 | 3x |
.indent_mods = .indent_mods, |
166 | 3x |
.ungroup_stats = "fraction" |
167 |
) |
|
168 | ||
169 | 3x |
checkmate::assert_string(var) |
170 | ||
171 | 3x |
analyze( |
172 | 3x |
lyt = lyt, |
173 | 3x |
vars = var, |
174 | 3x |
afun = afun, |
175 | 3x |
na_str = na_str, |
176 | 3x |
nested = nested, |
177 | 3x |
table_names = table_names, |
178 | 3x |
extra_args = extra_args, |
179 | 3x |
show_labels = "hidden" |
180 |
) |
|
181 |
} |
1 |
#' Count the Number of Patients with a Particular Event |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' The primary analysis variable `.var` denotes the unique patient identifier. |
|
6 |
#' |
|
7 |
#' @inheritParams argument_convention |
|
8 |
#' @param filters (`character`)\cr a character vector specifying the column names and flag variables |
|
9 |
#' to be used for counting the number of unique identifiers satisfying such conditions. |
|
10 |
#' Multiple column names and flags are accepted in this format |
|
11 |
#' `c("column_name1" = "flag1", "column_name2" = "flag2")`. |
|
12 |
#' Note that only equality is being accepted as condition. |
|
13 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("count_patients_with_event")` |
|
14 |
#' to see available statistics for this function. |
|
15 |
#' |
|
16 |
#' @seealso [count_patients_with_flags] |
|
17 |
#' |
|
18 |
#' @name count_patients_with_event |
|
19 |
#' @order 1 |
|
20 |
NULL |
|
21 | ||
22 |
#' @describeIn count_patients_with_event Statistics function which counts the number of patients for which |
|
23 |
#' the defined event has occurred. |
|
24 |
#' |
|
25 |
#' @inheritParams analyze_variables |
|
26 |
#' @param .var (`character`)\cr name of the column that contains the unique identifier. |
|
27 |
#' |
|
28 |
#' @return |
|
29 |
#' * `s_count_patients_with_event()` returns the count and fraction of unique identifiers with the defined event. |
|
30 |
#' |
|
31 |
#' @examples |
|
32 |
#' # `s_count_patients_with_event()` |
|
33 |
#' |
|
34 |
#' s_count_patients_with_event( |
|
35 |
#' tern_ex_adae, |
|
36 |
#' .var = "SUBJID", |
|
37 |
#' filters = c("TRTEMFL" = "Y") |
|
38 |
#' ) |
|
39 |
#' |
|
40 |
#' s_count_patients_with_event( |
|
41 |
#' tern_ex_adae, |
|
42 |
#' .var = "SUBJID", |
|
43 |
#' filters = c("TRTEMFL" = "Y", "AEOUT" = "FATAL") |
|
44 |
#' ) |
|
45 |
#' |
|
46 |
#' s_count_patients_with_event( |
|
47 |
#' tern_ex_adae, |
|
48 |
#' .var = "SUBJID", |
|
49 |
#' filters = c("TRTEMFL" = "Y", "AEOUT" = "FATAL"), |
|
50 |
#' denom = "N_col", |
|
51 |
#' .N_col = 456 |
|
52 |
#' ) |
|
53 |
#' |
|
54 |
#' @export |
|
55 |
s_count_patients_with_event <- function(df, |
|
56 |
.var, |
|
57 |
filters, |
|
58 |
.N_col, # nolint |
|
59 |
.N_row, # nolint |
|
60 |
denom = c("n", "N_row", "N_col")) { |
|
61 | 30x |
col_names <- names(filters) |
62 | 30x |
filter_values <- filters |
63 | ||
64 | 30x |
checkmate::assert_subset(col_names, colnames(df)) |
65 | ||
66 | 30x |
temp <- Map( |
67 | 30x |
function(x, y) which(df[[x]] == y), |
68 | 30x |
col_names, |
69 | 30x |
filter_values |
70 |
) |
|
71 | 30x |
position_satisfy_filters <- Reduce(intersect, temp) |
72 | 30x |
id_satisfy_filters <- as.character(unique(df[position_satisfy_filters, ][[.var]])) |
73 | 30x |
result <- s_count_values( |
74 | 30x |
as.character(unique(df[[.var]])), |
75 | 30x |
id_satisfy_filters, |
76 | 30x |
denom = denom, |
77 | 30x |
.N_col = .N_col, |
78 | 30x |
.N_row = .N_row |
79 |
) |
|
80 | 30x |
result |
81 |
} |
|
82 | ||
83 |
#' @describeIn count_patients_with_event Formatted analysis function which is used as `afun` |
|
84 |
#' in `count_patients_with_event()`. |
|
85 |
#' |
|
86 |
#' @return |
|
87 |
#' * `a_count_patients_with_event()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
88 |
#' |
|
89 |
#' @examples |
|
90 |
#' # `a_count_patients_with_event()` |
|
91 |
#' |
|
92 |
#' a_count_patients_with_event( |
|
93 |
#' tern_ex_adae, |
|
94 |
#' .var = "SUBJID", |
|
95 |
#' filters = c("TRTEMFL" = "Y"), |
|
96 |
#' .N_col = 100, |
|
97 |
#' .N_row = 100 |
|
98 |
#' ) |
|
99 |
#' |
|
100 |
#' @export |
|
101 |
a_count_patients_with_event <- make_afun( |
|
102 |
s_count_patients_with_event, |
|
103 |
.formats = c(count_fraction = format_count_fraction_fixed_dp) |
|
104 |
) |
|
105 | ||
106 |
#' @describeIn count_patients_with_event Layout-creating function which can take statistics function |
|
107 |
#' arguments and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
108 |
#' |
|
109 |
#' @return |
|
110 |
#' * `count_patients_with_event()` returns a layout object suitable for passing to further layouting functions, |
|
111 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
112 |
#' the statistics from `s_count_patients_with_event()` to the table layout. |
|
113 |
#' |
|
114 |
#' @examples |
|
115 |
#' # `count_patients_with_event()` |
|
116 |
#' |
|
117 |
#' lyt <- basic_table() %>% |
|
118 |
#' split_cols_by("ARM") %>% |
|
119 |
#' add_colcounts() %>% |
|
120 |
#' count_values( |
|
121 |
#' "STUDYID", |
|
122 |
#' values = "AB12345", |
|
123 |
#' .stats = "count", |
|
124 |
#' .labels = c(count = "Total AEs") |
|
125 |
#' ) %>% |
|
126 |
#' count_patients_with_event( |
|
127 |
#' "SUBJID", |
|
128 |
#' filters = c("TRTEMFL" = "Y"), |
|
129 |
#' .labels = c(count_fraction = "Total number of patients with at least one adverse event"), |
|
130 |
#' table_names = "tbl_all" |
|
131 |
#' ) %>% |
|
132 |
#' count_patients_with_event( |
|
133 |
#' "SUBJID", |
|
134 |
#' filters = c("TRTEMFL" = "Y", "AEOUT" = "FATAL"), |
|
135 |
#' .labels = c(count_fraction = "Total number of patients with fatal AEs"), |
|
136 |
#' table_names = "tbl_fatal" |
|
137 |
#' ) %>% |
|
138 |
#' count_patients_with_event( |
|
139 |
#' "SUBJID", |
|
140 |
#' filters = c("TRTEMFL" = "Y", "AEOUT" = "FATAL", "AEREL" = "Y"), |
|
141 |
#' .labels = c(count_fraction = "Total number of patients with related fatal AEs"), |
|
142 |
#' .indent_mods = c(count_fraction = 2L), |
|
143 |
#' table_names = "tbl_rel_fatal" |
|
144 |
#' ) |
|
145 |
#' |
|
146 |
#' build_table(lyt, tern_ex_adae, alt_counts_df = tern_ex_adsl) |
|
147 |
#' |
|
148 |
#' @export |
|
149 |
#' @order 2 |
|
150 |
count_patients_with_event <- function(lyt, |
|
151 |
vars, |
|
152 |
filters, |
|
153 |
riskdiff = FALSE, |
|
154 |
na_str = default_na_str(), |
|
155 |
nested = TRUE, |
|
156 |
..., |
|
157 |
table_names = vars, |
|
158 |
.stats = "count_fraction", |
|
159 |
.formats = NULL, |
|
160 |
.labels = NULL, |
|
161 |
.indent_mods = NULL) { |
|
162 | 6x |
checkmate::assert_flag(riskdiff) |
163 | ||
164 | 6x |
s_args <- list(filters = filters, ...) |
165 | ||
166 | 6x |
afun <- make_afun( |
167 | 6x |
a_count_patients_with_event, |
168 | 6x |
.stats = .stats, |
169 | 6x |
.formats = .formats, |
170 | 6x |
.labels = .labels, |
171 | 6x |
.indent_mods = .indent_mods |
172 |
) |
|
173 | ||
174 | 6x |
extra_args <- if (isFALSE(riskdiff)) { |
175 | 5x |
s_args |
176 |
} else { |
|
177 | 1x |
list( |
178 | 1x |
afun = list("s_count_patients_with_event" = afun), |
179 | 1x |
.stats = .stats, |
180 | 1x |
.indent_mods = .indent_mods, |
181 | 1x |
s_args = s_args |
182 |
) |
|
183 |
} |
|
184 | ||
185 | 6x |
analyze( |
186 | 6x |
lyt, |
187 | 6x |
vars, |
188 | 6x |
afun = ifelse(isFALSE(riskdiff), afun, afun_riskdiff), |
189 | 6x |
na_str = na_str, |
190 | 6x |
nested = nested, |
191 | 6x |
extra_args = extra_args, |
192 | 6x |
show_labels = ifelse(length(vars) > 1, "visible", "hidden"), |
193 | 6x |
table_names = table_names |
194 |
) |
|
195 |
} |
1 |
#' Counting Missed Doses |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' These are specific functions to count patients with missed doses. The difference to [count_cumulative()] is |
|
6 |
#' mainly the special labels. |
|
7 |
#' |
|
8 |
#' @inheritParams s_count_cumulative |
|
9 |
#' @inheritParams argument_convention |
|
10 |
#' @param thresholds (vector of `count`)\cr number of missed doses the patients at least had. |
|
11 |
#' @param .stats (`character`)\cr statistics to select for the table. Run `get_stats("count_missed_doses")` |
|
12 |
#' to see available statistics for this function. |
|
13 |
#' |
|
14 |
#' @seealso Relevant description function [d_count_missed_doses()]. |
|
15 |
#' |
|
16 |
#' @name count_missed_doses |
|
17 |
#' @order 1 |
|
18 |
NULL |
|
19 | ||
20 |
#' @describeIn count_missed_doses Statistics function to count non-missing values. |
|
21 |
#' |
|
22 |
#' @return |
|
23 |
#' * `s_count_nonmissing()` returns the statistic `n` which is the count of non-missing values in `x`. |
|
24 |
#' |
|
25 |
#' @keywords internal |
|
26 |
s_count_nonmissing <- function(x) { |
|
27 | 5x |
list(n = n_available(x)) |
28 |
} |
|
29 | ||
30 |
#' Description Function that Calculates Labels for [s_count_missed_doses()]. |
|
31 |
#' |
|
32 |
#' @description `r lifecycle::badge("stable")` |
|
33 |
#' |
|
34 |
#' @inheritParams s_count_missed_doses |
|
35 |
#' |
|
36 |
#' @return [d_count_missed_doses()] returns a named `character` vector with the labels. |
|
37 |
#' |
|
38 |
#' @seealso [s_count_missed_doses()] |
|
39 |
#' |
|
40 |
#' @export |
|
41 |
d_count_missed_doses <- function(thresholds) { |
|
42 | 4x |
paste0("At least ", thresholds, " missed dose", ifelse(thresholds > 1, "s", "")) |
43 |
} |
|
44 | ||
45 |
#' @describeIn count_missed_doses Statistics function to count patients with missed doses. |
|
46 |
#' |
|
47 |
#' @return |
|
48 |
#' * `s_count_missed_doses()` returns the statistics `n` and `count_fraction` with one element for each threshold. |
|
49 |
#' |
|
50 |
#' @keywords internal |
|
51 |
s_count_missed_doses <- function(x, |
|
52 |
thresholds, |
|
53 |
.N_col) { # nolint |
|
54 | 1x |
stat <- s_count_cumulative( |
55 | 1x |
x = x, |
56 | 1x |
thresholds = thresholds, |
57 | 1x |
lower_tail = FALSE, |
58 | 1x |
include_eq = TRUE, |
59 | 1x |
.N_col = .N_col |
60 |
) |
|
61 | 1x |
labels <- d_count_missed_doses(thresholds) |
62 | 1x |
for (i in seq_along(stat$count_fraction)) { |
63 | 2x |
stat$count_fraction[[i]] <- formatters::with_label(stat$count_fraction[[i]], label = labels[i]) |
64 |
} |
|
65 | 1x |
n_stat <- s_count_nonmissing(x) |
66 | 1x |
c(n_stat, stat) |
67 |
} |
|
68 | ||
69 |
#' @describeIn count_missed_doses Formatted analysis function which is used as `afun` |
|
70 |
#' in `count_missed_doses()`. |
|
71 |
#' |
|
72 |
#' @return |
|
73 |
#' * `a_count_missed_doses()` returns the corresponding list with formatted [rtables::CellValue()]. |
|
74 |
#' |
|
75 |
#' @keywords internal |
|
76 |
a_count_missed_doses <- make_afun( |
|
77 |
s_count_missed_doses, |
|
78 |
.formats = c(n = "xx", count_fraction = format_count_fraction) |
|
79 |
) |
|
80 | ||
81 |
#' @describeIn count_missed_doses Layout-creating function which can take statistics function arguments |
|
82 |
#' and additional format arguments. This function is a wrapper for [rtables::analyze()]. |
|
83 |
#' |
|
84 |
#' @return |
|
85 |
#' * `count_missed_doses()` returns a layout object suitable for passing to further layouting functions, |
|
86 |
#' or to [rtables::build_table()]. Adding this function to an `rtable` layout will add formatted rows containing |
|
87 |
#' the statistics from `s_count_missed_doses()` to the table layout. |
|
88 |
#' |
|
89 |
#' @examples |
|
90 |
#' library(dplyr) |
|
91 |
#' |
|
92 |
#' anl <- tern_ex_adsl %>% |
|
93 |
#' distinct(STUDYID, USUBJID, ARM) %>% |
|
94 |
#' mutate( |
|
95 |
#' PARAMCD = "TNDOSMIS", |
|
96 |
#' PARAM = "Total number of missed doses during study", |
|
97 |
#' AVAL = sample(0:20, size = nrow(tern_ex_adsl), replace = TRUE), |
|
98 |
#' AVALC = "" |
|
99 |
#' ) |
|
100 |
#' |
|
101 |
#' basic_table() %>% |
|
102 |
#' split_cols_by("ARM") %>% |
|
103 |
#' add_colcounts() %>% |
|
104 |
#' count_missed_doses("AVAL", thresholds = c(1, 5, 10, 15), var_labels = "Missed Doses") %>% |
|
105 |
#' build_table(anl, alt_counts_df = tern_ex_adsl) |
|
106 |
#' |
|
107 |
#' @export |
|
108 |
#' @order 2 |
|
109 |
count_missed_doses <- function(lyt, |
|
110 |
vars, |
|
111 |
thresholds, |
|
112 |
var_labels = vars, |
|
113 |
show_labels = "visible", |
|
114 |
na_str = default_na_str(), |
|
115 |
nested = TRUE, |
|
116 |
..., |
|
117 |
table_names = vars, |
|
118 |
.stats = NULL, |
|
119 |
.formats = NULL, |
|
120 |
.labels = NULL, |
|
121 |
.indent_mods = NULL) { |
|
122 | 1x |
extra_args <- list(thresholds = thresholds, ...) |
123 | ||
124 | 1x |
afun <- make_afun( |
125 | 1x |
a_count_missed_doses, |
126 | 1x |
.stats = .stats, |
127 | 1x |
.formats = .formats, |
128 | 1x |
.labels = .labels, |
129 | 1x |
.indent_mods = .indent_mods, |
130 | 1x |
.ungroup_stats = "count_fraction" |
131 |
) |
|
132 | 1x |
analyze( |
133 | 1x |
lyt = lyt, |
134 | 1x |
vars = vars, |
135 | 1x |
afun = afun, |
136 | 1x |
var_labels = var_labels, |
137 | 1x |
table_names = table_names, |
138 | 1x |
show_labels = show_labels, |
139 | 1x |
na_str = na_str, |
140 | 1x |
nested = nested, |
141 | 1x |
extra_args = extra_args |
142 |
) |
|
143 |
} |
1 |
#' Helper Functions for Tabulating Biomarker Effects on Survival by Subgroup |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' Helper functions which are documented here separately to not confuse the user |
|
6 |
#' when reading about the user-facing functions. |
|
7 |
#' |
|
8 |
#' @inheritParams survival_biomarkers_subgroups |
|
9 |
#' @inheritParams argument_convention |
|
10 |
#' @inheritParams fit_coxreg_multivar |
|
11 |
#' |
|
12 |
#' @examples |
|
13 |
#' library(dplyr) |
|
14 |
#' library(forcats) |
|
15 |
#' |
|
16 |
#' adtte <- tern_ex_adtte |
|
17 |
#' |
|
18 |
#' # Save variable labels before data processing steps. |
|
19 |
#' adtte_labels <- formatters::var_labels(adtte, fill = FALSE) |
|
20 |
#' |
|
21 |
#' adtte_f <- adtte %>% |
|
22 |
#' filter(PARAMCD == "OS") %>% |
|
23 |
#' mutate( |
|
24 |
#' AVALU = as.character(AVALU), |
|
25 |
#' is_event = CNSR == 0 |
|
26 |
#' ) |
|
27 |
#' labels <- c("AVALU" = adtte_labels[["AVALU"]], "is_event" = "Event Flag") |
|
28 |
#' formatters::var_labels(adtte_f)[names(labels)] <- labels |
|
29 |
#' |
|
30 |
#' @name h_survival_biomarkers_subgroups |
|
31 |
NULL |
|
32 | ||
33 |
#' @describeIn h_survival_biomarkers_subgroups helps with converting the "survival" function variable list |
|
34 |
#' to the "Cox regression" variable list. The reason is that currently there is an inconsistency between the variable |
|
35 |
#' names accepted by `extract_survival_subgroups()` and `fit_coxreg_multivar()`. |
|
36 |
#' |
|
37 |
#' @param biomarker (`string`)\cr the name of the biomarker variable. |
|
38 |
#' |
|
39 |
#' @return |
|
40 |
#' * `h_surv_to_coxreg_variables()` returns a named `list` of elements `time`, `event`, `arm`, |
|
41 |
#' `covariates`, and `strata`. |
|
42 |
#' |
|
43 |
#' @examples |
|
44 |
#' # This is how the variable list is converted internally. |
|
45 |
#' h_surv_to_coxreg_variables( |
|
46 |
#' variables = list( |
|
47 |
#' tte = "AVAL", |
|
48 |
#' is_event = "EVNT", |
|
49 |
#' covariates = c("A", "B"), |
|
50 |
#' strata = "D" |
|
51 |
#' ), |
|
52 |
#' biomarker = "AGE" |
|
53 |
#' ) |
|
54 |
#' |
|
55 |
#' @export |
|
56 |
h_surv_to_coxreg_variables <- function(variables, biomarker) { |
|
57 | 53x |
checkmate::assert_list(variables) |
58 | 53x |
checkmate::assert_string(variables$tte) |
59 | 53x |
checkmate::assert_string(variables$is_event) |
60 | 53x |
checkmate::assert_string(biomarker) |
61 | 53x |
list( |
62 | 53x |
time = variables$tte, |
63 | 53x |
event = variables$is_event, |
64 | 53x |
arm = biomarker, |
65 | 53x |
covariates = variables$covariates, |
66 | 53x |
strata = variables$strata |
67 |
) |
|
68 |
} |
|
69 | ||
70 |
#' @describeIn h_survival_biomarkers_subgroups prepares estimates for number of events, patients and median survival |
|
71 |
#' times, as well as hazard ratio estimates, confidence intervals and p-values, for multiple biomarkers |
|
72 |
#' in a given single data set. |
|
73 |
#' `variables` corresponds to names of variables found in `data`, passed as a named list and requires elements |
|
74 |
#' `tte`, `is_event`, `biomarkers` (vector of continuous biomarker variables) and optionally `subgroups` and `strat`. |
|
75 |
#' |
|
76 |
#' @return |
|
77 |
#' * `h_coxreg_mult_cont_df()` returns a `data.frame` containing estimates and statistics for the selected biomarkers. |
|
78 |
#' |
|
79 |
#' @examples |
|
80 |
#' # For a single population, estimate separately the effects |
|
81 |
#' # of two biomarkers. |
|
82 |
#' df <- h_coxreg_mult_cont_df( |
|
83 |
#' variables = list( |
|
84 |
#' tte = "AVAL", |
|
85 |
#' is_event = "is_event", |
|
86 |
#' biomarkers = c("BMRKR1", "AGE"), |
|
87 |
#' covariates = "SEX", |
|
88 |
#' strata = c("STRATA1", "STRATA2") |
|
89 |
#' ), |
|
90 |
#' data = adtte_f |
|
91 |
#' ) |
|
92 |
#' df |
|
93 |
#' |
|
94 |
#' # If the data set is empty, still the corresponding rows with missings are returned. |
|
95 |
#' h_coxreg_mult_cont_df( |
|
96 |
#' variables = list( |
|
97 |
#' tte = "AVAL", |
|
98 |
#' is_event = "is_event", |
|
99 |
#' biomarkers = c("BMRKR1", "AGE"), |
|
100 |
#' covariates = "REGION1", |
|
101 |
#' strata = c("STRATA1", "STRATA2") |
|
102 |
#' ), |
|
103 |
#' data = adtte_f[NULL, ] |
|
104 |
#' ) |
|
105 |
#' |
|
106 |
#' @export |
|
107 |
h_coxreg_mult_cont_df <- function(variables, |
|
108 |
data, |
|
109 |
control = control_coxreg()) { |
|
110 | 27x |
assert_df_with_variables(data, variables) |
111 | 27x |
checkmate::assert_list(control, names = "named") |
112 | 27x |
checkmate::assert_character(variables$biomarkers, min.len = 1, any.missing = FALSE) |
113 | 27x |
conf_level <- control[["conf_level"]] |
114 | 27x |
pval_label <- paste0( |
115 |
# the regex capitalizes the first letter of the string / senetence. |
|
116 | 27x |
"p-value (", gsub("(^[a-z])", "\\U\\1", trimws(control[["pval_method"]]), perl = TRUE), ")" |
117 |
) |
|
118 |
# If there is any data, run model, otherwise return empty results. |
|
119 | 27x |
if (nrow(data) > 0) { |
120 | 26x |
bm_cols <- match(variables$biomarkers, names(data)) |
121 | 26x |
l_result <- lapply(variables$biomarkers, function(bm) { |
122 | 52x |
coxreg_list <- fit_coxreg_multivar( |
123 | 52x |
variables = h_surv_to_coxreg_variables(variables, bm), |
124 | 52x |
data = data, |
125 | 52x |
control = control |
126 |
) |
|
127 | 52x |
result <- do.call( |
128 | 52x |
h_coxreg_multivar_extract, |
129 | 52x |
c(list(var = bm), coxreg_list[c("mod", "data", "control")]) |
130 |
) |
|
131 | 52x |
data_fit <- as.data.frame(as.matrix(coxreg_list$mod$y)) |
132 | 52x |
data_fit$status <- as.logical(data_fit$status) |
133 | 52x |
median <- s_surv_time( |
134 | 52x |
df = data_fit, |
135 | 52x |
.var = "time", |
136 | 52x |
is_event = "status" |
137 | 52x |
)$median |
138 | 52x |
data.frame( |
139 |
# Dummy column needed downstream to create a nested header. |
|
140 | 52x |
biomarker = bm, |
141 | 52x |
biomarker_label = formatters::var_labels(data[bm], fill = TRUE), |
142 | 52x |
n_tot = coxreg_list$mod$n, |
143 | 52x |
n_tot_events = coxreg_list$mod$nevent, |
144 | 52x |
median = as.numeric(median), |
145 | 52x |
result[1L, c("hr", "lcl", "ucl")], |
146 | 52x |
conf_level = conf_level, |
147 | 52x |
pval = result[1L, "pval"], |
148 | 52x |
pval_label = pval_label, |
149 | 52x |
stringsAsFactors = FALSE |
150 |
) |
|
151 |
}) |
|
152 | 26x |
do.call(rbind, args = c(l_result, make.row.names = FALSE)) |
153 |
} else { |
|
154 | 1x |
data.frame( |
155 | 1x |
biomarker = variables$biomarkers, |
156 | 1x |
biomarker_label = formatters::var_labels(data[variables$biomarkers], fill = TRUE), |
157 | 1x |
n_tot = 0L, |
158 | 1x |
n_tot_events = 0L, |
159 | 1x |
median = NA, |
160 | 1x |
hr = NA, |
161 | 1x |
lcl = NA, |
162 | 1x |
ucl = NA, |
163 | 1x |
conf_level = conf_level, |
164 | 1x |
pval = NA, |
165 | 1x |
pval_label = pval_label, |
166 | 1x |
row.names = seq_along(variables$biomarkers), |
167 | 1x |
stringsAsFactors = FALSE |
168 |
) |
|
169 |
} |
|
170 |
} |
|
171 | ||
172 |
#' @describeIn h_survival_biomarkers_subgroups prepares a single sub-table given a `df_sub` containing |
|
173 |
#' the results for a single biomarker. |
|
174 |
#' |
|
175 |
#' @param df (`data.frame`)\cr results for a single biomarker, as part of what is |
|
176 |
#' returned by [extract_survival_biomarkers()] (it needs a couple of columns which are |
|
177 |
#' added by that high-level function relative to what is returned by [h_coxreg_mult_cont_df()], |
|
178 |
#' see the example). |
|
179 |
#' |
|
180 |
#' @return |
|
181 |
#' * `h_tab_surv_one_biomarker()` returns an `rtables` table object with the given statistics arranged in columns. |
|
182 |
#' |
|
183 |
#' @examples |
|
184 |
#' # Starting from above `df`, zoom in on one biomarker and add required columns. |
|
185 |
#' df1 <- df[1, ] |
|
186 |
#' df1$subgroup <- "All patients" |
|
187 |
#' df1$row_type <- "content" |
|
188 |
#' df1$var <- "ALL" |
|
189 |
#' df1$var_label <- "All patients" |
|
190 |
#' h_tab_surv_one_biomarker( |
|
191 |
#' df1, |
|
192 |
#' vars = c("n_tot", "n_tot_events", "median", "hr", "ci", "pval"), |
|
193 |
#' time_unit = "days" |
|
194 |
#' ) |
|
195 |
#' |
|
196 |
#' @export |
|
197 |
h_tab_surv_one_biomarker <- function(df, |
|
198 |
vars, |
|
199 |
time_unit, |
|
200 |
na_str = default_na_str(), |
|
201 |
.indent_mods = 0L, |
|
202 |
...) { |
|
203 | 8x |
afuns <- a_survival_subgroups(na_str = na_str)[vars] |
204 | 8x |
colvars <- d_survival_subgroups_colvars( |
205 | 8x |
vars, |
206 | 8x |
conf_level = df$conf_level[1], |
207 | 8x |
method = df$pval_label[1], |
208 | 8x |
time_unit = time_unit |
209 |
) |
|
210 | 8x |
h_tab_one_biomarker( |
211 | 8x |
df = df, |
212 | 8x |
afuns = afuns, |
213 | 8x |
colvars = colvars, |
214 | 8x |
na_str = na_str, |
215 | 8x |
.indent_mods = .indent_mods, |
216 |
... |
|
217 |
) |
|
218 |
} |
1 |
#' Control Function for Logistic Regression Model Fitting |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' This is an auxiliary function for controlling arguments for logistic regression models. |
|
6 |
#' `conf_level` refers to the confidence level used for the Odds Ratio CIs. |
|
7 |
#' |
|
8 |
#' @inheritParams argument_convention |
|
9 |
#' @param response_definition (`string`)\cr the definition of what an event is in terms of `response`. |
|
10 |
#' This will be used when fitting the logistic regression model on the left hand side of the formula. |
|
11 |
#' Note that the evaluated expression should result in either a logical vector or a factor with 2 |
|
12 |
#' levels. By default this is just `"response"` such that the original response variable is used |
|
13 |
#' and not modified further. |
|
14 |
#' |
|
15 |
#' @return A list of components with the same names as the arguments. |
|
16 |
#' |
|
17 |
#' @examples |
|
18 |
#' # Standard options. |
|
19 |
#' control_logistic() |
|
20 |
#' |
|
21 |
#' # Modify confidence level. |
|
22 |
#' control_logistic(conf_level = 0.9) |
|
23 |
#' |
|
24 |
#' # Use a different response definition. |
|
25 |
#' control_logistic(response_definition = "I(response %in% c('CR', 'PR'))") |
|
26 |
#' |
|
27 |
#' @export |
|
28 |
control_logistic <- function(response_definition = "response", |
|
29 |
conf_level = 0.95) { |
|
30 | 29x |
checkmate::assert_true(grepl("response", response_definition)) |
31 | 28x |
checkmate::assert_string(response_definition) |
32 | 28x |
assert_proportion_value(conf_level) |
33 | 27x |
list( |
34 | 27x |
response_definition = response_definition, |
35 | 27x |
conf_level = conf_level |
36 |
) |
|
37 |
} |
1 |
#' Generate PK reference dataset |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' @return `data.frame` of PK parameters |
|
6 |
#' |
|
7 |
#' @examples |
|
8 |
#' pk_reference_dataset <- d_pkparam() |
|
9 |
#' |
|
10 |
#' @export |
|
11 |
d_pkparam <- function() { |
|
12 | 4x |
pk_dataset <- as.data.frame(matrix( |
13 | 4x |
c( |
14 | 4x |
"TMAX", "Time of CMAX", "Tmax", "Plasma/Blood/Serum", "1", |
15 | 4x |
"CMAX", "Max Conc", "Cmax", "Plasma/Blood/Serum", "2", |
16 | 4x |
"CMAXD", "Max Conc Norm by Dose", "Cmax/D", "Plasma/Blood/Serum", "3", |
17 | 4x |
"AUCIFO", "AUC Infinity Obs", "AUCinf obs", "Plasma/Blood/Serum", "4", |
18 | 4x |
"AUCIFP", "AUC Infinity Pred", "AUCinf pred", "Plasma/Blood/Serum", "5", |
19 | 4x |
"AUCIFOD", "AUC Infinity Obs Norm by Dose", "AUCinf/D obs", "Plasma/Blood/Serum", "6", |
20 | 4x |
"AUCIFD", "AUC Infinity Pred Norm by Dose", "AUCinf/D pred", "Plasma/Blood/Serum", "7", |
21 | 4x |
"AUCPEO", "AUC %Extrapolation Obs", "AUCinf extrap obs", "Plasma/Blood/Serum", "8", |
22 | 4x |
"AUCPEP", "AUC %Extrapolation Pred", "AUCinf extrap pred", "Plasma/Blood/Serum", "9", |
23 | 4x |
"AUCINT", "AUC from T1 to T2", "AUCupper-lower ", "Plasma/Blood/Serum", "10", |
24 | 4x |
"AUCTAU", "AUC Over Dosing Interval", "AUCtau", "Plasma/Blood/Serum", "11", |
25 | 4x |
"AUCLST", "AUC to Last Nonzero Conc", "AUClast", "Plasma/Blood/Serum", "12", |
26 | 4x |
"AUCALL", "AUC All", "AUCall", "Plasma/Blood/Serum", "13", |
27 | 4x |
"AUMCIFO", "AUMC Infinity Obs", "AUMCinf obs", "Plasma/Blood/Serum", "14", |
28 | 4x |
"AUMCIFP", "AUMC Infinity Pred", "AUMCinf pred", "Plasma/Blood/Serum", "15", |
29 | 4x |
"AUMCPEO", "AUMC % Extrapolation Obs", "AUMC extrap obs", "Plasma/Blood/Serum", "16", |
30 | 4x |
"AUMCPEP", "AUMC % Extrapolation Pred", "AUMC extrap pred", "Plasma/Blood/Serum", "17", |
31 | 4x |
"AUMCTAU", "AUMC Over Dosing Interval", "AUMCtau", "Plasma/Blood/Serum", "18", |
32 | 4x |
"AUMCLST", "AUMC to Last Nonzero Conc", "AUMClast", "Plasma/Blood/Serum", "19", |
33 | 4x |
"AURCIFO", "AURC Infinity Obs", "AURCinf obs", "Plasma/Blood/Serum", "20", |
34 | 4x |
"AURCIFP", "AURC Infinity Pred", "AURCinf pred", "Plasma/Blood/Serum", "21", |
35 | 4x |
"AURCPEO", "AURC % Extrapolation Obs", "AURC extrap obs", "Plasma/Blood/Serum", "22", |
36 | 4x |
"AURCPEP", "AURC % Extrapolation Pred", "AURC extrap pred", "Plasma/Blood/Serum", "23", |
37 | 4x |
"AURCLST", "AURC Dosing to Last Conc", "AURClast", "Plasma/Blood/Serum", "24", |
38 | 4x |
"AURCALL", "AURC All", "AURCall", "Plasma/Blood/Serum", "25", |
39 | 4x |
"TLST", "Time of Last Nonzero Conc", "Tlast", "Plasma/Blood/Serum", "26", |
40 | 4x |
"CO", "Initial Conc", "CO", "Plasma/Blood/Serum", "27", |
41 | 4x |
"C0", "Initial Conc", "C0", "Plasma/Blood/Serum", "28", |
42 | 4x |
"CAVG", "Average Conc", "Cavg", "Plasma/Blood/Serum", "29", |
43 | 4x |
"CLST", "Last Nonzero Conc", "Clast", "Plasma/Blood/Serum", "30", |
44 | 4x |
"CMIN", "Min Conc", "Cmin", "Plasma/Blood/Serum", "31", |
45 | 4x |
"LAMZHL", "Half-Life Lambda z", "t1/2", "Plasma/Blood/Serum", "32", |
46 | 4x |
"CLFO", "Total CL Obs by F", "CL/F obs", "Plasma/Blood/Serum", "33", |
47 | 4x |
"CLFP", "Total CL Pred by F", "CL/F pred", "Plasma/Blood/Serum", "34", |
48 | 4x |
"CLO", "Total CL Obs", "CL obs", "Plasma/Blood/Serum", "35", |
49 | 4x |
"CLP", "Total CL Pred", "CL pred", "Plasma/Blood/Serum", "36", |
50 | 4x |
"CLSS", "Total CL Steady State Pred", "CLss", "Plasma/Blood/Serum", "37", |
51 | 4x |
"CLSSF", "Total CL Steady State Pred by F", "CLss/F", "Plasma/Blood/Serum", "38", |
52 | 4x |
"VZFO", "Vz Obs by F", "Vz/F obs", "Plasma/Blood/Serum", "39", |
53 | 4x |
"VZFP", "Vz Pred by F", "Vz/F pred", "Plasma/Blood/Serum", "40", |
54 | 4x |
"VZO", "Vz Obs", "Vz obs", "Plasma/Blood/Serum", "41", |
55 | 4x |
"VZP", "Vz Pred", "Vz pred", "Plasma/Blood/Serum", "42", |
56 | 4x |
"VSSO", "Vol Dist Steady State Obs", "Vss obs", "Plasma/Blood/Serum", "43", |
57 | 4x |
"VSSP", "Vol Dist Steady State Pred", "Vss pred", "Plasma/Blood/Serum", "44", |
58 | 4x |
"LAMZ", "Lambda z", "Lambda z", "Plasma/Blood/Serum", "45", |
59 | 4x |
"LAMZLL", "Lambda z Lower Limit", "Lambda z lower", "Plasma/Blood/Serum", "46", |
60 | 4x |
"LAMZUL", "Lambda z Upper Limit", "Lambda z upper", "Plasma/Blood/Serum", "47", |
61 | 4x |
"LAMZNPT", "Number of Points for Lambda z", "No points Lambda z", "Plasma/Blood/Serum", "48", |
62 | 4x |
"MRTIFO", "MRT Infinity Obs", "MRTinf obs", "Plasma/Blood/Serum", "49", |
63 | 4x |
"MRTIFP", "MRT Infinity Pred", "MRTinf pred", "Plasma/Blood/Serum", "50", |
64 | 4x |
"MRTLST", "MRT to Last Nonzero Conc", "MRTlast", "Plasma/Blood/Serum", "51", |
65 | 4x |
"R2", "R Squared", "Rsq", "Plasma/Blood/Serum", "52", |
66 | 4x |
"R2ADJ", "R Squared Adjusted", "Rsq adjusted", "Plasma/Blood/Serum", "53", |
67 | 4x |
"TLAG", "Time Until First Nonzero Conc", "TIag", "Plasma/Blood/Serum", "54", |
68 | 4x |
"TMIN", "Time of CMIN Observation", "Tmin", "Plasma/Blood/Serum", "55", |
69 | 4x |
"ACCI", "Accumulation Index", "Accumulation Index", "Plasma/Blood/Serum/Urine", "56", |
70 | 4x |
"FLUCP", "Fluctuation%", "Fluctuation", "Plasma/Blood/Serum", "57", |
71 | 4x |
"CORRXY", "Correlation Between TimeX and Log ConcY", "Corr xy", "Plasma/Blood/Serum", "58", |
72 | 4x |
"RCAMINT", "Amt Rec from T1 to T2", "Ae", "Urine", "59", |
73 | 4x |
"RCPCINT", "Pct Rec from T1 to T2", "Fe", "Urine", "60", |
74 | 4x |
"VOLPK", "Sum of Urine Vol", "Urine volume", "Urine", "61", |
75 | 4x |
"RENALCL", "Renal CL", "CLR", "Plasma/Blood/Serum/Urine", "62", |
76 | 4x |
"ERTMAX", "Time of Max Excretion Rate", "Tmax Rate", "Urine", "63", |
77 | 4x |
"RMAX", "Time of Maximum Response", "Rmax", "Matrix of PD", "64", |
78 | 4x |
"RMIN", "Time of Minimum Response", "Rmin", "Matrix of PD", "65", |
79 | 4x |
"ERMAX", "Max Excretion Rate", "Max excretion rate", "Urine", "66", |
80 | 4x |
"MIDPTLST", "Midpoint of Collection Interval", "Midpoint last", "Urine", "67", |
81 | 4x |
"ERLST", "Last Meas Excretion Rate", "Rate last", "Urine", "68", |
82 | 4x |
"TON", "Time to Onset", "Tonset", "Matrix of PD", "69", |
83 | 4x |
"TOFF", "Time to Offset", "Toffset", "Matrix of PD", "70", |
84 | 4x |
"TBBLP", "Time Below Baseline %", "Time %Below Baseline", "Matrix of PD", "71", |
85 | 4x |
"TBTP", "Time Below Threshold %", "Time %Below Threshold", "Matrix of PD", "72", |
86 | 4x |
"TABL", "Time Above Baseline", "Time Above Baseline", "Matrix of PD", "73", |
87 | 4x |
"TAT", "Time Above Threshold", "Time Above Threshold", "Matrix of PD", "74", |
88 | 4x |
"TBT", "Time Below Threshold", "Time Below Threshold", "Matrix of PD", "75", |
89 | 4x |
"TBLT", "Time Between Baseline and Threshold", "Time Between Baseline Threshold", "Matrix of PD", "76", |
90 | 4x |
"BLRSP", "Baseline Response", "Baseline", "Matrix of PD", "77", |
91 | 4x |
"TSHDRSP", "Response Threshold", "Threshold", "Matrix of PD", "78", |
92 | 4x |
"AUCABL", "AUC Above Baseline", "AUC above baseline", "Matrix of PD", "79", |
93 | 4x |
"AUCAT", "AUC Above Threshold", "AUC above threshold", "Matrix of PD", "80", |
94 | 4x |
"AUCBBL", "AUC Below Baseline", "AUC below baseline", "Matrix of PD", "81", |
95 | 4x |
"AUCBT", "AUC Below Threshold", "AUC below threshold", "Matrix of PD", "82", |
96 | 4x |
"AUCBLDIF", "Diff AUC Above Base and AUC Below Base", "AUC diff baseline", "Matrix of PD", "83", |
97 | 4x |
"AUCTDIF", "Diff AUC Above Thr and AUC Below Thr", "AUCnet threshold", "Matrix of PD", "84", |
98 | 4x |
"TDIFF", "Diff Time to Offset and Time to Onset", "Diff toffset-tonset", "Matrix of PD", "85", |
99 | 4x |
"AUCPBEO", "AUC %Back Extrapolation Obs", "AUC%Back extrap obs", "Plasma/Blood/Serum", "86", |
100 | 4x |
"AUCPBEP", "AUC %Back Extrapolation Pred", "AUC%Back extrap pred", "Plasma/Blood/Serum", "87", |
101 | 4x |
"TSLP1L", "Lower Time Limit Slope 1st", "Slope1 lower", "Matrix of PD", "88", |
102 | 4x |
"TSLP1U", "Upper Time Limit Slope 1st Segment", "Slope1 upper", "Matrix of PD", "89", |
103 | 4x |
"TSLP2L", "Lower Time Limit Slope 2nd Segment", "Slope2 lower", "Matrix of PD", "90", |
104 | 4x |
"TSLP2U", "Upper Time Limit Slope 2nd Segment", "Slope2 upper", "Matrix of PD", "91", |
105 | 4x |
"SLP1", "Slope, 1st Segment", "Slope1", "Matrix of PD", "92", |
106 | 4x |
"SLP2", "Slope, 2nd Segment", "Slope2", "Matrix of PD", "93", |
107 | 4x |
"SLP1PT", "Number of Points for Slope 1st Segment", "No points slope1", "Matrix of PD", "94", |
108 | 4x |
"SLP2PT", "Number of Points for Slope 2nd Segment", "No points slope2", "Matrix of PD", "95", |
109 | 4x |
"R2ADJS1", "R-Squared Adjusted Slope, 1st Segment", "Rsq adjusted slope1", "Matrix of PD", "96", |
110 | 4x |
"R2ADJS2", "R-Squared Adjusted Slope, 2nd Segment", "Rsq adjusted slope2", "Matrix of PD", "97", |
111 | 4x |
"R2SLP1", "R Squared, Slope, 1st Segment", "Rsq slope1", "Matrix of PD", "98", |
112 | 4x |
"R2SLP2", "R Squared, Slope, 2nd Segment", "Rsq slope2", "Matrix of PD", "99", |
113 | 4x |
"CORRXYS1", "Corr Btw TimeX and Log ConcY, Slope 1st", "Corr xy slope1", "Plasma/Blood/Serum", "100", |
114 | 4x |
"CORRXYS2", "Corr Btw TimeX and Log ConcY, Slope 1st Slope 2nd", "Corr xy slope2", "Plasma/Blood/Serum", "101", |
115 | 4x |
"AILAMZ", "Accumulation Index using Lambda z", "AILAMZ", "Plasma/Blood/Serum", "102", |
116 | 4x |
"ARAUC", "Accumulation Ratio AUCTAU", "ARAUC", "Plasma/Blood/Serum", "103", |
117 | 4x |
"ARAUCD", "Accum Ratio AUCTAU norm by dose", "ARAUCD", "Plasma/Blood/Serum", "104", |
118 | 4x |
"ARAUCIFO", "Accum Ratio AUC Infinity Obs", "ARAUCIFO", "Plasma/Blood/Serum", "105", |
119 | 4x |
"ARAUCIFP", "Accum Ratio AUC Infinity Pred", "ARAUCIFP", "Plasma/Blood/Serum", "106", |
120 | 4x |
"ARAUCIND", "Accum Ratio AUC T1 to T2 norm by dose", "ARAUCIND_T1_T2_UNIT", "Plasma/Blood/Serum", "107", |
121 | 4x |
"ARAUCINT", "Accumulation Ratio AUC from T1 to T2", "ARAUCINT_T1_T2_UNIT", "Plasma/Blood/Serum", "108", |
122 | 4x |
"ARAUCIOD", "Accum Ratio AUCIFO Norm by Dose", "ARAUCIOD", "Plasma/Blood/Serum", "109", |
123 | 4x |
"ARAUCIPD", "Accum Ratio AUCIFP Norm by Dose", "ARAUCIPD", "Plasma/Blood/Serum", "110", |
124 | 4x |
"ARAUCLST", "Accum Ratio AUC to Last Nonzero Conc", "ARAUCLST", "Plasma/Blood/Serum", "111", |
125 | 4x |
"ARCMAX", "Accumulation Ratio Cmax", "ARCMAX", "Plasma/Blood/Serum", "112", |
126 | 4x |
"ARCMAXD", "Accum Ratio Cmax norm by dose", "ARCMAXD", "Plasma/Blood/Serum", "113", |
127 | 4x |
"ARCMIN", "Accumulation Ratio Cmin", "ARCMIN", "Plasma/Blood/Serum", "114", |
128 | 4x |
"ARCMIND", "Accum Ratio Cmin norm by dose", "ARCMIND", "Plasma/Blood/Serum", "115", |
129 | 4x |
"ARCTROUD", "Accum Ratio Ctrough norm by dose", "ARCTROUD", "Plasma/Blood/Serum", "116", |
130 | 4x |
"ARCTROUG", "Accumulation Ratio Ctrough", "ARCTROUG", "Plasma/Blood/Serum", "117", |
131 | 4x |
"AUCALLB", "AUC All Norm by BMI", "AUCall_B", "Plasma/Blood/Serum", "118", |
132 | 4x |
"AUCALLD", "AUC All Norm by Dose", "AUCall_D", "Plasma/Blood/Serum", "119", |
133 | 4x |
"AUCALLS", "AUC All Norm by SA", "AUCall_S", "Plasma/Blood/Serum", "120", |
134 | 4x |
"AUCALLW", "AUC All Norm by WT", "AUCall_W", "Plasma/Blood/Serum", "121", |
135 | 4x |
"AUCIFOB", "AUC Infinity Obs Norm by BMI", "AUCINF_obs_B", "Plasma/Blood/Serum", "122", |
136 | 4x |
"AUCIFOLN", "AUC Infinity Obs LN Transformed", "AUCIFOLN", "Plasma/Blood/Serum", "123", |
137 | 4x |
"AUCIFOS", "AUC Infinity Obs Norm by SA", "AUCINF_obs_S", "Plasma/Blood/Serum", "124", |
138 | 4x |
"AUCIFOUB", "AUC Infinity Obs, Unbound Drug", "AUCIFOUB", "Plasma/Blood/Serum", "125", |
139 | 4x |
"AUCIFOW", "AUC Infinity Obs Norm by WT", "AUCINF_obs_W", "Plasma/Blood/Serum", "126", |
140 | 4x |
"AUCIFPB", "AUC Infinity Pred Norm by BMI", "AUCINF_pred_B", "Plasma/Blood/Serum", "127", |
141 | 4x |
"AUCIFPD", "AUC Infinity Pred Norm by Dose", "AUCINF_pred_D", "Plasma/Blood/Serum", "128", |
142 | 4x |
"AUCIFPS", "AUC Infinity Pred Norm by SA", "AUCINF_pred_S", "Plasma/Blood/Serum", "129", |
143 | 4x |
"AUCIFPUB", "AUC Infinity Pred, Unbound Drug", "AUCIFPUB", "Plasma/Blood/Serum", "130", |
144 | 4x |
"AUCIFPW", "AUC Infinity Pred Norm by WT", "AUCINF_pred_W", "Plasma/Blood/Serum", "131", |
145 | 4x |
"AUCINTB", "AUC from T1 to T2 Norm by BMI", "AUC_B_T1_T2_UNIT", "Plasma/Blood/Serum", "132", |
146 | 4x |
"AUCINTD", "AUC from T1 to T2 Norm by Dose", "AUC_D_T1_T2_UNIT", "Plasma/Blood/Serum", "133", |
147 | 4x |
"AUCINTS", "AUC from T1 to T2 Norm by SA", "AUC_S_T1_T2_UNIT", "Plasma/Blood/Serum", "134", |
148 | 4x |
"AUCINTW", "AUC from T1 to T2 Norm by WT", "AUC_W_T1_T2_UNIT", "Plasma/Blood/Serum", "135", |
149 | 4x |
"AUCLSTB", "AUC to Last Nonzero Conc Norm by BMI", "AUClast_B", "Plasma/Blood/Serum", "136", |
150 | 4x |
"AUCLSTD", "AUC to Last Nonzero Conc Norm by Dose", "AUClast_D", "Plasma/Blood/Serum", "137", |
151 | 4x |
"AUCLSTLN", "AUC to Last Nonzero Conc LN Transformed", "AUCLSTLN", "Plasma/Blood/Serum", "138", |
152 | 4x |
"AUCLSTS", "AUC to Last Nonzero Conc Norm by SA", "AUClast_S", "Plasma/Blood/Serum", "139", |
153 | 4x |
"AUCLSTUB", "AUC to Last Nonzero Conc, Unbound Drug", "AUCLSTUB", "Plasma/Blood/Serum", "140", |
154 | 4x |
"AUCLSTW", "AUC to Last Nonzero Conc Norm by WT", "AUClast_W", "Plasma/Blood/Serum", "141", |
155 | 4x |
"AUCTAUB", "AUC Over Dosing Interval Norm by BMI", "AUC_TAU_B", "Plasma/Blood/Serum", "142", |
156 | 4x |
"AUCTAUD", "AUC Over Dosing Interval Norm by Dose", "AUC_TAU_D", "Plasma/Blood/Serum", "143", |
157 | 4x |
"AUCTAUS", "AUC Over Dosing Interval Norm by SA", "AUC_TAU_S", "Plasma/Blood/Serum", "144", |
158 | 4x |
"AUCTAUW", "AUC Over Dosing Interval Norm by WT", "AUC_TAU_W", "Plasma/Blood/Serum", "145", |
159 | 4x |
"AUMCIFOB", "AUMC Infinity Obs Norm by BMI", "AUMCINF_obs_B", "Plasma/Blood/Serum", "146", |
160 | 4x |
"AUMCIFOD", "AUMC Infinity Obs Norm by Dose", "AUMCINF_obs_D", "Plasma/Blood/Serum", "147", |
161 | 4x |
"AUMCIFOS", "AUMC Infinity Obs Norm by SA", "AUMCINF_obs_S", "Plasma/Blood/Serum", "148", |
162 | 4x |
"AUMCIFOW", "AUMC Infinity Obs Norm by WT", "AUMCINF_obs_W", "Plasma/Blood/Serum", "149", |
163 | 4x |
"AUMCIFPB", "AUMC Infinity Pred Norm by BMI", "AUMCINF_pred_B", "Plasma/Blood/Serum", "150", |
164 | 4x |
"AUMCIFPD", "AUMC Infinity Pred Norm by Dose", "AUMCINF_pred_D", "Plasma/Blood/Serum", "151", |
165 | 4x |
"AUMCIFPS", "AUMC Infinity Pred Norm by SA", "AUMCINF_pred_S", "Plasma/Blood/Serum", "152", |
166 | 4x |
"AUMCIFPW", "AUMC Infinity Pred Norm by WT", "AUMCINF_pred_W", "Plasma/Blood/Serum", "153", |
167 | 4x |
"AUMCLSTB", "AUMC to Last Nonzero Conc Norm by BMI", "AUMClast_B", "Plasma/Blood/Serum", "154", |
168 | 4x |
"AUMCLSTD", "AUMC to Last Nonzero Conc Norm by Dose", "AUMClast_D", "Plasma/Blood/Serum", "155", |
169 | 4x |
"AUMCLSTS", "AUMC to Last Nonzero Conc Norm by SA", "AUMClast_S", "Plasma/Blood/Serum", "156", |
170 | 4x |
"AUMCLSTW", "AUMC to Last Nonzero Conc Norm by WT", "AUMClast_W", "Plasma/Blood/Serum", "157", |
171 | 4x |
"AUMCTAUB", "AUMC Over Dosing Interval Norm by BMI", "AUMCTAUB", "Plasma/Blood/Serum", "158", |
172 | 4x |
"AUMCTAUD", "AUMC Over Dosing Interval Norm by Dose", "AUMCTAUD", "Plasma/Blood/Serum", "159", |
173 | 4x |
"AUMCTAUS", "AUMC Over Dosing Interval Norm by SA", "AUMCTAUS", "Plasma/Blood/Serum", "160", |
174 | 4x |
"AUMCTAUW", "AUMC Over Dosing Interval Norm by WT", "AUMCTAUW", "Plasma/Blood/Serum", "161", |
175 | 4x |
"AURCALLB", "AURC All Norm by BMI", "AURCALLB", "Plasma/Blood/Serum", "162", |
176 | 4x |
"AURCALLD", "AURC All Norm by Dose", "AURCALLD", "Plasma/Blood/Serum", "163", |
177 | 4x |
"AURCALLS", "AURC All Norm by SA", "AURCALLS", "Plasma/Blood/Serum", "164", |
178 | 4x |
"AURCALLW", "AURC All Norm by WT", "AURCALLW", "Plasma/Blood/Serum", "165", |
179 | 4x |
"AURCIFOB", "AURC Infinity Obs Norm by BMI", "AURCIFOB", "Plasma/Blood/Serum", "166", |
180 | 4x |
"AURCIFOD", "AURC Infinity Obs Norm by Dose", "AURCIFOD", "Plasma/Blood/Serum", "167", |
181 | 4x |
"AURCIFOS", "AURC Infinity Obs Norm by SA", "AURCIFOS", "Plasma/Blood/Serum", "168", |
182 | 4x |
"AURCIFOW", "AURC Infinity Obs Norm by WT", "AURCIFOW", "Plasma/Blood/Serum", "169", |
183 | 4x |
"AURCIFPB", "AURC Infinity Pred Norm by BMI", "AURCIFPB", "Plasma/Blood/Serum", "170", |
184 | 4x |
"AURCIFPD", "AURC Infinity Pred Norm by Dose", "AURCIFPD", "Plasma/Blood/Serum", "171", |
185 | 4x |
"AURCIFPS", "AURC Infinity Pred Norm by SA", "AURCIFPS", "Plasma/Blood/Serum", "172", |
186 | 4x |
"AURCIFPW", "AURC Infinity Pred Norm by WT", "AURCIFPW", "Plasma/Blood/Serum", "173", |
187 | 4x |
"AURCINT", "AURC from T1 to T2", "AURCINT_T1_T2_UNIT", "Plasma/Blood/Serum", "174", |
188 | 4x |
"AURCINTB", "AURC from T1 to T2 Norm by BMI", "AURCINTB_T1_T2_UNIT", "Plasma/Blood/Serum", "175", |
189 | 4x |
"AURCINTD", "AURC from T1 to T2 Norm by Dose", "AURCINTD_T1_T2_UNIT", "Plasma/Blood/Serum", "176", |
190 | 4x |
"AURCINTS", "AURC from T1 to T2 Norm by SA", "AURCINTS_T1_T2_UNIT", "Plasma/Blood/Serum", "177", |
191 | 4x |
"AURCINTW", "AURC from T1 to T2 Norm by WT", "AURCINTW_T1_T2_UNIT", "Plasma/Blood/Serum", "178", |
192 | 4x |
"AURCLSTB", "AURC to Last Nonzero Rate Norm by BMI", "AURCLSTB", "Plasma/Blood/Serum", "179", |
193 | 4x |
"AURCLSTD", "AURC to Last Nonzero Rate Norm by Dose", "AURCLSTD", "Plasma/Blood/Serum", "180", |
194 | 4x |
"AURCLSTS", "AURC to Last Nonzero Rate Norm by SA", "AURCLSTS", "Plasma/Blood/Serum", "181", |
195 | 4x |
"AURCLSTW", "AURC to Last Nonzero Rate Norm by WT", "AURCLSTW", "Plasma/Blood/Serum", "182", |
196 | 4x |
"C0B", "Initial Conc Norm by BMI", "C0B", "Plasma/Blood/Serum", "183", |
197 | 4x |
"C0D", "Initial Conc Norm by Dose", "C0D", "Plasma/Blood/Serum", "184", |
198 | 4x |
"C0S", "Initial Conc Norm by SA", "C0S", "Plasma/Blood/Serum", "185", |
199 | 4x |
"C0W", "Initial Conc Norm by WT", "C0W", "Plasma/Blood/Serum", "186", |
200 | 4x |
"CAVGB", "Average Conc Norm by BMI", "CAVGB", "Plasma/Blood/Serum", "187", |
201 | 4x |
"CAVGD", "Average Conc Norm by Dose", "CAVGD", "Plasma/Blood/Serum", "188", |
202 | 4x |
"CAVGINT", "Average Conc from T1 to T2", "CAVGINT_T1_T2_UNIT", "Plasma/Blood/Serum", "189", |
203 | 4x |
"CAVGINTB", "Average Conc from T1 to T2 Norm by BMI", "CAVGINTB_T1_T2_UNIT", "Plasma/Blood/Serum", "190", |
204 | 4x |
"CAVGINTD", "Average Conc from T1 to T2 Norm by Dose", "CAVGINTD_T1_T2_UNIT", "Plasma/Blood/Serum", "191", |
205 | 4x |
"CAVGINTS", "Average Conc from T1 to T2 Norm by SA", "CAVGINTS_T1_T2_UNIT", "Plasma/Blood/Serum", "192", |
206 | 4x |
"CAVGINTW", "Average Conc from T1 to T2 Norm by WT", "CAVGINTW_T1_T2_UNIT", "Plasma/Blood/Serum", "193", |
207 | 4x |
"CAVGS", "Average Conc Norm by SA", "CAVGS", "Plasma/Blood/Serum", "194", |
208 | 4x |
"CAVGW", "Average Conc Norm by WT", "CAVGW", "Plasma/Blood/Serum", "195", |
209 | 4x |
"CHTMAX", "Concentration at Half Tmax", "CHTMAX", "Plasma/Blood/Serum", "196", |
210 | 4x |
"CLFOB", "Total CL Obs by F Norm by BMI", "CLFOB", "Plasma/Blood/Serum", "197", |
211 | 4x |
"CLFOD", "Total CL Obs by F Norm by Dose", "CLFOD", "Plasma/Blood/Serum", "198", |
212 | 4x |
"CLFOS", "Total CL Obs by F Norm by SA", "CLFOS", "Plasma/Blood/Serum", "199", |
213 | 4x |
"CLFOW", "Total CL Obs by F Norm by WT", "CLFOW", "Plasma/Blood/Serum", "200", |
214 | 4x |
"CLFPB", "Total CL Pred by F Norm by BMI", "CLFPB", "Plasma/Blood/Serum", "201", |
215 | 4x |
"CLFPD", "Total CL Pred by F Norm by Dose", "CLFPD", "Plasma/Blood/Serum", "202", |
216 | 4x |
"CLFPS", "Total CL Pred by F Norm by SA", "CLFPS", "Plasma/Blood/Serum", "203", |
217 | 4x |
"CLFPW", "Total CL Pred by F Norm by WT", "CLFPW", "Plasma/Blood/Serum", "204", |
218 | 4x |
"CLFTAU", "Total CL by F for Dose Int", "CLFTAU", "Plasma/Blood/Serum", "205", |
219 | 4x |
"CLFTAUB", "Total CL by F for Dose Int Norm by BMI", "CLFTAUB", "Plasma/Blood/Serum", "206", |
220 | 4x |
"CLFTAUD", "Total CL by F for Dose Int Norm by Dose", "CLFTAUD", "Plasma/Blood/Serum", "207", |
221 | 4x |
"CLFTAUS", "Total CL by F for Dose Int Norm by SA", "CLFTAUS", "Plasma/Blood/Serum", "208", |
222 | 4x |
"CLFTAUW", "Total CL by F for Dose Int Norm by WT", "CLFTAUW", "Plasma/Blood/Serum", "209", |
223 | 4x |
"CLFUB", "Apparent CL for Unbound Drug", "CLFUB", "Plasma/Blood/Serum", "210", |
224 | 4x |
"CLOB", "Total CL Obs Norm by BMI", "CLOB", "Plasma/Blood/Serum", "211", |
225 | 4x |
"CLOD", "Total CL Obs Norm by Dose", "CLOD", "Plasma/Blood/Serum", "212", |
226 | 4x |
"CLOS", "Total CL Obs Norm by SA", "CLOS", "Plasma/Blood/Serum", "213", |
227 | 4x |
"CLOUB", "Total CL Obs for Unbound Drug", "CLOUB", "Plasma/Blood/Serum", "214", |
228 | 4x |
"CLOW", "Total CL Obs Norm by WT", "CLOW", "Plasma/Blood/Serum", "215", |
229 | 4x |
"CLPB", "Total CL Pred Norm by BMI", "CLPB", "Plasma/Blood/Serum", "216", |
230 | 4x |
"CLPD", "Total CL Pred Norm by Dose", "CLPD", "Plasma/Blood/Serum", "217", |
231 | 4x |
"CLPS", "Total CL Pred Norm by SA", "CLPS", "Plasma/Blood/Serum", "218", |
232 | 4x |
"CLPUB", "Total CL Pred for Unbound Drug", "CLPUB", "Plasma/Blood/Serum", "219", |
233 | 4x |
"CLPW", "Total CL Pred Norm by WT", "CLPW", "Plasma/Blood/Serum", "220", |
234 | 4x |
"CLRPCLEV", "Renal CL as Pct CL EV", "CLRPCLEV", "Urine", "221", |
235 | 4x |
"CLRPCLIV", "Renal CL as Pct CL IV", "CLRPCLIV", "Urine", "222", |
236 | 4x |
"CLSTB", "Last Nonzero Conc Norm by BMI", "CLSTB", "Plasma/Blood/Serum", "223", |
237 | 4x |
"CLSTD", "Last Nonzero Conc Norm by Dose", "CLSTD", "Plasma/Blood/Serum", "224", |
238 | 4x |
"CLSTS", "Last Nonzero Conc Norm by SA", "CLSTS", "Plasma/Blood/Serum", "225", |
239 | 4x |
"CLSTW", "Last Nonzero Conc Norm by WT", "CLSTW", "Plasma/Blood/Serum", "226", |
240 | 4x |
"CLTAU", "Total CL for Dose Int", "CLTAU", "Plasma/Blood/Serum", "227", |
241 | 4x |
"CLTAUB", "Total CL for Dose Int Norm by BMI", "CLTAUB", "Plasma/Blood/Serum", "228", |
242 | 4x |
"CLTAUD", "Total CL for Dose Int Norm by Dose", "CLTAUD", "Plasma/Blood/Serum", "229", |
243 | 4x |
"CLTAUS", "Total CL for Dose Int Norm by SA", "CLTAUS", "Plasma/Blood/Serum", "230", |
244 | 4x |
"CLTAUW", "Total CL for Dose Int Norm by WT", "CLTAUW", "Plasma/Blood/Serum", "231", |
245 | 4x |
"CMAXB", "Max Conc Norm by BMI", "CMAX_B", "Plasma/Blood/Serum", "232", |
246 | 4x |
"CMAXLN", "Max Conc LN Transformed", "CMAXLN", "Plasma/Blood/Serum", "233", |
247 | 4x |
"CMAXS", "Max Conc Norm by SA", "CMAXS", "Plasma/Blood/Serum", "234", |
248 | 4x |
"CMAXUB", "Max Conc, Unbound Drug", "CMAXUB", "Plasma/Blood/Serum", "235", |
249 | 4x |
"CMAXW", "Max Conc Norm by WT", "CMAXW", "Plasma/Blood/Serum", "236", |
250 | 4x |
"CMINB", "Min Conc Norm by BMI", "CMINB", "Plasma/Blood/Serum", "237", |
251 | 4x |
"CMIND", "Min Conc Norm by Dose", "CMIND", "Plasma/Blood/Serum", "238", |
252 | 4x |
"CMINS", "Min Conc Norm by SA", "CMINS", "Plasma/Blood/Serum", "239", |
253 | 4x |
"CMINW", "Min Conc Norm by WT", "CMINW", "Plasma/Blood/Serum", "240", |
254 | 4x |
"CONC", "Concentration", "CONC", "Plasma/Blood/Serum", "241", |
255 | 4x |
"CONCB", "Conc by BMI", "CONCB", "Plasma/Blood/Serum", "242", |
256 | 4x |
"CONCD", "Conc by Dose", "CONCD", "Plasma/Blood/Serum", "243", |
257 | 4x |
"CONCS", "Conc by SA", "CONCS", "Plasma/Blood/Serum", "244", |
258 | 4x |
"CONCW", "Conc by WT", "CONCW", "Plasma/Blood/Serum", "245", |
259 | 4x |
"CTROUGH", "Conc Trough", "CTROUGH", "Plasma/Blood/Serum", "246", |
260 | 4x |
"CTROUGHB", "Conc Trough by BMI", "CTROUGHB", "Plasma/Blood/Serum", "247", |
261 | 4x |
"CTROUGHD", "Conc Trough by Dose", "CTROUGHD", "Plasma/Blood/Serum", "248", |
262 | 4x |
"CTROUGHS", "Conc Trough by SA", "CTROUGHS", "Plasma/Blood/Serum", "249", |
263 | 4x |
"CTROUGHW", "Conc Trough by WT", "CTROUGHW", "Plasma/Blood/Serum", "250", |
264 | 4x |
"EFFHL", "Effective Half-Life", "EFFHL", "Plasma/Blood/Serum", "251", |
265 | 4x |
"ERINT", "Excret Rate from T1 to T2", "ERINT_T1_T2_UNIT", "Plasma/Blood/Serum", "252", |
266 | 4x |
"ERINTB", "Excret Rate from T1 to T2 Norm by BMI", "ERINTB_T1_T2_UNIT", "Plasma/Blood/Serum", "253", |
267 | 4x |
"ERINTD", "Excret Rate from T1 to T2 Norm by Dose", "ERINTD_T1_T2_UNIT", "Plasma/Blood/Serum", "254", |
268 | 4x |
"ERINTS", "Excret Rate from T1 to T2 Norm by SA", "ERINTS_T1_T2_UNIT", "Plasma/Blood/Serum", "255", |
269 | 4x |
"ERINTW", "Excret Rate from T1 to T2 Norm by WT", "ERINTW_T1_T2_UNIT", "Plasma/Blood/Serum", "256", |
270 | 4x |
"ERLSTB", "Last Meas Excretion Rate Norm by BMI", "ERLSTB", "Plasma/Blood/Serum", "257", |
271 | 4x |
"ERLSTD", "Last Meas Excretion Rate Norm by Dose", "ERLSTD", "Plasma/Blood/Serum", "258", |
272 | 4x |
"ERLSTS", "Last Meas Excretion Rate Norm by SA", "ERLSTS", "Plasma/Blood/Serum", "259", |
273 | 4x |
"ERLSTW", "Last Meas Excretion Rate Norm by WT", "ERLSTW", "Plasma/Blood/Serum", "260", |
274 | 4x |
"ERMAXB", "Max Excretion Rate Norm by BMI", "ERMAXB", "Plasma/Blood/Serum", "261", |
275 | 4x |
"ERMAXD", "Max Excretion Rate Norm by Dose", "ERMAXD", "Plasma/Blood/Serum", "262", |
276 | 4x |
"ERMAXS", "Max Excretion Rate Norm by SA", "ERMAXS", "Plasma/Blood/Serum", "263", |
277 | 4x |
"ERMAXW", "Max Excretion Rate Norm by WT", "ERMAXW", "Plasma/Blood/Serum", "264", |
278 | 4x |
"ERTLST", "Midpoint of Interval of Last Nonzero ER", "ERTLST", "Plasma/Blood/Serum", "265", |
279 | 4x |
"FABS", "Absolute Bioavailability", "FABS", "Plasma/Blood/Serum", "266", |
280 | 4x |
"FB", "Fraction Bound", "FB", "Plasma/Blood/Serum", "267", |
281 | 4x |
"FREL", "Relative Bioavailability", "FREL", "Plasma/Blood/Serum", "268", |
282 | 4x |
"FREXINT", "Fract Excr from T1 to T2", "FREXINT_T1_T2_UNIT", "Plasma/Blood/Serum", "269", |
283 | 4x |
"FU", "Fraction Unbound", "FU", "Plasma/Blood/Serum", "270", |
284 | 4x |
"HDCL", "Hemodialysis Clearance", "HDCL", "Plasma/Blood/Serum", "271", |
285 | 4x |
"HDER", "Hemodialysis Extraction Ratio", "HDER", "Plasma/Blood/Serum", "272", |
286 | 4x |
"HTMAX", "Half Tmax", "HTMAX", "Plasma/Blood/Serum", "273", |
287 | 4x |
"LAMZLTAU", "Lambda z Lower Limit TAU", "LAMZLTAU", "Plasma/Blood/Serum", "274", |
288 | 4x |
"LAMZNTAU", "Number of Points for Lambda z TAU", "LAMZNTAU", "Plasma/Blood/Serum", "275", |
289 | 4x |
"LAMZSPN", "Lambda z Span", "LAMZSPN", "Plasma/Blood/Serum", "276", |
290 | 4x |
"LAMZTAU", "Lambda z TAU", "LAMZTAU", "Plasma/Blood/Serum", "277", |
291 | 4x |
"LAMZUTAU", "Lambda z Upper Limit TAU", "LAMZUTAU", "Plasma/Blood/Serum", "278", |
292 | 4x |
"MAT", "Mean Absorption Time", "MAT", "Plasma/Blood/Serum", "279", |
293 | 4x |
"MRAUCIFO", "Metabolite Ratio for AUC Infinity Obs", "MRAUCIFO", "Plasma/Blood/Serum", "280", |
294 | 4x |
"MRAUCIFP", "Metabolite Ratio for AUC Infinity Pred", "MRAUCIFP", "Plasma/Blood/Serum", "281", |
295 | 4x |
"MRAUCINT", "Metabolite Ratio AUC from T1 to T2", "MRAUCINT_T1_T2_UNIT", "Plasma/Blood/Serum", "282", |
296 | 4x |
"MRAUCLST", "Metabolite Ratio AUC Last Nonzero Conc", "MRAUCLST", "Plasma/Blood/Serum", "283", |
297 | 4x |
"MRAUCTAU", "Metabolite Ratio for AUC Dosing Interval", "MRAUCTAU", "Plasma/Blood/Serum", "284", |
298 | 4x |
"MRCMAX", "Metabolite Ratio for Max Conc", "MRCMAX", "Plasma/Blood/Serum", "285", |
299 | 4x |
"MRTEVIFO", "MRT Extravasc Infinity Obs", "MRTEVIFO", "Plasma/Blood/Serum", "286", |
300 | 4x |
"MRTEVIFP", "MRT Extravasc Infinity Pred", "MRTEVIFP", "Plasma/Blood/Serum", "287", |
301 | 4x |
"MRTEVLST", "MRT Extravasc to Last Nonzero Conc", "MRTEVLST", "Plasma/Blood/Serum", "288", |
302 | 4x |
"MRTIVIFO", "MRT Intravasc Infinity Obs", "MRTIVIFO", "Plasma/Blood/Serum", "289", |
303 | 4x |
"MRTIVIFP", "MRT Intravasc Infinity Pred", "MRTIVIFP", "Plasma/Blood/Serum", "290", |
304 | 4x |
"MRTIVLST", "MRT Intravasc to Last Nonzero Conc", "MRTIVLST", "Plasma/Blood/Serum", "291", |
305 | 4x |
"NRENALCL", "Nonrenal CL", "NRENALCL", "Urine", "292", |
306 | 4x |
"NRENLCLB", "Nonrenal CL Norm by BMI", "NRENLCLB", "Urine", "293", |
307 | 4x |
"NRENLCLD", "Nonrenal CL Norm by Dose", "NRENLCLD", "Urine", "294", |
308 | 4x |
"NRENLCLS", "Nonrenal CL Norm by SA", "NRENLCLS", "Urine", "295", |
309 | 4x |
"NRENLCLW", "Nonrenal CL Norm by WT", "NRENLCLW", "Urine", "296", |
310 | 4x |
"PTROUGHR", "Peak Trough Ratio", "PTROUGHR", "Plasma/Blood/Serum", "297", |
311 | 4x |
"RAAUC", "Ratio AUC", "RAAUC", "Plasma/Blood/Serum", "298", |
312 | 4x |
"RAAUCIFO", "Ratio AUC Infinity Obs", "RAAUCIFO", "Plasma/Blood/Serum", "299", |
313 | 4x |
"RAAUCIFP", "Ratio AUC Infinity Pred", "RAAUCIFP", "Plasma/Blood/Serum", "300", |
314 | 4x |
"RACMAX", "Ratio CMAX", "RACMAX", "Plasma/Blood/Serum", "301", |
315 | 4x |
"RAMAXMIN", "Ratio of CMAX to CMIN", "RAMAXMIN", "Plasma/Blood/Serum", "302", |
316 | 4x |
"RCAMIFO", "Amt Rec Infinity Obs", "RCAMIFO", "Plasma/Blood/Serum", "303", |
317 | 4x |
"RCAMIFOB", "Amt Rec Infinity Obs Norm by BMI", "RCAMIFOB", "Plasma/Blood/Serum", "304", |
318 | 4x |
"RCAMIFOS", "Amt Rec Infinity Obs Norm by SA", "RCAMIFOS", "Plasma/Blood/Serum", "305", |
319 | 4x |
"RCAMIFOW", "Amt Rec Infinity Obs Norm by WT", "RCAMIFOW", "Plasma/Blood/Serum", "306", |
320 | 4x |
"RCAMIFP", "Amt Rec Infinity Pred", "RCAMIFP", "Plasma/Blood/Serum", "307", |
321 | 4x |
"RCAMIFPB", "Amt Rec Infinity Pred Norm by BMI", "RCAMIFPB", "Plasma/Blood/Serum", "308", |
322 | 4x |
"RCAMIFPS", "Amt Rec Infinity Pred Norm by SA", "RCAMIFPS", "Plasma/Blood/Serum", "309", |
323 | 4x |
"RCAMIFPW", "Amt Rec Infinity Pred Norm by WT", "RCAMIFPW", "Plasma/Blood/Serum", "310", |
324 | 4x |
"RCAMINTB", "Amt Rec from T1 to T2 Norm by BMI", "RCAMINTB_T1_T2_UNIT", "Plasma/Blood/Serum", "311", |
325 | 4x |
"RCAMINTS", "Amt Rec from T1 to T2 Norm by SA", "RCAMINTS_T1_T2_UNIT", "Plasma/Blood/Serum", "312", |
326 | 4x |
"RCAMINTW", "Amt Rec from T1 to T2 Norm by WT", "RCAMINTW_T1_T2_UNIT", "Plasma/Blood/Serum", "313", |
327 | 4x |
"RCAMTAU", "Amt Rec Over Dosing Interval", "RCAMTAU", "Plasma/Blood/Serum", "314", |
328 | 4x |
"RCAMTAUB", "Amt Rec Over Dosing Interval Norm by BMI", "RCAMTAUB", "Plasma/Blood/Serum", "315", |
329 | 4x |
"RCAMTAUS", "Amt Rec Over Dosing Interval Norm by SA", "RCAMTAUS", "Plasma/Blood/Serum", "316", |
330 | 4x |
"RCAMTAUW", "Amt Rec Over Dosing Interval Norm by WT", "RCAMTAUW", "Plasma/Blood/Serum", "317", |
331 | 4x |
"RCPCIFO", "Pct Rec Infinity Obs", "RCPCIFO", "Plasma/Blood/Serum", "318", |
332 | 4x |
"RCPCIFOB", "Pct Rec Infinity Obs Norm by BMI", "RCPCIFOB", "Plasma/Blood/Serum", "319", |
333 | 4x |
"RCPCIFOS", "Pct Rec Infinity Obs Norm by SA", "RCPCIFOS", "Plasma/Blood/Serum", "320", |
334 | 4x |
"RCPCIFOW", "Pct Rec Infinity Obs Norm by WT", "RCPCIFOW", "Plasma/Blood/Serum", "321", |
335 | 4x |
"RCPCIFP", "Pct Rec Infinity Pred", "RCPCIFP", "Plasma/Blood/Serum", "322", |
336 | 4x |
"RCPCIFPB", "Pct Rec Infinity Pred Norm by BMI", "RCPCIFPB", "Plasma/Blood/Serum", "323", |
337 | 4x |
"RCPCIFPS", "Pct Rec Infinity Pred Norm by SA", "RCPCIFPS", "Plasma/Blood/Serum", "324", |
338 | 4x |
"RCPCIFPW", "Pct Rec Infinity Pred Norm by WT", "RCPCIFPW", "Plasma/Blood/Serum", "325", |
339 | 4x |
"RCPCINTB", "Pct Rec from T1 to T2 Norm by BMI", "RCPCINTB_T1_T2_UNIT", "Plasma/Blood/Serum", "326", |
340 | 4x |
"RCPCINTS", "Pct Rec from T1 to T2 Norm by SA", "RCPCINTS_T1_T2_UNIT", "Plasma/Blood/Serum", "327", |
341 | 4x |
"RCPCINTW", "Pct Rec from T1 to T2 Norm by WT", "RCPCINTW_T1_T2_UNIT", "Plasma/Blood/Serum", "328", |
342 | 4x |
"RCPCLST", "Pct Rec to Last Nonzero Conc", "RCPCLST", "Plasma/Blood/Serum", "329", |
343 | 4x |
"RCPCTAU", "Pct Rec Over Dosing Interval", "RCPCTAU", "Plasma/Blood/Serum", "330", |
344 | 4x |
"RCPCTAUB", "Pct Rec Over Dosing Interval Norm by BMI", "RCPCTAUB", "Plasma/Blood/Serum", "331", |
345 | 4x |
"RCPCTAUS", "Pct Rec Over Dosing Interval Norm by SA", "RCPCTAUS", "Plasma/Blood/Serum", "332", |
346 | 4x |
"RCPCTAUW", "Pct Rec Over Dosing Interval Norm by WT", "RCPCTAUW", "Plasma/Blood/Serum", "333", |
347 | 4x |
"RENALCLB", "Renal CL Norm by BMI", "RENALCLB", "Urine", "334", |
348 | 4x |
"RENALCLD", "Renal CL Norm by Dose", "RENALCLD", "Urine", "335", |
349 | 4x |
"RENALCLS", "Renal CL Norm by SA", "RENALCLS", "Urine", "336", |
350 | 4x |
"RENALCLW", "Renal CL Norm by WT", "RENALCLW", "Urine", "337", |
351 | 4x |
"RENCLTAU", "Renal CL for Dose Int", "RENCLTAU", "Urine", "338", |
352 | 4x |
"RNCLINT", "Renal CL from T1 to T2", "RNCLINT_T1_T2_UNIT", "Urine", "339", |
353 | 4x |
"RNCLINTB", "Renal CL from T1 to T2 Norm by BMI", "RNCLINTB_T1_T2_UNIT", "Urine", "340", |
354 | 4x |
"RNCLINTD", "Renal CL from T1 to T2 Norm by Dose", "RNCLINTD_T1_T2_UNIT", "Urine", "341", |
355 | 4x |
"RNCLINTS", "Renal CL from T1 to T2 Norm by SA", "RNCLINTS_T1_T2_UNIT", "Urine", "342", |
356 | 4x |
"RNCLINTW", "Renal CL from T1 to T2 Norm by WT", "RNCLINTW_T1_T2_UNIT", "Urine", "343", |
357 | 4x |
"RNCLTAUB", "Renal CL for Dose Int Norm by BMI", "RNCLTAUB", "Urine", "344", |
358 | 4x |
"RNCLTAUD", "Renal CL for Dose Int Norm by Dose", "RNCLTAUD", "Urine", "345", |
359 | 4x |
"RNCLTAUS", "Renal CL for Dose Int Norm by SA", "RNCLTAUS", "Urine", "346", |
360 | 4x |
"RNCLTAUW", "Renal CL for Dose Int Norm by WT", "RNCLTAUW", "Urine", "347", |
361 | 4x |
"RNCLUB", "Renal CL for Unbound Drug", "RNCLUB", "Urine", "348", |
362 | 4x |
"SRAUC", "Stationarity Ratio AUC", "SRAUC", "Plasma/Blood/Serum", "349", |
363 | 4x |
"SWING", "Swing", "SWING", "Plasma/Blood/Serum", "350", |
364 | 4x |
"TAUHL", "Half-Life TAU", "TAUHL", "Plasma/Blood/Serum", "351", |
365 | 4x |
"TBBL", "Time Below Baseline", "Time_Below_B", "Plasma/Blood/Serum", "352", |
366 | 4x |
"TROUGHPR", "Trough Peak Ratio", "TROUGHPR", "Plasma/Blood/Serum", "353", |
367 | 4x |
"V0", "Vol Dist Initial", "V0", "Plasma/Blood/Serum", "354", |
368 | 4x |
"V0B", "Vol Dist Initial Norm by BMI", "V0B", "Plasma/Blood/Serum", "355", |
369 | 4x |
"V0D", "Vol Dist Initial Norm by Dose", "V0D", "Plasma/Blood/Serum", "356", |
370 | 4x |
"V0S", "Vol Dist Initial Norm by SA", "V0S", "Plasma/Blood/Serum", "357", |
371 | 4x |
"V0W", "Vol Dist Initial Norm by WT", "V0W", "Plasma/Blood/Serum", "358", |
372 | 4x |
"VSSOB", "Vol Dist Steady State Obs Norm by BMI", "VSSOB", "Plasma/Blood/Serum", "359", |
373 | 4x |
"VSSOBD", "Vol Dist Steady State Obs by B", "VSSOBD", "Plasma/Blood/Serum", "360", |
374 | 4x |
"VSSOD", "Vol Dist Steady State Obs Norm by Dose", "VSSOD", "Plasma/Blood/Serum", "361", |
375 | 4x |
"VSSOF", "Vol Dist Steady State Obs by F", "VSSOF", "Plasma/Blood/Serum", "362", |
376 | 4x |
"VSSOS", "Vol Dist Steady State Obs Norm by SA", "VSSOS", "Plasma/Blood/Serum", "363", |
377 | 4x |
"VSSOUB", "Vol Dist Steady State Obs by UB", "VSSOUB", "Plasma/Blood/Serum", "364", |
378 | 4x |
"VSSOW", "Vol Dist Steady State Obs Norm by WT", "VSSOW", "Plasma/Blood/Serum", "365", |
379 | 4x |
"VSSPB", "Vol Dist Steady State Pred Norm by BMI", "VSSPB", "Plasma/Blood/Serum", "366", |
380 | 4x |
"VSSPBD", "Vol Dist Steady State Pred by B", "VSSPBD", "Plasma/Blood/Serum", "367", |
381 | 4x |
"VSSPD", "Vol Dist Steady State Pred Norm by Dose", "VSSPD", "Plasma/Blood/Serum", "368", |
382 | 4x |
"VSSPF", "Vol Dist Steady State Pred by F", "VSSPF", "Plasma/Blood/Serum", "369", |
383 | 4x |
"VSSPS", "Vol Dist Steady State Pred Norm by SA", "VSSPS", "Plasma/Blood/Serum", "370", |
384 | 4x |
"VSSPUB", "Vol Dist Steady State Pred by UB", "VSSPUB", "Plasma/Blood/Serum", "371", |
385 | 4x |
"VSSPW", "Vol Dist Steady State Pred Norm by WT", "VSSPW", "Plasma/Blood/Serum", "372", |
386 | 4x |
"VZ", "Vol Z", "Vz", "Plasma/Blood/Serum", "373", |
387 | 4x |
"VZF", "Vol Z by F", "Vz_F", "Plasma/Blood/Serum", "374", |
388 | 4x |
"VZFOB", "Vz Obs by F Norm by BMI", "VZFOB", "Plasma/Blood/Serum", "375", |
389 | 4x |
"VZFOD", "Vz Obs by F Norm by Dose", "VZFOD", "Plasma/Blood/Serum", "376", |
390 | 4x |
"VZFOS", "Vz Obs by F Norm by SA", "VZFOS", "Plasma/Blood/Serum", "377", |
391 | 4x |
"VZFOUB", "Vz Obs by F for UB", "VZFOUB", "Plasma/Blood/Serum", "378", |
392 | 4x |
"VZFOW", "Vz Obs by F Norm by WT", "VZFOW", "Plasma/Blood/Serum", "379", |
393 | 4x |
"VZFPB", "Vz Pred by F Norm by BMI", "VZFPB", "Plasma/Blood/Serum", "380", |
394 | 4x |
"VZFPD", "Vz Pred by F Norm by Dose", "VZFPD", "Plasma/Blood/Serum", "381", |
395 | 4x |
"VZFPS", "Vz Pred by F Norm by SA", "VZFPS", "Plasma/Blood/Serum", "382", |
396 | 4x |
"VZFPUB", "Vz Pred by F for UB", "VZFPUB", "Plasma/Blood/Serum", "383", |
397 | 4x |
"VZFPW", "Vz Pred by F Norm by WT", "VZFPW", "Plasma/Blood/Serum", "384", |
398 | 4x |
"VZFTAU", "Vz for Dose Int by F", "VZFTAU", "Plasma/Blood/Serum", "385", |
399 | 4x |
"VZFTAUB", "Vz for Dose Int by F Norm by BMI", "VZFTAUB", "Plasma/Blood/Serum", "386", |
400 | 4x |
"VZFTAUD", "Vz for Dose Int by F Norm by Dose", "VZFTAUD", "Plasma/Blood/Serum", "387", |
401 | 4x |
"VZFTAUS", "Vz for Dose Int by F Norm by SA", "VZFTAUS", "Plasma/Blood/Serum", "388", |
402 | 4x |
"VZFTAUW", "Vz for Dose Int by F Norm by WT", "VZFTAUW", "Plasma/Blood/Serum", "389", |
403 | 4x |
"VZOB", "Vz Obs Norm by BMI", "VZOB", "Plasma/Blood/Serum", "390", |
404 | 4x |
"VZOD", "Vz Obs Norm by Dose", "VZOD", "Plasma/Blood/Serum", "391", |
405 | 4x |
"VZOS", "Vz Obs Norm by SA", "VZOS", "Plasma/Blood/Serum", "392", |
406 | 4x |
"VZOUB", "Vz Obs for UB", "VZOUB", "Plasma/Blood/Serum", "393", |
407 | 4x |
"VZOW", "Vz Obs Norm by WT", "VZOW", "Plasma/Blood/Serum", "394", |
408 | 4x |
"VZPB", "Vz Pred Norm by BMI", "VZPB", "Plasma/Blood/Serum", "395", |
409 | 4x |
"VZPD", "Vz Pred Norm by Dose", "VZPD", "Plasma/Blood/Serum", "396", |
410 | 4x |
"VZPS", "Vz Pred Norm by SA", "VZPS", "Plasma/Blood/Serum", "397", |
411 | 4x |
"VZPUB", "Vz Pred for UB", "VZPUB", "Plasma/Blood/Serum", "398" |
412 |
), |
|
413 | 4x |
ncol = 5, |
414 | 4x |
byrow = TRUE |
415 |
)) |
|
416 | 4x |
colnames(pk_dataset) <- c("PARAMCD", "PARAM", "TLG_DISPLAY", "MATRIX", "TLG_ORDER") |
417 | 4x |
pk_dataset |
418 |
} |
1 |
#' Control function for incidence rate |
|
2 |
#' |
|
3 |
#' @description `r lifecycle::badge("stable")` |
|
4 |
#' |
|
5 |
#' This is an auxiliary function for controlling arguments for the incidence rate, used |
|
6 |
#' internally to specify details in `s_incidence_rate()`. |
|
7 |
#' |
|
8 |
#' @inheritParams argument_convention |
|
9 |
#' @param conf_type (`string`)\cr `normal` (default), `normal_log`, `exact`, or `byar` |
|
10 |
#' for confidence interval type. |
|
11 |
#' @param input_time_unit (`string`)\cr `day`, `week`, `month`, or `year` (default) |
|
12 |
#' indicating time unit for data input. |
|
13 |
#' @param num_pt_year (`numeric`)\cr number of patient-years to use when calculating adverse event rates. |
|
14 |
#' @param time_unit_input `r lifecycle::badge("deprecated")` Please use the `input_time_unit` argument instead. |
|
15 |
#' @param time_unit_output `r lifecycle::badge("deprecated")` Please use the `num_pt_year` argument instead. |
|
16 |
#' |
|
17 |
#' @return A list of components with the same names as the arguments. |
|
18 |
#' |
|
19 |
#' @seealso [incidence_rate] |
|
20 |
#' |
|
21 |
#' @examples |
|
22 |
#' control_incidence_rate(0.9, "exact", "month", 100) |
|
23 |
#' |
|
24 |
#' @export |
|
25 |
control_incidence_rate <- function(conf_level = 0.95, |
|
26 |
conf_type = c("normal", "normal_log", "exact", "byar"), |
|
27 |
input_time_unit = c("year", "day", "week", "month"), |
|
28 |
num_pt_year = 100, |
|
29 |
time_unit_input = lifecycle::deprecated(), |
|
30 |
time_unit_output = lifecycle::deprecated()) { |
|
31 | 8x |
if (lifecycle::is_present(time_unit_input)) { |
32 | ! |
lifecycle::deprecate_warn( |
33 | ! |
"0.8.3", "control_incidence_rate(time_unit_input)", "control_incidence_rate(input_time_unit)" |
34 |
) |
|
35 | ! |
input_time_unit <- time_unit_input |
36 |
} |
|
37 | 8x |
if (lifecycle::is_present(time_unit_output)) { |
38 | ! |
lifecycle::deprecate_warn( |
39 | ! |
"0.8.3", "control_incidence_rate(time_unit_output)", "control_incidence_rate(num_pt_year)" |
40 |
) |
|
41 | ! |
num_pt_year <- time_unit_output |
42 |
} |
|
43 | ||
44 | 8x |
conf_type <- match.arg(conf_type) |
45 | 7x |
input_time_unit <- match.arg(input_time_unit) |
46 | 6x |
checkmate::assert_number(num_pt_year) |
47 | 5x |
assert_proportion_value(conf_level) |
48 | ||
49 | 4x |
list( |
50 | 4x |
conf_level = conf_level, |
51 | 4x |
conf_type = conf_type, |
52 | 4x |
input_time_unit = input_time_unit, |
53 | 4x |
num_pt_year = num_pt_year |
54 |
) |
|
55 |
} |