我正在尝试编写一个R
使用两个包的函数:simsem
和psych
. 简而言之,我希望该函数允许我为要绘制的每个随机样本指定一个大小,使用指定要在每个样本上运行simsem
的因子分析 () 选项,然后保存每个模型的值在数据框中采样,以便我以后可以在它们之间进行汇总。fa
psych
fa
但是,该功能目前不起作用;没有任何值从函数的任何重复中保存在目标数据帧中。
可重现的示例和我的功能代码如下。真的很感激任何洞察出了什么问题。
#Install and call simsem and psych package, to simulate datasets based on population model, and fit fa model
install.packages("simsem")
library(simsem)
install.packages("psych")
library(psych)
#Specify Population Model
popModel<-"
f1 =~ 0.7*y1 + 0.7*y2 + 0.7*y3
f2 =~ 0.5*y4 + 0.5*y5 + 0.5*y6
f1 ~~ 1*f1
f2 ~~ 1*f2
f1 ~~ 0.50*f2
y1 ~~ 0.51*y1
y2 ~~ 0.51*y2
y3 ~~ 0.51*y3
y4 ~~ 0.75*y4
y5 ~~ 0.75*y5
y6 ~~ 0.75*y6
"
#Function: User specifies number of reps, sample size, number of factors, rotation and extraction method
#Then for each rep, a random sample of popModel is drawn, a FA model is fit, and two logical values are saved
#in data.frame fit
sample.efa = function(rep, N, nfac, rotation, extract){
fit = data.frame(RMSEA= logical(0), TLI = logical(0)) #create empty data frame with two columns
for(i in seq_len(rep)){
dat = generate(popModel, N) #draw a random sample of N size from popModel
model = fa(dat, nfactors = nfac, rotate = rotation, fm = extract, SMC = TRUE, alpha = .05) #fit FA model with user specified options from function
store = data.frame(RMSEA=all(model$rms < .08), TLI = all(model$TLI > .90)) #save two logical values in "store"
names(store) = names(fit) #give "store" same names as target data-frame
fit=rbind(fit, store) #save values from each iteration of "store" in target data-frame "fit"
}
}
#Run test of function with small number of reps (5) of sample sizes of 200
set.seed(123)
sample.efa(5, N = 200, nfac = 2, rotation = "promax", extract = "ml")