While Using factanal
function from stats package for performing factor analysis.
I tried following thing.
library(mirt)
library(ltm)
library(psych)
library(stats)
data(SAT12)
data=SAT12
cor_mat=polychoric(data, ML=TRUE, global=F)
fit <- factanal(factors=2, n.obs=nrow(data), covmat=cor_mat$rho)
Divide_item_Factor_Loading(fit)
when I am trying to run Divide_item_Factor_Loading(fit) an error called
Error in a[[i]][[2]] : subscript out of bounds
pops up.
my complete code of Divide_item_Factor_Loading:
Divide_item_Factor_Loading=function(fit)
{
a=list()
items=NULL
for(i in 1:nrow(fit$loadings)) ######corresponding to rows of loading matrix
{
k=which(fit$loadings[i,]==max(abs(fit$loadings[i,])))
a[[i]]=c(i,as.numeric(k))
}
fact_item_mat=matrix(, nrow=nrow(fit$loadings), ncol=ncol(fit$loadings))
for(j in 1:(ncol(fit$loadings)))
{
for(i in 1:(nrow(fit$loadings)))
{
if(a[[i]][[2]]==j) {fact_item_mat[i,j]=a[[i]][[1]]}
}
}
nam=names(fit$loadings[,1])
factor=list()
for(i in 1:ncol(fit$loadings))
{
factor[[i]]=sort(fact_item_mat[,i], decreasing = FALSE, na.last = NA)
fac=factor[[i]]
fac=nam[fac]
factor[[i]]=fac
}
names(factor)=paste("factor", 1:ncol(fit$loadings), sep="")
return(factor)
}
What steps should I take now to avoid this error?
To change the way the loadings are printed, use the cutoff
argument to print.loadings
.
Try something like this:
print(fit$loadings, cutoff=0)
The actual matrix contains all the values.
print(loadings(fit), cutoff=0)
Loadings:
Factor1 Factor2
Item 1 0.014 0.418
Item 2 0.130 0.350
Item 3 0.036 0.553
Item 4 0.166 0.294
Item 5 0.990 0.125
Factor1 Factor2
SS loadings 1.025 0.705
Proportion Var 0.205 0.141
Cumulative Var 0.205 0.346
Now extract the maximum loading on each factor, using apply()
:
apply(loadings(fit), 2, max)
Factor1 Factor2
0.9895743 0.5531770