R语言中循环执行因子分析并保存迭代结果的方法
Hey there! The issue with your current code is that you're trying to store the output of principal() (which is a complex object containing loadings, eigenvalues, and more) into an uninitialized vector. Instead, you should use a list to hold each iteration's results—lists are perfect for storing objects of different sizes/types like the output from psych::principal(). Here's how to adjust your code:
Step 1: Initialize an empty list
First, create an empty list to store each factor analysis result before your loop runs:
library(psych) # Initialize empty list to hold results fit <- list()
Step 2: Update your loop to store results in the list
Modify your loop to assign each principal() output to a named element in the list. Using the number of factors as the element name makes it way easier to access specific results later:
for (i in 5:10){ # Use the factor count as the list element name for clarity fit[[as.character(i)]] <- principal(data, nfactors = i, rotate = "varimax") }
Step 3: Access your saved results
Now you can easily retrieve any iteration's output:
- To view the full result for 5 factors:
fit[["5"]] - To extract just the loading matrix for 7 factors:
fit[["7"]]$loadings - To get the eigenvalues for 10 factors:
fit[["10"]]$values
Bonus: Loop through results to summarize all outputs
If you want a quick overview of every iteration, loop through the list and print summaries:
for (factor_count in names(fit)) { cat("=== Factor Analysis with", factor_count, "Factors ===\n") print(summary(fit[[factor_count]])) cat("\n") }
Why your original code didn't work
Your initial code tried to assign principal() outputs to fit[i], but two key issues blocked it:
fitwasn't initialized, so R defaulted to treating it as a regular vector (which can't hold complex objects like factor analysis results).principal()returns a multi-component object, which can't be stored in a simple vector.
内容的提问来源于stack exchange,提问作者Daniel Rawlings

