转换“ dist”类的对象进入R中的数据帧 [英] convert object of class "dist" into data frame in r
本文介绍了转换“ dist”类的对象进入R中的数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果有可能将数据帧转换为 dist类的对象,是否有可能做相反的事情?将类 dist转换为数据框?例如
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(hasil)
< dist(hasil)
1 2 3 4
2 0.088814413
3 0.084929382 0.030413813
4 0.063245553 0.029120440 0.044418465
5 0.061983869 0.027018512 0.036400549 0.009055385
并在数据框中显示结果
<
col row distance
1 2 0.088814413
1 3 0.084929382
1 4 0.063245553
1 5 0.061983869
2 3 0.030413813
2 4 0.029120440
2 5 0.027018512
3 4 0.044418465
3 5 0.036400549
4 5 0.009055385
推荐答案
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
这篇关于转换“ dist”类的对象进入R中的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文