R中数据帧对的距离矩阵

时间:2014-01-17 07:45:12

标签: r matrix

我在R中有跟随距离矩阵。

              s1           s2           s3           s4           s5           s6           s7           s8           s9
s2   624667.8824                                                                                                        
s3   618711.2948  526120.6529                                                                                           
s4  1023257.9362 1006497.8847 1025400.5256                                                                              
s5   628679.9303  585435.1935  559319.5066 1031703.3141                                                                 
s6  1023252.3053 1006489.4853 1025393.0225     156.4817 1031695.9148                                                    
s7  1023263.1482 1006500.0433 1025404.4117     152.3829 1031707.4551     131.4696                                       
s8   619143.6849  557422.9677  513802.7576 1026714.3103  472012.4235 1026706.2563 1026718.1619                          
s9  1023282.3175 1006518.0410 1025422.0552     196.2825 1031727.5514     158.4078     159.3760 1026737.7122             
s10  610640.0380  532209.9671  519005.5448 1019135.5176  561862.4551 1019128.4830 1019139.1512  516171.7835 1019158.3403

如何以最有效的方式将上面的矩阵转换为数据帧,如下所示(带行标题)。

s1,s2   624667.8824
s1,s3   618711.2948
s1,s4   1023257.9362
s1,s5   628679.9303
.
.
.
s9,s10  1019158.3403

2 个答案:

答案 0 :(得分:4)

library(reshape2)
mdat <- matrix(c(1,2,3, 11,12,13), nrow = 2, ncol = 3, byrow = TRUE,
               dimnames = list(c("row1", "row2"),
                               c("C.1", "C.2", "C.3")))
melt(mdat)

输出 -

> melt(mdat)
  Var1 Var2 value
1 row1  C.1     1
2 row2  C.1    11
3 row1  C.2     2
4 row2  C.2    12
5 row1  C.3     3
6 row2  C.3    13

答案 1 :(得分:0)

调用距离矩阵d

f <- function(i) {
  c1 <- paste(colnames(d)[i],rownames(d)[i:nrow(d)],sep=",")
  c2 <- d[i:nrow(d),i]
  return(cbind(c1,c2))
}
result <- do.call(rbind,lapply(1:9,f))
result <- data.frame(result)
head(result)
#      c1           c2
# 1 s1,s2  624667.8824
# 2 s1,s3  618711.2948
# 3 s1,s4 1023257.9362
# 4 s1,s5  628679.9303
# 5 s1,s6 1023252.3053
# 6 s1,s7 1023263.1482

如果您如此倾向,可以使用匿名函数将所有这些放入一个语句中:

result=data.frame(do.call(rbind, lapply(1:9,function(i){
         cbind(paste0(colnames(d)[i],",",rownames(d)[i:nrow(d)]),
               d[i:nrow(d),i])})))