-
Notifications
You must be signed in to change notification settings - Fork 0
/
correlations.R
72 lines (64 loc) · 1.93 KB
/
correlations.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
#' Observed Residual Correlations
#'
#' Compute observed residual correlation (ORC) matrix among observed residuals
#' for variables supplied data.
#'
#' `r lifecycle::badge('experimental')`
#'
#' @param data A data.frame or tibble
#' @param na.rm logical (defaults to TRUE)
#' @returns A numeric matrix of correlations among variable residuals.
#' @examples
#' # Use the SCWB data example
#' data(SCWB)
#' cor.orc(SCWB[, 1:20])
#' @import dplyr tidyselect
#' @export
cor.orc <- function(data, na.rm = TRUE) {
temp.data <- data
temp.data <- append_observed_residuals(temp.data, na.rm = na.rm)
# compute correlations of residuals
Qij <- temp.data %>%
select(contains("resid_")) %>%
cor(use = "pairwise.complete.obs")
rownames(Qij) <- colnames(Qij) <- colnames(data)
Qij
}
#' Relative Excess Correlations
#'
#' Compute relative excess correlation (REC) matrix among variables in supplied
#' data.
#'
#' `r lifecycle::badge('experimental')`
#'
#' @param data A data.frame or tibble
#' @param na.rm logical (defaults to TRUE)
#' @returns A numeric matrix of correlations among variable residuals.
#' @examples
#' # Use the SCWB data example
#' data(SCWB)
#' cor.rec(SCWB[, 1:20])
#' @export
cor.rec <- function(data, na.rm = TRUE) {
temp.data <- data
temp.data <- append_observed_residuals(temp.data, na.rm = na.rm)
# observed correlations
Cij <- temp.data %>%
select(!contains("resid_")) %>%
cor(use = "pairwise.complete.obs")
rownames(Cij) <- colnames(Cij) <- colnames(data)
# compute relative excess correlation
diag(Cij) <- NA
rho.i <- rowMeans(Cij, na.rm = TRUE)
rho.. <- mean(Cij, na.rm = TRUE)
Qij.star <- matrix(nrow = ncol(Cij), ncol = ncol(Cij))
for (i in 1:ncol(Cij)) {
for (j in 1:ncol(Cij)) {
if (i != j) {
Qij.star[i, j] <- (Cij[i, j] - rho..) - ((rho.i[i] - rho..) + (rho.i[j] - rho..))
}
}
}
rownames(Qij.star) <- colnames(Qij.star) <- colnames(data)
Qij.star
}