Debian Codegraph @

R/hmisc.R

raw
1 #' @templateVar class rcorr
2 #' @template title_desc_tidy
3 #'
4 #' @param x An `rcorr` object returned from [Hmisc::rcorr()].
5 #' @param diagonal Logical indicating whether or not to include diagonal
6 #' elements of the correlation matrix, or the correlation of a column with
7 #' itself. For the elements, `estimate` is always 1 and `p.value` is always
8 #' `NA`. Defaults to `FALSE`.
9 #' @template param_unused_dots
10 #'
11 #' @evalRd return_tidy(
12 #' "column1",
13 #' "column2",
14 #' "estimate",
15 #' "p.value",
16 #' n = "Number of observations used to compute the correlation"
17 #' )
18 #'
19 #' @details Suppose the original data has columns A and B. In the correlation
20 #' matrix from `rcorr` there may be entries for both the `cor(A, B)` and
21 #' `cor(B, A)`. Only one of these pairs will ever be present in the tidy
22 #' output.
23 #'
24 #' @examplesIf FALSE
25 #'
26 #' # load libraries for models and data
27 #' library(Hmisc)
28 #'
29 #' mat <- replicate(52, rnorm(100))
30 #'
31 #' # add some NAs
32 #' mat[sample(length(mat), 2000)] <- NA
33 #'
34 #' # also, column names
35 #' colnames(mat) <- c(LETTERS, letters)
36 #'
37 #' # fit model
38 #' rc <- rcorr(mat)
39 #'
40 #' # summarize model fit with tidiers + visualization
41 #' td <- tidy(rc)
42 #' td
43 #'
44 #' library(ggplot2)
45 #' ggplot(td, aes(p.value)) +
46 #' geom_histogram(binwidth = .1)
47 #'
48 #' ggplot(td, aes(estimate, p.value)) +
49 #' geom_point() +
50 #' scale_y_log10()
51 #'
52 #' @export
53 #' @aliases rcorr_tidiers Hmisc_tidiers
54 #' @seealso [tidy()], [Hmisc::rcorr()]
55 tidy.rcorr <- function(x, diagonal = FALSE, ...) {
56 ret <- x$r |>
57 as.data.frame() |>
58 tibble::rownames_to_column("column1") |>
59 pivot_longer(
60 c(dplyr::everything(), -column1),
61 names_to = "column2",
62 values_to = "estimate"
63 ) |>
64 as.data.frame() |>
65 mutate(n = as.vector(x$n), p.value = as.vector(x$P))
66
67 # include only half the symmetric matrix.
68 ret <- ret[upper.tri(x$r, diag = diagonal), ]
69 as_tibble(ret)
70 }