变量与数据框中所有其他变量的比较

Comparison of variable to all other variables in data frame

我想检查一个变量与数据框中所有其他变量的接近程度。我想通过计算它们对同一行具有相同值的次数(即相同的观察)来做到这一点。例如,在 mtcars 数据集中,变量 gearcarb 有 7 个观察值,它们在同一行(即同一辆车)中具有相同的值。

我尝试了以下方法,结果是 closeness_matrix。然而,结果似乎是不合理的。知道什么不起作用吗?

PS:我也尝试过使用 mapply,我想它会更快,但它没有用,所以我最终使用了嵌套的 loop

MWE:

cols_ls <- colnames(mtcars)

closeness_matrix <- matrix(nrow = ncol(mtcars),
                            ncol = ncol(mtcars))

row.names(closeness_matrix) <- cols_ls; colnames(closeness_matrix) <- cols_ls


for (i in 1:length(cols_ls)){

  for (j in i:length(cols_ls)){

    closeness_matrix[i,j] <- sum(duplicated(mtcars[,c(i,j), with = FALSE])==TRUE)

  }
}

我猜下面的方法可以做到(但我相信有更聪明的方法):

closenessFunc<-function(v1,M){
      apply(M, 2, function(x,v2) {
        sum(x==v)
      }, v2=v1)
    }
apply(mtcars, MARGIN = 2, closenessFunc, M=mtcars)

输出:

     mpg cyl disp hp drat wt qsec vs am gear carb
mpg   32   0    0  0    0  0    0  0  0    0    0
cyl    0  32    0  0    0  0    0  0  0    8    2
disp   0   0   32  0    0  0    0  0  0    0    0
hp     0   0    0 32    0  0    0  0  0    0    0
drat   0   0    0  0   32  0    0  0  0    1    0
wt     0   0    0  0    0 32    0  0  0    0    0
qsec   0   0    0  0    0  0   32  0  0    0    0
vs     0   0    0  0    0  0    0 32 19    0    7
am     0   0    0  0    0  0    0 19 32    0    4
gear   0   8    0  0    1  0    0  0  0   32    7
carb   0   2    0  0    0  0    0  7  4    7   32

改变

sum(duplicated(mtcars[,c(i,j), with = FALSE])==TRUE)

sum(mtcars[,i]==mtcars[,j])

重复的功能与您使用的方式不同。