将邻接矩阵转换为R中的两列表

时间:2018-10-26 05:34:10

标签: r adjacency-matrix

我有以下邻接矩阵。我想将其隐藏到R中的两列表中。可重现的示例包括:

            Village_A   Village_B   Village_C   Village_D   Village_E
Village_A   438          507         157         166         832
Village_B   285          887         116         758         244
Village_C   935          459         217         561         550
Village_D   151          606         202         869         169
Village_E   572          362         416         899         510

我想将其隐藏为两列表,如下所示:

Village_A   Village_A   438
Village_B   Village_A   285
Village_C   Village_A   935
Village_D   Village_A   151
Village_E   Village_A   572
Village_A   Village_B   507
Village_B   Village_B   887
Village_C   Village_B   459
Village_D   Village_B   606
Village_E   Village_B   362
Village_A   Village_C   157
Village_B   Village_C   116
Village_C   Village_C   217
Village_D   Village_C   202
Village_E   Village_C   416
Village_A   Village_D   166
Village_B   Village_D   758
Village_C   Village_D   561
Village_D   Village_D   869
Village_E   Village_D   899
Village_A   Village_E   832
Village_B   Village_E   244
Village_C   Village_E   550
Village_D   Village_E   169
Village_E   Village_E   510

2 个答案:

答案 0 :(得分:0)

#temptable.txt:
##Village_A   Village_B   Village_C   Village_D   Village_E
##Village_A   438          507         157         166         832
##Village_B   285          887         116         758         244
##Village_C   935          459         217         561         550
##Village_D   151          606         202         869         169
##Village_E   572          362         416         899         510
data <- read.delim("temptable.txt",sep="")
crossdata <- lapply(rownames(data),function(x)sapply(colnames(data),function(y)list(x,y,data[x,y])))
crossdatatmp <- matrix(unlist(crossdata),nrow=3)
crossdatamat <- t(crossdatatmp)
colnames(crossdatamat) <- c("From","To","Value")
crossdatadf <- as.data.frame(crossdatamat,stringsAsFactors=F)
crossdatadf[,3] <- as.numeric(crossdatadf[,3])
crossdatadf
##        From        To Value
##1  Village_A Village_A   438
##2  Village_A Village_B   507
##3  Village_A Village_C   157
##4  Village_A Village_D   166
##5  Village_A Village_E   832
## ...

答案 1 :(得分:0)

看看gather中的tidyr函数。 您想做类似的事情(假设df是您数据框的名称):

gather(df, "Village_A", "Village_B", "Village_C", "Village_D", "Village_E", key = "village_2", value = "value")