写了一个函数进行bayes判别分析,当待测样本为NULL时运行无问题,但待测样本不为空时就出错,求大神指点
distinguish.bayes<-function
(TrnX, TrnG, p=rep(1, length(levels(TrnG))),
TstX = NULL, var.equal = FALSE){
if ( is.factor(TrnG) == FALSE){
mx<-nrow(TrnX); mg<-nrow(TrnG)
TrnX<-rbind(TrnX, TrnG)
TrnG<-factor(rep(1:2, c(mx, mg)))
}
if (is.null(TstX) == TRUE) TstX<-TrnX
if (is.vector(TstX) == TRUE) TstX<-t(as.matrix(TstX))
else if (is.matrix(TstX) != TRUE)
TstX<-as.matrix(TstX)
if (is.matrix(TrnX) != TRUE) TrnX<-as.matrix(TrnX)
nx<-nrow(TstX)
blong<-matrix(rep(0, nx), nrow=1, dimnames=list("blong", 1:nx))
g<-length(levels(TrnG))
mu<-matrix(0, nrow=g, ncol=ncol(TrnX))
for (i in 1:g)
mu[i,]<-colMeans(TrnX[TrnG==i,])
D<-matrix(0, nrow=g, ncol=nx)
if (var.equal == TRUE || var.equal == T){
for (i in 1:g){
d2 <- mahalanobis(TstX, mu[i,], var(TrnX))
D[i,] <- d2^2 - 2*log(p[i])
}
}
else{
for (i in 1:g){
S<-var(TrnX[TrnG==i,])
d2 <- mahalanobis(TstX, mu[i,], S)
D[i,] <- d2^2 -2*log(p[i])+log(det(S))
}
}
for (j in 1:nx){
dmin<-Inf
for (i in 1:g)
if (D[i,j]<dmin){
dmin<-D[i,j]; blong[j]<-i
}
}
blong
}
class1<-data.frame(
x1=c(0.045,0.066,0.094,0.003,0.048,0.210,0.086,0.196,0.187,0.053,0.020,0.035,0.205,0.088),
x2=c(0.043,0.039,0.061,0.003,0.015,0.066,0.072,0.072,0.082,0.060,0.008,0.015,0.068,0.058),
x3=c(0.265,0.264,0.194,0.102,0.106,0.263,0.274,0.211,0.301,0.209,0.112,0.170,0.284,0.215)
)
class1
class2<-data.frame(
x1=c(0.101,0.045),
x2=c(0.052,0.005),
x3=c(0.181,0.122)
)
class2
temp=c(2,2,2,3,3,1,2,1,1,2,3,3,1,2)
t=factor(temp)
t
bartlett.test(class1,t)
distinguish.bayes(class1,t,class2)
distinguish.bayes(class1,t)
distinguish.bayes(class1,t,class2,var.equal=T)
distinguish.bayes(class1,t,var.equal=T)