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

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

    You could do this:

    d <- function(distance, selection){
      eval(parse(text = paste("as.matrix(distance)[",
                   selection, "]")))
    }
    
    `d<-` <- function(distance, selection, value){
      eval(parse(text = paste("as.matrix(distance)[",
                   selection, "] <- value")))
      as.dist(distance)
    }
    

    Which would allow you to do this:

     mat <- matrix(1:12, nrow=4)
     mat.d <- dist(mat)
     mat.d
            1   2   3
        2 1.7        
        3 3.5 1.7    
        4 5.2 3.5 1.7
    
     d(mat.d, "3, 2")
        [1] 1.7
     d(mat.d, "3, 2") <- 200
     mat.d
              1     2     3
        2   1.7            
        3   3.5 200.0      
        4   5.2   3.5   1.7
    

    However, any changes you make to the diagonal or upper triangle are ignored. That may or may not be the right thing to do. If it isn't, you'll need to add some kind of sanity check or appropriate handling for those cases. And probably others.

提交回复
热议问题