【问题标题】:R Pairwise comparison of matrix columns ignoring empty valuesR忽略空值的矩阵列的成对比较
【发布时间】:2015-06-10 19:52:54
【问题描述】:

我有一个数组,我想为它获取每列中 之间相似性的度量。我的意思是我希望比较数组的成对列之间的行,并在它们的值匹配时增加一个度量。然后,对于完全相同的两列,得到的度量将处于最大值。

基本上我的问题与此处讨论的相同:R: Compare all the columns pairwise in matrix,只是我不希望计算空单元格。

使用从链接页面派生的代码创建的示例数据:

data1 <- c("", "B", "", "", "")
data2 <- c("A", "", "", "", "")
data3 <- c("", "", "C", "", "A")
data4 <- c("", "", "", "", "")
data5 <- c("", "", "C", "", "A")
data6 <- c("", "B", "C", "", "")

my.matrix <- cbind(data1, data2, data3, data4, data5, data6)

similarity.matrix <- matrix(nrow=ncol(my.matrix), ncol=ncol(my.matrix))
for(col in 1:ncol(my.matrix)){
  matches <- my.matrix[,col] == my.matrix
  match.counts <- colSums(matches)
  match.counts[col] <- 0 
  similarity.matrix[,col] <- match.counts

}

我得到:

similarity.matrix =

    V1  V2  V3  V4  V5  V6
1   0   3   2   4   2   4
2   3   0   2   4   2   2
3   2   2   0   3   5   3
4   4   4   3   0   3   3
5   2   2   5   3   0   3
6   4   2   3   3   3   0

计算非值对。

我想要的输出是:

expected.output =

    V1  V2  V3  V4  V5  V6
1   0   0   0   0   0   1
2   0   0   0   0   0   0
3   0   0   0   0   2   1
4   0   0   0   0   0   0
5   0   0   2   0   0   1
6   1   0   1   0   1   0

谢谢,

马特

【问题讨论】:

  • 你能显示预期的输出吗?尝试将'' 替换为NAis.na(matrix) &lt;- matrix=='' 并在您的循环中match.counts &lt;- colSums(matches, na.rm=TRUE)
  • 是的。我只是用我的真实数据检查。那你能把这个作为答案吗?
  • 我看不到了。我认为它已被删除。
  • 我看到了你的循环,但是对“相似性”的意思的口头解释会大大改善这个问题。我真的不认为指向另一个问题的链接可以替代这里的解释。顺便说一句,你可能不想调用任何东西 matrix,因为这是一个常用函数的名称。

标签: r matrix similarity


【解决方案1】:

所以下面是 akrun 的回答:

首先将空白单元格更改为 NA's

is.na(my.matrix) <- my.matrix==''

然后删除 match.counts 的 NA

similarity.matrix <- matrix(nrow=ncol(my.matrix), ncol=ncol(my.matrix))

for(col in 1:ncol(my.matrix)){
  matches <- my.matrix[,col] == my.matrix
  match.counts <- colSums(matches, na.rm=TRUE)
  match.counts[col] <- 0 
  similarity.matrix[,col] <- match.counts

}

这确实给了我想要的输出:

    V1  V2  V3  V4  V5  V6
1   0   0   0   0   0   1
2   0   0   0   0   0   0
3   0   0   0   0   2   1
4   0   0   0   0   0   0
5   0   0   2   0   0   1
6   1   0   1   0   1   0

谢谢。

【讨论】:

    猜你喜欢
    • 2013-11-24
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 2014-04-22
    • 2012-09-22
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    相关资源
    最近更新 更多