-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_cosinor.R
617 lines (559 loc) · 18.1 KB
/
test_cosinor.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
#' Test for differences in a cosinor model between components.
#'
#' Given a time variable and optional covariates, generate inference a cosinor
#' fit. For the covariate named (or vector of covariates), this function
#' performs a Wald test comparing the group with covariates equal to 1 to the
#' group with covariates equal to 0. This may not be the desired result for
#' continuous covariates.
#'
#'
#' @param x An \code{cglmm} object.
#' @param x_str A \code{character}. The name of the grouping variable within
#' which differences in the selected cosinor characteristic (amplitude or
#' acrophase) will be tested. If there is no grouping variable in the model,
#' then this can be left as NULL (default).
#' @param param A \code{character}. Either \code{"amp"} or \code{"acr"} for
#' testing differences in amplitude or acrophase, respectively.
#' @param comparison_A An \code{integer}. Refers to the component number that is
#' to act as the reference group.
#' for the comparison.
#' @param comparison_B An \code{integer}. Refers to the component number that is
#' to act as the comparator group
#' @param level_index An \code{integer}. If
#' \code{comparison_type = "components"}, \code{level_index} indicates which
#' level of the grouping variable is being used for the comparison between
#' components.
#' @param ci_level The level for calculated confidence intervals. Defaults to
#' \code{0.95}.
#'
#' @return Returns a \code{test_cosinor} object.
#' @export
#'
#' @examples
#' data_2_component <- simulate_cosinor(
#' n = 10000,
#' mesor = 5,
#' amp = c(2, 5),
#' acro = c(0, pi),
#' beta.mesor = 4,
#' beta.amp = c(3, 4),
#' beta.acro = c(0, pi / 2),
#' family = "gaussian",
#' n_components = 2,
#' period = c(10, 12),
#' beta.group = TRUE
#' )
#' mod_2_component <- cglmm(
#' Y ~ group + amp_acro(times,
#' n_components = 2, group = "group",
#' period = c(10, 12)
#' ),
#' data = data_2_component
#' )
#' test_cosinor_components(mod_2_component, param = "amp", x_str = "group")
test_cosinor_components <- function(x,
x_str = NULL,
param = "amp",
comparison_A = 1,
comparison_B = 2,
level_index = 0,
ci_level = 0.95) {
# Validating the inputs
if (param == "amp" | param == "acr") {
} else {
# Display an error message if the parameter is invalid
stop("Invalid parameter. Expected 'amp' or 'acro'.")
}
validate_ci_level(ci_level)
assertthat::assert_that(
inherits(x, "cglmm"),
msg = "'x' must be of class 'cglmm'"
)
if (!is.null(x_str)) {
stopifnot(is.character(x_str))
}
# assertthat::assert_that(
# length(grep(x_str, names(x$coefficients))) > 0,
# msg = "x_str must be the name of a group in object"
# )
assertthat::assert_that(
comparison_A %in% 1:x$n_components & comparison_B %in% 1:x$n_components,
msg = paste(
"'comparison_A' and 'comparison_B' must be numbers",
"corresponding to a component in the model"
)
)
if (!is.null(x_str)) {
assertthat::assert_that(
level_index %in% x$group_stats[[x$group_original[comparison_A]]] &
level_index %in% x$group_stats[[x$group_original[comparison_B]]],
msg = paste(
"'level_index' must be supplied and it must be a number",
"corresponding to a level in the model"
)
)
}
# passing these inputs into the internal function
test_obj <- .test_cosinor(
x = x,
x_str = x_str,
param = param,
comparison_A = comparison_A,
comparison_B = comparison_B,
level_index = level_index,
ci_level = ci_level,
comparison_type = "components"
)
test_obj
}
#' Test for differences in a cosinor model between levels of the grouping
#' variable.
#'
#' Given a time variable and optional covariates, generate inference a cosinor
#' fit. For the covariate named (or vector of covariates), this function
#' performs a Wald test comparing the group with covariates equal to 1 to the
#' group with covariates equal to 0. This may not be the desired result for
#' continuous covariates.
#'
#' @param x An \code{cglmm} object.
#' @param x_str A \code{character}. The name of the grouping variable within
#' which differences in the selected cosinor characteristic (amplitude or
#' acrophase) will be tested.
#' @param param A \code{character}. Either \code{"amp"} or \code{"acr"} for
#' testing differences in amplitude or acrophase, respectively.
#' @param comparison_A An \code{integer, or string}. Refers to the first level
#' within the grouping variable \code{x_str} that is to act as the reference
#' group in the comparison. Ensure that it corresponds to the name of the level
#' in the original dataset.
#' @param comparison_B An \code{integer, or string}. Refers to the second level
#' within the grouping variable \code{x_str} that is to act as the comparator
#' group in the comparison. Ensure that it corresponds to the name of the level
#' in the original dataset.
#' @param component_index An \code{integer}. If
#' \code{comparison_type = "levels"}, \code{component_index} indicates which
#' component is being compared between the levels of the grouping variable.
#' @param ci_level The level for calculated confidence intervals. Defaults to
#' \code{0.95}.
#'
#'
#' @return Returns a \code{test_cosinor} object.
#' @export
#'
#' @examples
#' data_2_component <- simulate_cosinor(
#' n = 10000,
#' mesor = 5,
#' amp = c(2, 5),
#' acro = c(0, pi),
#' beta.mesor = 4,
#' beta.amp = c(3, 4),
#' beta.acro = c(0, pi / 2),
#' family = "gaussian",
#' n_components = 2,
#' period = c(10, 12),
#' beta.group = TRUE
#' )
#' mod_2_component <- cglmm(
#' Y ~ group + amp_acro(times,
#' n_components = 2, group = "group",
#' period = c(10, 12)
#' ),
#' data = data_2_component
#' )
#' test_cosinor_levels(mod_2_component, param = "amp", x_str = "group")
test_cosinor_levels <- function(x,
x_str,
param = "amp",
comparison_A,
comparison_B,
component_index = 1,
ci_level = 0.95) {
# Validating the inputs
if (param == "amp" | param == "acr") {
} else {
# Display an error message if the parameter is invalid
stop("Invalid parameter. Expected 'amp' or 'acr'.")
}
validate_ci_level(ci_level)
assertthat::assert_that(
inherits(x, "cglmm"),
msg = "'x' must be of class 'cglmm'"
)
stopifnot(is.character(x_str))
assertthat::assert_that(
length(grep(x_str, names(x$coefficients))) > 0,
msg = "x_str must be the name of a group in object"
)
# If there are no levels supplied, the first two levels will be compared
if (missing(comparison_A) & missing(comparison_B)) {
comparison_A <- x$group_stats[[x_str]][1]
comparison_B <- x$group_stats[[x_str]][2]
}
assertthat::assert_that(
comparison_A %in% x$group_stats[[x_str]],
msg = "'comparison_A' must correspond to a level within the group
specified by 'x_str'"
)
assertthat::assert_that(
comparison_B %in% x$group_stats[[x_str]],
msg = paste(
"'comparison_B' must correspond to a level within the",
"group specified by 'x_str'"
)
)
assertthat::assert_that(
component_index %in% 1:x$n_components,
msg = paste(
"'component_index' must be supplied and it must be a",
"number corresponding to a component in the model"
)
)
# passing these inputs into the internal function
test_obj <- .test_cosinor(
x = x,
x_str = x_str,
param = param,
comparison_A = comparison_A,
comparison_B = comparison_B,
component_index = component_index,
ci_level = ci_level,
comparison_type = "levels"
)
test_obj
}
#' Test for differences in a cosinor model. This function has been replaced
#' with a more user-friendly and intuitive way of specifying comparisons:
#' \code{test_cosinor_components} and \code{test_cosinor_levels}.
#' These external functions use this internal function.
#'
#' Given a time variable and optional covariates, generate inference a cosinor
#' fit. For the covariate named (or vector of covariates), this function
#' performs a Wald test comparing the group with covariates equal to 1 to the
#' group with covariates equal to 0. This may not be the desired result for
#' continuous covariates.
#'
#'
#' @param x An \code{cglmm} object.
#' @param x_str A \code{character}. The name of the grouping variable within
#' which differences in the selected cosinor characteristic (amplitude or
#' acrophase) will be tested.
#' @param param A \code{character}. Either \code{"amp"} or \code{"acr"} for
#' testing differences in amplitude or acrophase, respectively.
#' @param comparison_A An \code{integer}. Refers to the level (within the
#' grouping variable) or component number that is to act as the reference group
#' for the comparison.
#' @param comparison_B An \code{integer}. Refers to the level (within the
#' grouping variable) or component number that is to act as the comparator group
#' for the comparison.
#' @param comparison_type A \code{character}. Indicates whether the comparison
#' to be performed is to be between levels of a grouping variable
#' (\code{"levels"}) or indices of components in a multiple-component cosinor
#' model (\code{"components"}).
#' @param component_index An \code{integer}. If
#' \code{comparison_type = "levels"}, \code{component_index} indicates which
#' component is being compared between the levels of the grouping variable.
#' @param level_index An \code{integer}. If
#' \code{comparison_type = "components"}, \code{level_index} indicates which
#' level of the grouping variable is being used for the comparison between
#' components.
#' @param ci_level The level for calculated confidence intervals. Defaults to
#' \code{0.95}.
#'
#' @return Returns a \code{test_cosinor} object.
#' @examples
#' mod_grouped <- cglmm(vit_d ~ X + amp_acro(time,
#' group = "X",
#' n_components = 1,
#' period = 12
#' ), data = vitamind)
#'
#' test_cosinor(mod_grouped, "X", "amp")
#'
#' data_2_component <- simulate_cosinor(
#' n = 10000,
#' mesor = 5,
#' amp = c(2, 5),
#' acro = c(0, pi),
#' beta.mesor = 4,
#' beta.amp = c(3, 4),
#' beta.acro = c(0, pi / 2),
#' family = "gaussian",
#' n_components = 2,
#' period = c(10, 12)
#' )
#'
#' mod_2_component <- cglmm(
#' Y ~ group + amp_acro(times,
#' n_components = 2, group = "group",
#' period = c(10, 12)
#' ),
#' data = data_2_component
#' )
#'
#' test_cosinor(mod_2_component, param = "amp", comparison_type = "components")
#'
#' @noRd
.test_cosinor <- function(x,
x_str,
param,
comparison_A,
comparison_B,
comparison_type,
component_index,
level_index,
ci_level) {
# TODO handle the text labels for the factor variable used for grouping - i.e
# using data made with : sim_data %>% mutate(group = ifelse(group == 1,
# "control", "treatment"))
summary.fit <- summary(x)
if (is.null(x_str)) {
x_str_length <- 1
} else {
x_str_length <- length(x_str)
}
index <- matrix(0, ncol = length(x$coefficients), nrow = x_str_length)
colnames(index) <- names(x$coefficients)
if (comparison_type == "components") {
if (is.null(x_str)) {
index[1, paste0(param, comparison_A)] <- -1
index[1, paste0(param, comparison_B)] <- 1
} else {
for (i in seq_along(x_str)) {
index[i, paste0(x_str[i], level_index, ":", param, comparison_A)] <- -1
index[i, paste0(x_str[i], level_index, ":", param, comparison_B)] <- 1
}
}
}
if (comparison_type == "levels") {
if (x$n_components == 1) {
component_index <- ""
}
for (i in seq_along(x_str)) {
index[i, paste0(
x_str[i],
comparison_A, ":", param, component_index
)] <- -1
index[i, paste0(
x_str[i],
comparison_B, ":", param, component_index
)] <- 1
}
}
diff.est <- index %*% x$coefficients
diff.var <- index[
, grep("(amp|acr)", names(x$coefficients)),
drop = FALSE
] %*%
summary.fit$transformed.covariance %*%
t(index[, grep("(amp|acr)", names(x$coefficients)), drop = FALSE])
glob.chi <- (diff.est %*% solve(diff.var) %*% t(diff.est))[1, 1]
ind.Z <- diff.est / sqrt(diag(diff.var))
# get the quantile corresponding to ci_level
zt <- stats::qnorm((1 - ci_level) / 2, lower.tail = F)
interval <- cbind(
diff.est,
diff.est - zt * sqrt(diag(diff.var)),
diff.est + zt * sqrt(diag(diff.var))
)
global.test <- structure(list(
statistic = glob.chi,
df = dim(diff.var)[1],
conf.int = NULL,
p.value = stats::pchisq(glob.chi, df = dim(diff.var)[1], lower.tail = FALSE)
), class = "cglmmSubTest")
ind.test <- structure(list(
statistic = ind.Z[, ],
df = NULL,
conf.int = interval,
ci_level = ci_level,
p.value = 2 * stats::pnorm(-abs(ind.Z))[, ],
names = x_str
), class = "cglmmSubTest")
if (comparison_type == "components") {
test_details <- list(
x = x,
x_str = x_str,
param = param,
comparison_A = comparison_A,
comparison_B = comparison_B,
comparison_type = comparison_type,
level_index = level_index,
ci_level = ci_level
)
}
if (comparison_type == "levels") {
test_details <- list(
x = x,
x_str = x_str,
param = param,
comparison_A = comparison_A,
comparison_B = comparison_B,
comparison_type = comparison_type,
component_index = component_index,
ci_level = ci_level
)
}
structure(
list(
global.test = global.test,
ind.test = ind.test,
test_details = test_details
),
class = "cglmmTest"
)
}
#' Print results of test of cosinor model
#'
#' @param x A \code{test_cosinor} object.
#' @param ... Arguments passed to \code{print}
#'
#' @return \code{print(x)} returns \code{x} invisibly.
#' @examples
#' data_2_component <- simulate_cosinor(
#' n = 10000,
#' mesor = 5,
#' amp = c(2, 5),
#' acro = c(0, pi),
#' beta.mesor = 4,
#' beta.amp = c(3, 4),
#' beta.acro = c(0, pi / 2),
#' family = "gaussian",
#' n_components = 2,
#' period = c(10, 12),
#' beta.group = TRUE
#' )
#' mod_2_component <- cglmm(
#' Y ~ group + amp_acro(times,
#' n_components = 2, group = "group",
#' period = c(10, 12)
#' ),
#' data = data_2_component
#' )
#' test_cosinor_levels(
#' mod_2_component,
#' param = "amp",
#' x_str = "group"
#' )
#' @export
print.cglmmTest <- function(x, ...) {
cat("Test Details: \n")
.print_details(x$test_details)
cat("\n\n\nGlobal test: \n")
print(x$global.test, ...)
cat("\n\n\nIndividual tests:\n")
print(x$ind.test, ...)
invisible(x)
}
#' Print test of model
#'
#' @param x A \code{sub_test_cosinor} object.
#' @param ... Additional, ignored arguments.
#'
#' @return \code{print(x)} returns \code{x} invisibly.
#'
#' @examples
#' data_2_component <- simulate_cosinor(
#' n = 10000,
#' mesor = 5,
#' amp = c(2, 5),
#' acro = c(0, pi),
#' beta.mesor = 4,
#' beta.amp = c(3, 4),
#' beta.acro = c(0, pi / 2),
#' family = "gaussian",
#' n_components = 2,
#' period = c(10, 12),
#' beta.group = TRUE
#' )
#' mod_2_component <- cglmm(
#' Y ~ group + amp_acro(times,
#' n_components = 2, group = "group",
#' period = c(10, 12)
#' ),
#' data = data_2_component
#' )
#' test_output <- test_cosinor_levels(
#' mod_2_component,
#' param = "amp",
#' x_str = "group"
#' )
#' print(test_output$global.test)
#' @export
print.cglmmSubTest <- function(x, ...) {
if (length(x$statistic) == 1) {
cat("Statistic: \n")
cat(round(x$statistic, 2))
cat("\n\nP-value: \n")
cat(round(x$p.value, 4))
if (!is.null(x$conf.int)) {
ci <- round(x$conf.int, 2)
cat(paste0(
"\n\nEstimate and ", x$ci_level * 100, "% confidence interval:\n"
))
cat(paste0(ci[1], " (", ci[2], " to ", ci[3], ")"))
}
} else {
ci <- round(x$conf.int, 2)
msat <- data.frame(
statistic = round(x$statistic),
estimate = paste0(ci[, 1], " (", ci[, 2], " to ", ci[, 3], ")"),
p.value = round(x$p.value, 4)
)
rownames(msat) <- x$names
}
invisible(x)
}
#' Print extra details about \code{test_cosinor} comparison.
#'
#' @param test_details A \code{list} of details from \code{test_cosinor}.
#'
#' @return \code{.print_details(x)} returns \code{x} invisibly.
#' @noRd
.print_details <- function(test_details) {
# Print parameter being assessed
cat(paste0(
"Parameter being tested:\n",
switch(test_details$param,
amp = "Amplitude",
acr = "Acrophase"
)
))
# Print type of comparison
cat("\n\nComparison type:\n")
cat(test_details$comparison_type)
# If comparison is on levels of a factor...
# - specify factor variable
# - levels being compared
# - the component being held constant
if (test_details$comparison_type == "levels") {
cat(paste0(
"\n\nGrouping variable used for comparison between groups: ",
test_details$x_str,
"\nReference group: ", test_details$comparison_A,
"\nComparator group: ", test_details$comparison_B
))
if (test_details$component_index == "") {
cat("\n\ncglmm model only has a single component and to compare
between groups.\n")
} else {
cat(paste0(
"\n\ncglmm model has", test_details$x$n_components,
" components. Component ", test_details$component_index,
" is being used for comparison between groups.\n"
))
}
}
# If comparison is on components of the model...
# - specify the component indices being compared
# - the grouping variable (if there is one) being held constant
# and its value
if (test_details$comparison_type == "components") {
cat(paste0(
"\n\nComponent indices used for comparison between groups: ",
test_details$x_str,
"\nReference component: ", test_details$comparison_A,
"\nComparator component: ", test_details$comparison_B
))
}
invisible(test_details)
}