neutral neutral - 1 month ago 13
R Question

Adding Factor Scores to the Data Set in R using cbind

I am having difficulties adding factor scores to the original data set. It is not a difficult procedure at all, as is described here. However, in my case, I receive the following error to the below code:

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


It would be no surprise to receive this error, if the row numbers really differed, but when I type "fa$scores" and hit enter, R displays all of the 889 rows. The dim function still returns 851 though:

dim(fa$scores)
[1] 851 2


Can you please clarify for me why I am receiving this error, and if possible, what I can do to add the factor scores to the data successfully?

Thanks!

Answer

fa$scores returns a matrix with rownames that you can use to join/merge the data together.

First, make sure data has rownames. If not, give it dummy names like:

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

Then run fa <- factanal(...), and convert fa$scores to a data frame of factor scores. E.g.,

fs <- data.frame(fa$scores)

Then, add a rowname column to both your original data and fs:

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

Then left join to data (using dplyr package):

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