如何在 R 中使用雏菊函数创建相异矩阵?
How to create a dissimilarity matrix with daisy function in R?
我想用 R 中的 pam
函数进行聚类分析,使用 daisy
创建相异矩阵。我的数据包含 2 列(ID 和疾病)。两者都是具有很多值的因子(分别为 400 和 1800)。如何创建需要使用 pam
对数据进行聚类的相异矩阵?
示例数据框:
set.seed(1)
df <- data.frame(ID = rep(sample(c("a","b","c","d","e","f","g"),10,replace = TRUE),70),
disease = sample(c("flu","headache","pain","inflammation","depression","infection","chest pain"),100,replace = TRUE))
df <- unique(df)
我可以 运行 这个数据框上的 daisy
函数还是必须将它转换成另一种格式?
由于 "Dissimilarities will be computed between the rows of x" (?daisy
),您可能希望 运行 daisy
在 table
你的数据框。
(df.tab <- table(df))
# disease
# ID chest pain depression flu headache infection inflammation pain
# a 1 1 1 1 1 1 1
# b 1 1 1 1 1 1 1
# c 1 1 0 0 1 1 1
# d 1 1 1 0 1 0 1
# e 0 1 1 1 1 1 0
# f 0 1 1 1 1 0 1
# g 1 1 1 1 1 1 0
library(cluster)
daisy(df.tab, metric="euclidean")
# Dissimilarities :
# a b c d e f
# b 0.000000
# c 1.414214 1.414214
# d 1.414214 1.414214 1.414214
# e 1.414214 1.414214 2.000000 2.000000
# f 1.414214 1.414214 2.000000 1.414214 1.414214
# g 1.000000 1.000000 1.732051 1.732051 1.000000 1.732051
#
# Metric : euclidean
# Number of objects : 7
我想用 R 中的 pam
函数进行聚类分析,使用 daisy
创建相异矩阵。我的数据包含 2 列(ID 和疾病)。两者都是具有很多值的因子(分别为 400 和 1800)。如何创建需要使用 pam
对数据进行聚类的相异矩阵?
示例数据框:
set.seed(1)
df <- data.frame(ID = rep(sample(c("a","b","c","d","e","f","g"),10,replace = TRUE),70),
disease = sample(c("flu","headache","pain","inflammation","depression","infection","chest pain"),100,replace = TRUE))
df <- unique(df)
我可以 运行 这个数据框上的 daisy
函数还是必须将它转换成另一种格式?
由于 "Dissimilarities will be computed between the rows of x" (?daisy
),您可能希望 运行 daisy
在 table
你的数据框。
(df.tab <- table(df))
# disease
# ID chest pain depression flu headache infection inflammation pain
# a 1 1 1 1 1 1 1
# b 1 1 1 1 1 1 1
# c 1 1 0 0 1 1 1
# d 1 1 1 0 1 0 1
# e 0 1 1 1 1 1 0
# f 0 1 1 1 1 0 1
# g 1 1 1 1 1 1 0
library(cluster)
daisy(df.tab, metric="euclidean")
# Dissimilarities :
# a b c d e f
# b 0.000000
# c 1.414214 1.414214
# d 1.414214 1.414214 1.414214
# e 1.414214 1.414214 2.000000 2.000000
# f 1.414214 1.414214 2.000000 1.414214 1.414214
# g 1.000000 1.000000 1.732051 1.732051 1.000000 1.732051
#
# Metric : euclidean
# Number of objects : 7