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

前端 未结 12 2116
傲寒
傲寒 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:26

    Converting to a matrix was also out of question for me, because the resulting matrix would be 35K by 35K, so I left it as a vector (result of dist) and wrote a function to find the place in the vector where the distance should be:

    distXY <- function(X,Y,n){
      A=min(X,Y)
      B=max(X,Y)
    
      d=eval(parse(text=
                   paste0("(A-1)*n  -",paste0((1:(A-1)),collapse="-"),"+ B-A")))
    
      return(d)
    
    }
    

    Where you provide X and Y, the original rows of the elements in the matrix from which you calculated dist, and n is the total number of elements in that matrix. The result is the position in the dist vector where the distance will be. I hope it makes sense.

提交回复
热议问题