使用 cbind 向 R 中的数据集添加因子分数

Adding Factor Scores to the Data Set in R using cbind

我在向原始数据集添加因子得分时遇到困难。正如 here 所述,这根本不是一个困难的过程。但是,就我而言,我收到以下代码的以下错误:

fa <- factanal(data, factors=2, rotation="promax", scores="regression")

data <- cbind(data, fa$scores)
Error in data.frame(..., check.names = FALSE) :
arguments imply differing number of rows: 889, 851

如果行号确实不同,收到此错误也就不足为奇了,但是当我键入 "fa$scores" 并按回车键时,R 会显示所有 889 行。 dim 函数仍然 returns 851 虽然:

dim(fa$scores)
[1] 851   2

能否请您解释一下我收到此错误的原因,如果可能的话,我可以做些什么来成功地将因子分数添加到数据中?

谢谢!

fa$scores returns 具有行名的矩阵,您可以将其用于 join/merge 数据。

首先,确保 data 有行名。如果不是,请给它起个虚拟名称,例如:

rownames(data) <- 1:nrow(data)

然后运行fa <- factanal(...),将fa$scores转换为因子得分的数据框。例如,

fs <- data.frame(fa$scores)

然后,将 rowname 列添加到原始数据和 fs:

data$rowname <- rownames(data)
fs$rowname   <- rownames(fs)

然后左连接到数据(使用 dplyr 包):

library(dplyr)
left_join(data, fs, by = "rowname)