-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcfa.R
104 lines (84 loc) · 2.13 KB
/
cfa.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#' Create three models that can be used to fit lavaan models for HCL-32
#'
#' @return A list with three models on lavaan package syntax.
#' @export
#'
create_models <- function() {
bech <- 'Active =~ y2 + y28 + y11 +
y5 + y18 + y4 + y15 + y20 +
y10 + y1
Risk =~ y23 + y8 + y9 + y25 +
y21 + y31 + y29 + y7 + y27 + y32'
forty <- 'Active =~ y1 + y4 + y6 +
y10 + y13 + y17 + y19 + y20 + y28
Risk =~ y8 + y9 + y14 + y27 +
y30 + y31 + y32'
hcl28 <- 'Active =~ y2 + y3 + y4 + y5 + y6 +
y10 + y11 + y12 + y13 + y14 +
y15 + y18 + y19 + y20 + y22 +
y24 + y28
Risk =~ y1 + y7 + y8 + y9 + y25 +
y26 + y27 + y29 + y30 +
y31 + y32'
models <- list(bech, forty, hcl28) %>%
purrr::set_names(
nm = c("Bech", "Forty", "HCL-28")
)
return(models)
}
#' Fit CFA models on given data using WLSMV estimator
#'
#' @param data Data frame or tibble containing the HCL-32 items.
#' @param models Models to be fitted on data.
#'
#' @return A list containing the fitted models.
#' @export
#'
fit_models <- function(data, models) {
set.seed(666)
fits <- purrr::map(models,
~ lavaan::cfa(.x,
data = data,
estimator = "WLSMV",
ordered = names(data))
)
return(fits)
}
#' Summarize fitted models performance metrics
#'
#' @param fits A list containing fitted models.
#'
#' @return Summarized metrics for each model as a list. Based on lavaan output.
#' @export
#'
summarize_fit <- function(fits) {
summaries <- purrr::map(fits,
~ lavaan::summary(.x,
fit.measures = TRUE,
standardized = TRUE)
)
return(summaries)
}
#' Summarize fitted models metrics
#'
#' @param fits A list containing fitted models.
#'
#' @return Summarized parameters for each model as a list. Based on lavaan output.
#' @export
#'
summarize_parameters <- function(fits) {
tables <- purrr::map(
fits,
~ lavaan::parameterEstimates(.x, standardized = TRUE) %>%
dplyr::filter(op == "=~") %>%
dplyr::select("Factor" = lhs,
Item = rhs,
B = est,
SE = se,
Z = z,
"p-value" = pvalue,
Beta = std.all) %>%
dplyr::arrange(dplyr::desc(Beta))
)
return(tables)
}