从R中的距离矩阵中提取对角线

时间:2016-08-30 15:45:55

标签: r matrix distance diagonal distance-matrix

我想知道如何从距离矩阵中提取第一个对角线的值。

例如:

> mymatrix
     [,1] [,2]
[1,]    1    2
[2,]    3    4
[3,]    6    4
[4,]    8    6

> dist(mymatrix)

         1        2        3
2 2.828427                  
3 5.385165 3.000000         
4 8.062258 5.385165 2.828427

我想在矢量中输入值2.828427, 3.000000, 2.828427

谢谢!

2 个答案:

答案 0 :(得分:9)

一种解决方法是将<a id="div1OpenButton" class="openButton" onClick="openDiv(this)">div1</a> <script> function openDiv(e){ document.getElementById(e.innerHTML).style.width= '20px' } </script> 对象转换为dist,然后提取行索引比列索引大1的元素:

matrix

答案 1 :(得分:0)

一种看似复杂但非常有效的解决方案,用于提取“ dist”矩阵的第d 次对角线。

subdiag <- function (dist_obj, d) {
  if (!inherits(dist_obj, "dist")) stop("please provide a 'dist' object!")
  n <- attr(dist_obj, "Size")
  if (d < 1 || d > (n - 1)) stop(sprintf("'d' needs be between 1 and %d", n - 1L))
  j_1 <- c(0, seq.int(from = n - 1, by = -1, length = n - d - 1))
  subdiag_ind <- d + cumsum(j_1)
  dist_obj[subdiag_ind]
  }

有关“ dist”对象的打包存储的详细信息,请参见R - How to get row & column subscripts of matched elements from a distance matrix。在此函数内,j_1是第X 列中“ (j - 1)”的编号。 cumsum给出主要对角线的一维索引(其值均为零)。进一步偏移d可以得到d 次对角线的一维索引。

set.seed(0)
x <- dist(matrix(runif(10), 5))
#          1         2         3         4
#2 0.9401067                              
#3 0.9095143 0.1162289                    
#4 0.5618382 0.3884722 0.3476762          
#5 0.4275871 0.6968296 0.6220650 0.3368478

subdiag(x, 1)
#[1] 0.9401067 0.1162289 0.3476762 0.3368478

lapply(1:4, subdiag, dist_obj = x)
#[[1]]
#[1] 0.9401067 0.1162289 0.3476762 0.3368478
#
#[[2]]
#[1] 0.9095143 0.3884722 0.6220650
#
#[[3]]
#[1] 0.5618382 0.6968296
#
#[[4]]
#[1] 0.4275871

对于大到大的“ dist”矩阵都具有良好的性能。

## mimic a "dist" object without actually calling function `dist`
n <- 2000
x <- structure(numeric(n * (n - 1) / 2), class = "dist", Size = n)

library(bench)
bench::mark("Psidom" = {mat = as.matrix(x); mat[row(mat) == col(mat) + 1]},
            "zheyuan" = subdiag(x, 1))
## A tibble: 2 x 14
#  expression      min     mean  median      max `itr/sec` mem_alloc  n_gc n_itr
#  <chr>      <bch:tm> <bch:tm> <bch:t> <bch:tm>     <dbl> <bch:byt> <dbl> <int>
#1 Psidom        553ms    553ms   553ms 552.74ms      1.81   251.8MB     5     1
#2 zheyuan       106µs    111µs   108µs   3.85ms   9045.      62.7KB     2  4519
## ... with 5 more variables: total_time <bch:tm>, result <list>, memory <list>,
##   time <list>, gc <list>

subdiag的速度提高了5120倍(553ms / 108µs),存储效率提高了4112倍(251.8MB / 62.7KB)。