基于psych包的R模拟函数不保存值

R simulation function based on psych package not saving values

我正在尝试为 R 编写一个使用两个包的函数:simsempsych。简而言之,我希望该函数允许我使用 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")

您错误地更改了数据框的名称...

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"
  }
  return(fit)
}

此外,您可能希望将 stringsAsFactors=FALSE 添加到您的数据框以避免以后出现问题...