你好,我需要帮助,试图将此代码推广到任何矩阵的数据PoliticalDemocracy在lavaan中可用。图书馆
What I tried
library(lavaan)
R<-chol(cor(PoliticalDemocracy[1:8]))
diag(R)<-NA
R<-round(R,3)
R
R[R==0]<-NA
R
d<-matrix(NA,nrow(R),ncol(R))
d[,1]<-acos(R[1,])
d
d[,2]<-acos(R[2,]/sin(d[,1]))
d[,3]<-acos(R[3,]/sin(d[,1])*sin(d[,2]))
d[,4]<-acos(R[4,]/sin(d[,1])*sin(d[,2])*sin(d[,3]))
d[,5]<-acos(R[5,]/sin(d[,1])*sin(d[,2])*sin(d[,3])*sin(d[,4]))
d[,6]<-acos(R[6,]/sin(d[,1])*sin(d[,2])*sin(d[,3])*sin(d[,4])*sin(d[,5]))
d[,7]<-acos(R[7,]/sin(d[,1])*sin(d[,2])*sin(d[,3])*sin(d[,4])*sin(d[,5])*sin(d[,6]))
d[,8]<-acos(R[8,]/sin(d[,1])*sin(d[,2])*sin(d[,3])*sin(d[,4])*sin(d[,5])*sin(d[,6])*sin(d[,7]))
我尝试使用循环,但有错误和一个空矩阵d
d<-matrix(NA,nrow(R),ncol(R))
d[,1]<-acos(R[1,])
d
for (i in 2:nrow(d)){
d[,i]<-acos(R[i,])/prod(sin(d[,i-1]))
d
}
d
@AllanCameron
您可以使用Reduce
函数,如下所示
(Reduce(function(x, y)
cbind(x, acos(y/matrixStats::rowProds(sin(x)))),
data.frame(t(R)), init = matrix(rep(pi/2), nrow(R)))[,-1])