How do I manipulate/access elements of an instance of “dist” class using core R?

前端 未结 12 2185
傲寒
傲寒 2021-02-02 10:50

A basic/common class in R is called \"dist\", and is a relatively efficient representation of a symmetric distance matrix. Unlike a \"matrix\" object,

12条回答
  •  南旧
    南旧 (楼主)
    2021-02-02 11:20

    There aren't standard ways of doing this, unfortunately. Here's are two functions that convert between the 1D index into the 2D matrix coordinates. They aren't pretty, but they work, and at least you can use the code to make something nicer if you need it. I'm posting it just because the equations aren't obvious.

    distdex<-function(i,j,n) #given row, column, and n, return index
        n*(i-1) - i*(i-1)/2 + j-i
    
    rowcol<-function(ix,n) { #given index, return row and column
        nr=ceiling(n-(1+sqrt(1+4*(n^2-n-2*ix)))/2)
        nc=n-(2*n-nr+1)*nr/2+ix+nr
        cbind(nr,nc)
    }
    

    A little test harness to show it works:

    dist(rnorm(20))->testd
    as.matrix(testd)[7,13]   #row

提交回复
热议问题