【问题标题】:Matching columns across matrices跨矩阵匹配列
【发布时间】:2018-01-21 11:27:24
【问题描述】:

假设我有两个或更多矩阵。矩阵的行数和列数相同。但矩阵不一定是正方形的。

Matrix1
     a        b        c
1    0.911    0.067    0.023
2    0.891    0.089    0.019
3    0.044    0.931    0.025
4    0.919    0.058    0.023

Matrix2
     a        b        c
1    0.024    0.070    0.906
2    0.020    0.090    0.891
3    0.025    0.930    0.045
4    0.024    0.058    0.918

行的总和始终为 1。列的位置可能会从一个矩阵转移到另一个矩阵。所以列名没有多大意义。上面的示例,mat 1 中的列“a”是 mat2 中的列“c”。该值将不相同但相似。

我可以使用哪种方法/算法来对齐许多此类矩阵中的列?

想要的结果如下所示

Matrix1
     a        b        c
1    0.911    0.067    0.023
2    0.891    0.089    0.019
3    0.044    0.931    0.025
4    0.919    0.058    0.023

Matrix2
     c        b        b
1    0.906    0.070    0.024
2    0.891    0.090    0.020
3    0.045    0.930    0.025
4    0.918    0.058    0.024

列对齐。 mat1 中的“a”对应于 mat2 中的“c”,依此类推。在这个可能的结果中,mat1 是参考,mat2 与之对齐。

如果有人想尝试,我正在使用 R。

mat1 <-
 matrix(c(0.911,0.891,0.044,0.919,0.067,0.089,0.931,0.058,0.023,0.019,0.025,0.023),nrow=4)
mat2 <-
 matrix(c(0.024,0.020,0.025,0.024,0.070,0.090,0.930,0.058,0.906,0.891,0.045,0.918),nrow=4)

【问题讨论】:

  • 请将所需结果显示为在许多此类矩阵中对齐列不清楚。
  • 基本上你想识别矩阵 2 中的列并将它们命名为矩阵 1 中最相似的列?
  • 我已编辑添加所需的结果。
  • 可能像mat2[,order(mat1[1,]- mat2[1,])] 或mat2[,max.col(-outer(mat1[1,], mat2[1,], function(i, j) abs(i-j)))] 一样简单

标签: r combinations permutation distance similarity


【解决方案1】:

你可以做这样的事情。该函数以与m.base 的列最匹配(按欧几里德距离)的顺序返回mat 的列索引。

col.order <- function(m.base, mat){
  no.cols <- ncol(mat)
  col.ord <- rep(NA, no.cols)
  for(i in 1:no.cols){
    vec <- m.base[, i]
    col.dists <- apply(mat, 2, function(x) sum((x-vec)^2))
    best.dist <- min(col.dists[is.na(col.ord)])
    best.col <- match(best.dist, col.dists)
    col.ord[best.col] <- i
  }
  return(col.ord)
}

mat2[, col.order(mat1,mat2)]

      [,1]  [,2]  [,3]
[1,] 0.906 0.070 0.024
[2,] 0.891 0.090 0.020
[3,] 0.045 0.930 0.025
[4,] 0.918 0.058 0.024

【讨论】:

    【解决方案2】:

    假设每列总是有一个很好的匹配,这应该可以工作。

    Matrix2[, sapply(1:ncol(Matrix1), 
         function(i) which.min(colSums(abs(Matrix2 - Matrix1[,i]))))]
          c     b     a
    1 0.906 0.070 0.024
    2 0.891 0.090 0.020
    3 0.045 0.930 0.025
    4 0.918 0.058 0.024
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多