Debian Codegraph @

R/stats-factanal.R

raw
1 #' @templateVar class factanal
2 #' @template title_desc_tidy
3 #'
4 #' @param x A `factanal` object created by [stats::factanal()].
5 #' @template param_unused_dots
6 #'
7 #' @evalRd return_tidy(
8 #' "variable",
9 #' uniqueness = "Proportion of residual, or unexplained variance",
10 #' flX = "Factor loading for level X."
11 #' )
12 #'
13 #' @examples
14 #'
15 #' set.seed(123)
16 #'
17 #' # generate data
18 #' library(dplyr)
19 #' library(purrr)
20 #'
21 #' m1 <- tibble(
22 #' v1 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 4, 5, 6),
23 #' v2 = c(1, 2, 1, 1, 1, 1, 2, 1, 2, 1, 3, 4, 3, 3, 3, 4, 6, 5),
24 #' v3 = c(3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 4, 6),
25 #' v4 = c(3, 3, 4, 3, 3, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 5, 6, 4),
26 #' v5 = c(1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 6, 4, 5),
27 #' v6 = c(1, 1, 1, 2, 1, 3, 3, 3, 4, 3, 1, 1, 1, 2, 1, 6, 5, 4)
28 #' )
29 #'
30 #' # new data
31 #' m2 <- map_dfr(m1, rev)
32 #'
33 #' # factor analysis objects
34 #' fit1 <- factanal(m1, factors = 3, scores = "Bartlett")
35 #' fit2 <- factanal(m1, factors = 3, scores = "regression")
36 #'
37 #' # tidying the object
38 #' tidy(fit1)
39 #' tidy(fit2)
40 #'
41 #' # augmented dataframe
42 #' augment(fit1)
43 #' augment(fit2)
44 #'
45 #' # augmented dataframe (with new data)
46 #' augment(fit1, data = m2)
47 #' augment(fit2, data = m2)
48 #'
49 #' @aliases factanal_tidiers
50 #' @export
51 #' @seealso [tidy()], [stats::factanal()]
52 #' @family factanal tidiers
53
54 tidy.factanal <- function(x, ...) {
55 # as.matrix() causes this to break. unsure if this is a hack or appropriate
56 loadings <- stats::loadings(x)
57 class(loadings) <- "matrix"
58
59 tidy_df <- data.frame(
60 variable = rownames(loadings),
61 uniqueness = x$uniquenesses,
62 data.frame(loadings)
63 ) |>
64 as_tibble()
65
66 tidy_df$variable <- as.character(tidy_df$variable)
67
68 # Remove row names and clean column names
69 colnames(tidy_df) <- gsub("Factor", "fl", colnames(tidy_df))
70
71 tidy_df
72 }
73
74 #' @templateVar class factanal
75 #' @template title_desc_augment
76 #'
77 #' @inheritParams tidy.factanal
78 #' @template param_data
79 #'
80 #' @return When `data` is not supplied `augment.factanal` returns one
81 #' row for each observation, with a factor score column added for each factor
82 #' X, (`.fsX`). This is because [stats::factanal()], unlike other
83 #' stats methods like [stats::lm()], does not retain the original data.
84 #'
85 #' When `data` is supplied, `augment.factanal` returns one row for
86 #' each observation, with a factor score column added for each factor X,
87 #' (`.fsX`).
88 #'
89 #' @export
90 #' @seealso [augment()], [stats::factanal()]
91 #' @family factanal tidiers
92 augment.factanal <- function(x, data, ...) {
93 check_ellipses("newdata", "augment", "factanal", ...)
94
95 scores <- x$scores
96
97 # Check scores were computed
98 if (is.null(scores)) {
99 cli::cli_abort(
100 'Cannot augment {.cls factanal} objects fit with {.code scores = "none"}.'
101 )
102 }
103
104 # Place relevant values into a tidy data frame
105 if (has_rownames(scores)) {
106 tidy_df <- data.frame(.rownames = rownames(scores), data.frame(scores)) |>
107 as_tibble() |>
108 dplyr::mutate(.rownames = as.character(.rownames))
109 } else {
110 tidy_df <- tibble::rownames_to_column(
111 as.data.frame(scores),
112 var = ".rownames"
113 ) |>
114 as_tibble() |>
115 dplyr::mutate(.rownames = as.character(.rownames))
116 }
117
118 colnames(tidy_df) <- gsub("Factor", ".fs", colnames(tidy_df))
119
120 # Check if original data provided
121 if (missing(data)) {
122 return(tidy_df)
123 } else {
124 data <- tibble::rownames_to_column(
125 as.data.frame(data),
126 var = ".rownames"
127 ) |>
128 as_tibble() |>
129 dplyr::mutate(.rownames = as.character(.rownames))
130 }
131
132 # Bind to data
133 tidy_df <- dplyr::right_join(x = tidy_df, y = data, by = ".rownames")
134
135 # select all columns with name pattern `.fs` and move them to the end of the
136 # augmented dataframe
137 tidy_df |>
138 dplyr::select(
139 .rownames,
140 dplyr::everything(),
141 -dplyr::matches("\\.fs[0-9]*"),
142 dplyr::matches("\\.fs[0-9]*")
143 )
144 }
145
146 #' @templateVar class factanal
147 #' @template title_desc_glance
148 #'
149 #' @inherit tidy.factanal params examples
150 #'
151 #' @evalRd return_glance(
152 #' "n.factors",
153 #' "total.variance",
154 #' "statistic",
155 #' "p.value",
156 #' "df",
157 #' "n",
158 #' "method",
159 #' "converged",
160 #' "nobs"
161 #' )
162 #'
163 #' @export
164 #'
165 #' @seealso [glance()], [stats::factanal()]
166 #' @family factanal tidiers
167 glance.factanal <- function(x, ...) {
168 # Compute total variance accounted for by all factors
169 loadings <- stats::loadings(x)
170 class(loadings) <- "matrix"
171 total.variance <- sum(apply(loadings, 2, function(i) sum(i^2) / length(i)))
172
173 # Results as single-row data frame
174 as_glance_tibble(
175 n.factors = x$factors,
176 total.variance = total.variance,
177 statistic = unname(x$STATISTIC),
178 p.value = unname(x$PVAL),
179 df = x$dof,
180 n = x$n.obs,
181 method = x$method,
182 converged = x$converged,
183 nobs = stats::nobs(x),
184 na_types = "irrriicli"
185 )
186 }