将成对距离转换为R中的距离矩阵 [英] Converting pairwise distances into a distance matrix in R

查看:788
本文介绍了将成对距离转换为R中的距离矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有成对的距离,我需要显示/转换成一个距离矩阵。 R应该有一个功能,但我不知道哪一个或如何使用相同。我的资料如下所示

  A1 A1 0.90 
A1 B1 0.85
A1 C1 0.45
A1 D1 0.96
B1 B1 0.90
B1 C1 0.85
B1 D1 0.56
C1 C1 0.55
C1 D1 0.45
D1 D1 0.90

我想转换/显示如下

  A1 B1 C1 D1 
A1 0.90 0.85 0.45 0.96
B1 0.90 0.85 0.56
C1 0.55 0.45
D1 0.90

我该怎么办?谢谢

解决方案

您可以使用 reshape

  df<  -  read.table(textConnection(
A1 A1 0.90
A1 B1 0.85
A1 C1 0.45
A1 D1 0.96
B1 B1 0.90
B1 C1 0.85
B1 D1 0.56
C1 C1 0.55
C1 D1 0.45
D1 D1 0.90 )

dfr< - reshape(df,direction =wide,idvar =V2,timevar =V1)
dfr
#V2 V3.A1 V3.B1 V3.C1 V3.D1
#1 A1 0.90 NA NA NA
#2 B1 0.85 0.90 NA NA
#3 C1 0.45 0.85 0.55 NA
#4 D1 0.96 0.56 0.45 0.9

d < - as.dist(dfr [,-1])$ ​​b $ bd
#1 2 3
#2 0.85
#3 0.45 0.85
#4 0.96 0.56 0.45

#重置标签
attr(d,Labels)< - dfr [,1]
d
#A1 B1 C1
#B1 0.85
#C1 0.45 0.85
#D1 0.96 0.56 0.45






@ale提到的解决方案xis_laz似乎更优雅:

  as.dist(xtabs(df [,3]〜df [,2] + df [,1]))
#A1 B1 C1
#B1 0.85
#C1 0.45 0.85
#D1 0.96 0.56 0.45
/ pre>

I have pairwise distances that I need to display/convert into a distance matrix. R should have a function for this but I am not sure which one or how to use the same. My data looks like below

A1  A1  0.90
A1  B1  0.85
A1  C1  0.45
A1  D1  0.96
B1  B1  0.90
B1  C1  0.85
B1  D1  0.56
C1  C1  0.55
C1  D1  0.45
D1  D1  0.90

I want to convert/display it as below

      A1      B1      C1      D1
A1    0.90    0.85    0.45    0.96
B1            0.90    0.85    0.56
C1                    0.55    0.45
D1                            0.90

What should I do? Thanks

解决方案

You could use reshape:

df <- read.table(textConnection("
A1  A1  0.90
A1  B1  0.85
A1  C1  0.45
A1  D1  0.96
B1  B1  0.90
B1  C1  0.85
B1  D1  0.56
C1  C1  0.55
C1  D1  0.45
D1  D1  0.90"))

dfr <- reshape(df, direction="wide", idvar="V2", timevar="V1")
dfr
#   V2 V3.A1 V3.B1 V3.C1 V3.D1
# 1 A1  0.90    NA    NA    NA
# 2 B1  0.85  0.90    NA    NA
# 3 C1  0.45  0.85  0.55    NA
# 4 D1  0.96  0.56  0.45   0.9

d <- as.dist(dfr[, -1])
d
#      1    2    3
# 2 0.85          
# 3 0.45 0.85     
# 4 0.96 0.56 0.45

# reset labels
attr(d, "Labels") <- dfr[, 1]
d
#      A1   B1   C1
# B1 0.85          
# C1 0.45 0.85     
# D1 0.96 0.56 0.45


The solution mentioned by @alexis_laz seems to be more elegant:

as.dist(xtabs(df[, 3] ~ df[, 2] + df[, 1]))
#      A1   B1   C1
# B1 0.85          
# C1 0.45 0.85     
# D1 0.96 0.56 0.45

这篇关于将成对距离转换为R中的距离矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆