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

前端 未结 4 1477
傲寒
傲寒 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:05

    library(maps)
    data(us.cities)
    
    d <- dist(head(us.cities[c("lat", "long")]))
    
    ##           1         2         3         4         5
    ## 2 20.160489                                        
    ## 3 23.139853 40.874243                              
    ## 4 15.584303  9.865374 38.579820                    
    ## 5 27.880674  7.882037 48.707100 15.189882          
    ## 6 26.331187 41.720457  6.900101 41.036931 49.328558
    
    library(reshape2)
    
    df <- melt(as.matrix(d), varnames = c("row", "col"))
    
    df[df$row > df$col,]
    ##    row col     value
    ## 2    2   1 20.160489
    ## 3    3   1 23.139853
    ## 4    4   1 15.584303
    ## 5    5   1 27.880674
    ## 6    6   1 26.331187
    ## 9    3   2 40.874243
    ## 10   4   2  9.865374
    ## 11   5   2  7.882037
    ## 12   6   2 41.720457
    ## 16   4   3 38.579820
    ## 17   5   3 48.707100
    ## 18   6   3  6.900101
    ## 23   5   4 15.189882
    ## 24   6   4 41.036931
    ## 30   6   5 49.328558
    

提交回复
热议问题