Debian Codegraph @

R/list-svd.R

raw
1 #' @templateVar class svd
2 #' @template title_desc_tidy_list
3 #'
4 #' @inherit tidy.prcomp return details params
5 #' @param x A list with components `u`, `d`, `v` returned by [base::svd()].
6 #'
7 #' @examplesIf rlang::is_installed(c("modeldata", "ggplot2"))
8 #'
9 #' library(modeldata)
10 #' data(hpc_data)
11 #'
12 #' mat <- scale(as.matrix(hpc_data[, 2:5]))
13 #' s <- svd(mat)
14 #'
15 #' tidy_u <- tidy(s, matrix = "u")
16 #' tidy_u
17 #'
18 #' tidy_d <- tidy(s, matrix = "d")
19 #' tidy_d
20 #'
21 #' tidy_v <- tidy(s, matrix = "v")
22 #' tidy_v
23 #'
24 #' library(ggplot2)
25 #' library(dplyr)
26 #'
27 #' ggplot(tidy_d, aes(PC, percent)) +
28 #' geom_point() +
29 #' ylab("% of variance explained")
30 #'
31 #' tidy_u |>
32 #' mutate(class = hpc_data$class[row]) |>
33 #' ggplot(aes(class, value)) +
34 #' geom_boxplot() +
35 #' facet_wrap(~PC, scale = "free_y")
36 #'
37 #' @seealso [base::svd()]
38 #' @aliases svd_tidiers
39 #' @family svd tidiers
40 #' @family list tidiers
41 tidy_svd <- function(x, matrix = "u", ...) {
42 if (length(matrix) > 1) {
43 cli::cli_abort("Must specify a single matrix to tidy.")
44 }
45
46 if (matrix == "u") {
47 ret <- x$u |>
48 as_tibble(.name_repair = "unique_quiet") |>
49 tibble::rowid_to_column("row") |>
50 pivot_longer(
51 cols = c(dplyr::everything(), -row),
52 names_to = "PC",
53 values_to = "value"
54 ) |>
55 dplyr::mutate(
56 PC = stringr::str_remove(PC, "...") |>
57 as.numeric()
58 ) |>
59 arrange(PC, row) |>
60 as.data.frame()
61 } else if (matrix == "d") {
62 ret <- tibble(PC = seq_along(x$d), std.dev = x$d) |>
63 mutate(
64 percent = std.dev^2 / sum(std.dev^2),
65 cumulative = cumsum(percent)
66 )
67 } else if (matrix == "v") {
68 # use unique_quiet to silence test in tidy_svd
69 ret <- x$v |>
70 as_tibble(.name_repair = "unique_quiet") |>
71 tibble::rowid_to_column("column") |>
72 pivot_longer(
73 cols = c(dplyr::everything(), -column),
74 names_to = "PC",
75 values_to = "value"
76 ) |>
77 dplyr::mutate(
78 PC = stringr::str_remove(PC, "...") |>
79 as.numeric()
80 ) |>
81 arrange(PC, column) |>
82 as.data.frame()
83 }
84 as_tibble(ret)
85 }