R 中的 Sokal 和 Sneath 函数距离

Sokal and Sneath Function Distance in R

这更多是功能问题。所以对于二进制向量,我有 Sokal 和 Sneath 距离:

d(xi,xj)=a/(a+2*(b+c))

其中,a=#(xik=xjk=1),b=#(xik=0 和 xjk=1) 和 c=#(xik=1 和 xjk=0)。 k为矩阵的列数,#表示事件发生的次数。

你能给我提示和技巧吗?谢谢。

我把a,b,c写成

a=sum(x[i]==x[j]==1)

b=sum((x[i]==0)&&(x[j]==0]))

c=sum((x[i]==1)&&(x[j]==1))

我找到了问题的解决方案:

SSD<- function(x) {
      x<-as.matrix(x) #convert to matrix 
      dist.matrix<- matrix(0,nrow(x),nrow(x)) #creates empty matrix
      for (i in 1:nrow(x)) { #iterate the data rows over i
        for (j in 1:nrow(x)) { #iterate the data rows over j
          a<- 0 #empty|
          b<- 0 #empty|=> to populate later on
          c<- 0 #empty|
          for (k in 1:ncol(x)) { #iterate the data over columns
          if (((x)[i,k]==1)&((x)[j,k]==1)) { #first assumption to hold
              a<-a+1 #summing the ones that hold the case
            }else if (((x)[i,k]==0)&((x)[j,k]==1)) { #second assumption
              b<-b+1 #summing the ones that hold the case
            } else if (((x)[i,k]==1)&((x)[j,k]==0)) { #third assumption
              c<-c+1 #summing the ones that hold the case
            }
          }
          dist.matrix[i,j]<-a/(a+2*(b+c)) #populate the matrix by the formula given 
        }
      }  
      library(xtable)
      return(xtable(dist.matrix))
    }