R:成对比较矩阵中的所有列 [英] R: Compare all the columns pairwise in matrix

查看:49
本文介绍了R:成对比较矩阵中的所有列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 41 行 6 列的矩阵.这就是第一部分的样子.

I have a matrix with 41 rows and 6 columns. This is how the first part looks like.

      X13  X15  X17  X19  X21  X23 
 [1,] "7"  "6"  "5"  "8"  "1"  "8" 
 [2,] "7"  "6"  "5"  "8"  "14" "3" 
 [3,] "7"  "6"  "1"  "3"  "12" "3" 
 [4,] "7"  "6"  "1"  "5"  "6"  "14"
 [5,] "2"  "6"  "1"  "5"  "16" "3" 
 [6,] "2"  "3"  "5"  "5"  "2"  "3" 
 [7,] "7"  "5"  "5"  "17" "7"  "3" 
 [8,] "7"  "2"  "5"  "2"  "2"  "14"
 [9,] "2"  "2"  "10" "10" "2"  "3" 
[10,] "2"  "2"  "10" "5"  "2"  "6" 

我的目标是,将所有列相互比较,看看有多少数字在两列中相等.我试着这样做:

My goal is, to compare all the columns with each other, and see, how many of the numbers are equal in the 2 columns. I tried to do it like this:

s <- sum(matrix[,1]==matrix[,2])

但是由于我需要比较所有可能的对,所以它无效.把它放在一个循环中会很好,但我不知道如何.

But since I need to compare all the possible pairs, it is not effective. It would be good to put this in a loop, but I have no idea how.

我想以 6x6 相似矩阵的形式得到我的结果.像这样:

And I would like to get my result in a form of a 6x6 similarity matrix. Something like this:

      X13 X15 X17 X19 X21 X23
 X13   0   0   3   2   2   3
 X15   0   0   9  11   4   6
 X17   3   9   0   5   1   3
 X19   2  11   5   0   9  10
 X21   2   4   1   9   0   9
 X23   3   6   3  10   9   0

如您所见,当将一列与 iteslf 进行比较时,我想在矩阵中置零.

As you see, I would like to put zeros to the matrix when a column is compared to iteslf.

由于我是 R 初学者,这个任务对我来说真的很复杂.我需要将此比较用于 50 个矩阵,因此如果您能帮助我,我会很高兴.我将不胜感激任何提示/建议.我的英语也不是很好,但我希望我能很好地解释我的问题.:)

Since I am a beginner R user, this task semms really complicated to me. I need to use this comparison to 50 matrixes, so I would be glad if you could help me. I would appreciate any tips/suggestions. My english is not so good either, but I hope I could explain my problem well enough. :)

推荐答案

一种非矢量化(但可能更节省内存)的方法:

A non-vectorized, (but perhaps more memory-efficient) way of doing this:

# Fancy way.
similarity.matrix<-apply(matrix,2,function(x)colSums(x==matrix))
diag(similarity.matrix)<-0


# More understandable. But verbose.
similarity.matrix<-matrix(nrow=ncol(matrix),ncol=ncol(matrix))
for(col in 1:ncol(matrix)){
  matches<-matrix[,col]==matrix
  match.counts<-colSums(matches)
  match.counts[col]<-0 # Set the same column comparison to zero.
  similarity.matrix[,col]<-match.counts
}

这篇关于R:成对比较矩阵中的所有列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆