gpt4 book ai didi

r - 将成对距离转换为 R 中的距离矩阵

转载 作者:行者123 更新时间:2023-12-02 16:58:26 24 4
gpt4 key购买 nike

我有成对距离,需要显示/转换为距离矩阵。 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])
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
<小时/>

@alexis_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

关于r - 将成对距离转换为 R 中的距离矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22492767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com