convert object of class “dist” into data frame in r

前端 未结 4 1473
傲寒
傲寒 2021-02-04 14:43

if possible to convert a data frame to an object of class \"dist\" is it possible to do just the opposite? convert class \"dist\" to data frame? for example

< dist(ha

4条回答
  •  执念已碎
    2021-02-04 15:04

    Here's another approach that avoids melt() and as.matrix() ... it'd be nice to avoid subset() too, but I'll leave that as a homework exercise

    dist.to.df <- function(d){
      size <- attr(d, "Size")
      return(
        data.frame(
          subset(expand.grid(row=2:size, col=1:(size-1)), row > col),
          distance=as.numeric(d),
          row.names = NULL
        )
      )
    }
    

    which gives...

    library(maps)
    data(us.cities)
    d <- dist(head(us.cities[c("lat", "long")]))
    dist.to.df(d)
    ##    row col  distance
    ## 1    2   1 20.160489
    ## 2    3   1 23.139853
    ## 3    4   1 15.584303
    ## 4    5   1 27.880674
    ## 5    6   1 26.331187
    ## 6    3   2 40.874243
    ## 7    4   2  9.865374
    ## 8    5   2  7.882037
    ## 9    6   2 41.720457
    ## 10   4   3 38.579820
    ## 11   5   3 48.707100
    ## 12   6   3  6.900101
    ## 13   5   4 15.189882
    ## 14   6   4 41.036931
    ## 15   6   5 49.328558
    

提交回复
热议问题