Debian Codegraph @

R/stats-prcomp.R

raw
1 #' @templateVar class prcomp
2 #' @template title_desc_tidy
3 #'
4 #' @param x A `prcomp` object returned by [stats::prcomp()].
5 #' @param matrix Character specifying which component of the PCA should be
6 #' tidied.
7 #'
8 #' - `"u"`, `"samples"`, `"scores"`, or `"x"`: returns information about
9 #' the map from the original space into principle components space.
10 #'
11 #' - `"v"`, `"rotation"`, `"loadings"` or `"variables"`: returns information
12 #' about the map from principle components space back into the original
13 #' space.
14 #'
15 #' - `"d"`, `"eigenvalues"` or `"pcs"`: returns information about the
16 #' eigenvalues.
17 #'
18 #' @template param_unused_dots
19 #'
20 #' @return A [tibble::tibble] with columns depending on the component of
21 #' PCA being tidied.
22 #'
23 #' If `matrix` is `"u"`, `"samples"`, `"scores"`, or `"x"` each row in the
24 #' tidied output corresponds to the original data in PCA space. The columns
25 #' are:
26 #'
27 #' \item{`row`}{ID of the original observation (i.e. rowname from original
28 #' data).}
29 #' \item{`PC`}{Integer indicating a principal component.}
30 #' \item{`value`}{The score of the observation for that particular principal
31 #' component. That is, the location of the observation in PCA space.}
32 #'
33 #' If `matrix` is `"v"`, `"rotation"`, `"loadings"` or `"variables"`, each
34 #' row in the tidied output corresponds to information about the principle
35 #' components in the original space. The columns are:
36 #'
37 #' \item{`row`}{The variable labels (colnames) of the data set on
38 #' which PCA was performed.}
39 #' \item{`PC`}{An integer vector indicating the principal component.}
40 #' \item{`value`}{The value of the eigenvector (axis score) on the
41 #' indicated principal component.}
42 #'
43 #' If `matrix` is `"d"`, `"eigenvalues"` or `"pcs"`, the columns are:
44 #'
45 #' \item{`PC`}{An integer vector indicating the principal component.}
46 #' \item{`std.dev`}{Standard deviation explained by this PC.}
47 #' \item{`percent`}{Fraction of variation explained by this component
48 #' (a numeric value between 0 and 1).}
49 #' \item{`cumulative`}{Cumulative fraction of variation explained by
50 #' principle components up to this component (a numeric value between 0 and
51 #' 1).}
52 #'
53 #' @details See https://stats.stackexchange.com/questions/134282/relationship-between-svd-and-pca-how-to-use-svd-to-perform-pca
54 #' for information on how to interpret the various tidied matrices. Note
55 #' that SVD is only equivalent to PCA on centered data.
56 #'
57 #' @examplesIf rlang::is_installed(c("maps", "ggplot2"))
58 #'
59 #' pc <- prcomp(USArrests, scale = TRUE)
60 #'
61 #' # information about rotation
62 #' tidy(pc)
63 #'
64 #' # information about samples (states)
65 #' tidy(pc, "samples")
66 #'
67 #' # information about PCs
68 #' tidy(pc, "pcs")
69 #'
70 #' # state map
71 #' library(dplyr)
72 #' library(ggplot2)
73 #' library(maps)
74 #'
75 #' pc |>
76 #' tidy(matrix = "samples") |>
77 #' mutate(region = tolower(row)) |>
78 #' inner_join(map_data("state"), by = "region") |>
79 #' ggplot(aes(long, lat, group = group, fill = value)) +
80 #' geom_polygon() +
81 #' facet_wrap(~PC) +
82 #' theme_void() +
83 #' ggtitle("Principal components of arrest data")
84 #'
85 #' au <- augment(pc, data = USArrests)
86 #'
87 #' au
88 #'
89 #' ggplot(au, aes(.fittedPC1, .fittedPC2)) +
90 #' geom_point() +
91 #' geom_text(aes(label = .rownames), vjust = 1, hjust = 1)
92 #'
93 #' @aliases prcomp_tidiers
94 #' @export
95 #' @seealso [stats::prcomp()], [svd_tidiers]
96 #' @family svd tidiers
97 tidy.prcomp <- function(x, matrix = "u", ...) {
98 if (length(matrix) > 1) {
99 cli::cli_abort("Must select a single matrix to tidy.")
100 }
101
102 MATRIX <- c(
103 "rotation",
104 "x",
105 "variables",
106 "samples",
107 "v",
108 "u",
109 "pcs",
110 "d",
111 "scores",
112 "loadings",
113 "eigenvalues"
114 )
115 matrix <- rlang::arg_match(matrix, MATRIX)
116
117 ncomp <- NCOL(x$rotation)
118 if (matrix %in% c("pcs", "d", "eigenvalues")) {
119 ret <- as_tidy_tibble(
120 t(summary(x)$importance),
121 new_names = c("std.dev", "percent", "cumulative"),
122 new_column = "PC"
123 )
124 } else if (matrix %in% c("rotation", "variables", "v", "loadings")) {
125 ret <- x$rotation |>
126 tibble::as_tibble(rownames = "column") |>
127 tidyr::pivot_longer(
128 cols = -"column",
129 names_to = "PC",
130 values_to = "value"
131 )
132 if (is.null(rownames(x$rotation))) ret$column <- as.integer(ret$column)
133 } else if (matrix %in% c("x", "samples", "u", "scores")) {
134 ret <- x$x |>
135 tibble::as_tibble(rownames = "row") |>
136 tidyr::pivot_longer(
137 cols = -"row",
138 names_to = "PC",
139 values_to = "value"
140 )
141 if (is.null(rownames(x$x))) ret$row <- as.integer(ret$row)
142 }
143
144 # change the PC to a numeric
145 ret <- mutate(ret, PC = as.numeric(stringr::str_replace(PC, "PC", "")))
146 as_tibble(ret)
147 }
148
149
150 #' @templateVar class prcomp
151 #' @template title_desc_augment
152 #'
153 #' @inheritParams tidy.prcomp
154 #' @template param_data
155 #' @template param_newdata
156 #'
157 #' @return A [tibble::tibble] containing the original data along with
158 #' additional columns containing each observation's projection into
159 #' PCA space.
160 #'
161 #' @export
162 #' @seealso [stats::prcomp()], [svd_tidiers]
163 #' @family svd tidiers
164 #'
165 augment.prcomp <- function(x, data = NULL, newdata, ...) {
166 ret <- if (!missing(newdata)) {
167 ret <- data.frame(.rownames = rownames(newdata))
168 pred <- as.data.frame(predict(x, newdata = newdata))
169 names(pred) <- paste0(".fitted", names(pred))
170 cbind(ret, newdata, pred)
171 } else {
172 pred <- as.data.frame(predict(x))
173 names(pred) <- paste0(".fitted", names(pred))
174 if (!missing(data) && !is.null(data)) {
175 cbind(.rownames = rownames(as.data.frame(data)), data, pred)
176 } else {
177 data.frame(.rownames = rownames(as.data.frame(x$x)), pred)
178 }
179 }
180 as_tibble(ret)
181 }