[英]define data.frame as a distance and perform hierarchical clustering in R
[英]How to convert data.frame into distance matrix for hierarchical clustering?
我有一個以距離矩陣格式定義的數據框:
> df
DA DB DC DD
DB 0.39 NA NA NA
DC 0.44 0.35 NA NA
DD 0.30 0.48 0.32 NA
DE 0.50 0.80 0.91 0.7
我想將其用作hclust
函數中的距離矩陣。 但是,當我嘗試將其轉換為dist
對象時,它會發生變化:
> as.dist(df)
DB DC DD
DC 0.44
DD 0.30 0.48
DE 0.50 0.80 0.91
您會看到DA
不再是矩陣的一部分。 如果我嘗試直接在hclust
使用df
,它將無法正常工作:
> hclust(d = df)
Error in if (is.na(n) || n > 65536L) stop("size cannot be NA nor exceed 65536") :
missing value where TRUE/FALSE needed
如何使用df
作為距離矩陣?
由於您將對象稱為df,因此我有點擔心它是data.frame而不是矩陣。 但是,好像它是矩陣一樣進行處理...
## creating your data
df = as.matrix(read.table(text="DA DB DC DD
0.39 NA NA NA
0.44 0.35 NA NA
0.30 0.48 0.32 NA
0.50 0.80 0.91 0.7",
header=TRUE))
您只需要給它零對角線。
DM = matrix(0, nrow=5, ncol=5)
DM[lower.tri(DM)] = df[lower.tri(df, diag=TRUE)]
as.dist(DM)
1 2 3 4
2 0.39
3 0.44 0.35
4 0.30 0.48 0.32
5 0.50 0.80 0.91 0.70
temp = as.vector(na.omit(unlist(df1)))
NM = unique(c(colnames(df1), row.names(df1)))
mydist = structure(temp, Size = length(NM), Labels = NM,
Diag = FALSE, Upper = FALSE, method = "euclidean", #Optional
class = "dist")
mydist
# DA DB DC DD
#DB 0.39
#DC 0.44 0.35
#DD 0.30 0.48 0.32
#DE 0.50 0.80 0.91 0.70
plot(hclust(mydist))
數據
df1 = structure(list(DA = c(0.39, 0.44, 0.3, 0.5), DB = c(NA, 0.35,
0.48, 0.8), DC = c(NA, NA, 0.32, 0.91), DD = c(NA, NA, NA, 0.7
)), .Names = c("DA", "DB", "DC", "DD"), class = "data.frame", row.names = c("DB",
"DC", "DD", "DE"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.