另一種方法是reshape::cast
df.long = data.frame(one=c('a','a','a','b','b','c'),
two=c('b','c','d','c','d','d'),
value=c(30,40,20,10,05,30))
# cast will recover the upper/lower-triangles...
df <- as.matrix(cast(df.long, one ~ two, fill=0))
# b c d
# a 30 40 20
# b 0 10 5
# c 0 0 30
所以我們構建矩陣全索引,並插入:
df <- matrix(nrow=length(indices), ncol=length(indices),dimnames = list(indices,indices))
diag(df) <- 0
# once we assure that the full upper-triangle is present and in sorted order (as Robert's answer does), then we
df[upper.tri(df)] <- as.matrix(cast(df.long, one ~ two, fill=0))
df[lower.tri(df)] <- df[upper.tri(df)]
UPDATE :原始草圖中包含這些手動卡012
那麼同樣的方法來添加缺少的行「d」和列「A」,並通過加入轉置T(DF)填充下三角:
df <- cbind(a=rep(0,4), rbind(df, d=rep(0,3)))
# a b c d
# a 0 30 40 20
# b 0 0 10 5
# c 0 0 0 30
# d 0 0 0 0
df + t(df)
# a b c d
# a 0 30 40 20
# b 30 0 10 5
# c 40 10 0 30
# d 20 5 30 0
您可能會發現在'功能daisy'如果你需要聚類分類變量,'cluster'軟件包很有用,例如'cutree(hclust(daisy(data)),k = 2)'返回矢量'1 1 1 2 2 1'。 –
請使用'dput()'發佈可再現的代碼示例。 – smci