[R] confusion matrix - better code?

Wolfgang Huber huber at ebi.ac.uk
Fri Sep 7 22:04:32 CEST 2007


Dear Monica,

try this:

cm =  table(tr, pr)
cm
    pr
tr  1 2 3
   1 2 1 0
   2 2 1 0
   3 0 0 3
   4 0 1 0


rowSums(cm)
colSums(cm)

   Best wishes
	Wolfgang Huber

Monica Pisica ha scritto:
> Hi,
>  
> I�ve written some code to obtain a confusion matrix when the true classification and the predicted classification are known. Suppose true classification is called �tr� and predicted classification is �pr�. I have 4 classes in tr, but only 3 classes out of 4 are predicted in �pr�. Following is my code, but looks quite �clunky� to me. I wonder if you have any suggestions to improve it.
>  
> Thanks,
>  
> Monica
>  
> -----------------------------
>  
> tr <- c(1,2,2,3,3,3,2,4,1,1)
> pr<-c(1,2,1,3,3,3,1,2,1,2)
> dat <- data.frame(tr, pr)
> class <- c(1:length(tr))
> m <- max(c(length(unique(tr)), length(unique(pr))))
> for(i in 1:length(class)) {
>  class[i] <- sub(' ','',paste(dat[i,1],dat[i,2])) }
> dat <- data.frame(dat, class)
> mat <- matrix(0, nrow=m, ncol=m)
> for (i in 1:m){
>   for (j in 1:m){
>  mat[i,j] <- sub(' ','',paste(i,j))
>  }}
> cat <- matrix(0, nrow=(m+1), ncol=(m+1))
>   for (i in 1:m){
>   for(j in 1:m){
>  cat[i,j]<- nrow(dat[dat$class==mat[i,j],])
> }}
> for (i in 1:m){
> cat[(m+1),i]<-sum(cat[1:m,i])
>  cat[i,(m+1)]<- sum(cat[i,1:m])
> cat[(m+1),(m+1)] <- sum(cat[1:m,(m+1)])
> }
> cat
>      [,1] [,2] [,3] [,4] [,5]
> [1,]    2    1    0    0    3
> [2,]    2    1    0    0    3
> [3,]    0    0    3    0    3
> [4,]    0    1    0    0    1
> [5,]    4    3    3    0   10
>  
> The 5th row / col represents the sum on each row / col respectively.



More information about the R-help mailing list