代码如下:
CER <- function(partition1,partition2){
if (length(partition1)!= length(partition2))
stop("partition1 and 2 dont have the same observations")
mycer=0
for (i in 1:length(partition1)-1){
for (j in (i+1):length(partition1)){
mycer <- mycer+abs(as.numeric(partition1[i]==partition1[j])-as.numeric(partition2[i]==partition2[j]))
}
}
error_rate <- mycer/(length(partition1)*(length(partition1)-1)/2)
return (error_rate)
}
测试的数据为:
partition1<- c(3,3,1,1,1,3,1,1,1,1,1,3,3,1,3,1,3,1,3,1,2,2,2,2,2,2,2,2,2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 2, 1, 3, 2, 3, 2, 1, 1, 3, 3, 1, 1, 3, 1, 2, 1, 1, 3)
partition2<-c(3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 ,3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
先运行循环
mycer=0
for (i in 1:length(partition1)-1){
for (j in (i+1):length(partition1)){
mycer <- mycer+abs(as.numeric(partition1[i]==partition1[j])-as.numeric(partition2[i]==partition2[j]))
}
得到的结果是 mycer为numeric(0),但是单独运行每一个循环,能得到正确的数字,不知道是怎么回事