R- Convert adjacency data frame to edgelist type list

别等时光非礼了梦想. 提交于 2019-12-24 14:15:53

问题


I need to change a data frame with named column and rows (NxN dimension) into an edge list.

For example the matrix in the data frame is:

     C1  C2  C3  C4
Ane  0   1   31  0
Jol  4   14  2   0
Ruf  3   3   11  6 
Rei  1   7    0  0

I want to change this to a list (like an edge list):

Ane-C1  0
Ane-C2  1
Ane-C3  31
Ane-C4  0
Jol-C1  4
Jol-C2  14
Jol-C3  2
Jol-C4  0
Ruf-C1  3
Ruf-C2  3
Ruf-C3  11
Ruf-C4  6
Rei-C1  1
Rei-C2  7
Rei-C3  0
Rei-C4  0

The other threads that I found seems to have only column names/ the data frame is not containing an adjacency matrix.

I tried to make it a graph and then get.edgelist, also tried [order(df[,1],df[1,]),,drop=FALSE] but those doesn't give what I want. Can anyone help teach me?


回答1:


In base R, replicate the rownames and column names, paste it, create a data.frame based on that along with the values of the matrix

data.frame(name = paste(rownames(m1)[col(m1)], colnames(m1)[row(m1)], sep="-"),
          val = c(t(m1)), stringsAsFactors = FALSE)
#     name val
#1  Ane-C1   0
#2  Ane-C2   1
#3  Ane-C3  31
#4  Ane-C4   0
#5  Jol-C1   4
#6  Jol-C2  14
#7  Jol-C3   2
#8  Jol-C4   0
#9  Ruf-C1   3
#10 Ruf-C2   3
#11 Ruf-C3  11
#12 Ruf-C4   6
#13 Rei-C1   1
#14 Rei-C2   7
#15 Rei-C3   0
#16 Rei-C4   0



回答2:


Here's a tidyverse solution. Use gather to convert from wide to long format. Then, unite the two columns into one.

library('tidyverse')

df <- data.frame(
  C1 = c(0, 4, 3, 1),
  C2 = c(1, 14, 3, 7),
  C3 = c(31, 2, 11, 0),
  C4 = c(0, 0, 4, 0),
  row.names = c('Ane', 'Jol', 'Ruf', 'Rei')
)

df %>%
  rownames_to_column %>%
  gather(key = 'key', value = 'value', -rowname) %>%
  unite('name', rowname, key, sep = '-')
#>      name value
#> 1  Ane-C1     0
#> 2  Jol-C1     4
#> 3  Ruf-C1     3
#> 4  Rei-C1     1
#> 5  Ane-C2     1
#> 6  Jol-C2    14
#> 7  Ruf-C2     3
#> 8  Rei-C2     7
#> 9  Ane-C3    31
#> 10 Jol-C3     2
#> 11 Ruf-C3    11
#> 12 Rei-C3     0
#> 13 Ane-C4     0
#> 14 Jol-C4     0
#> 15 Ruf-C4     4
#> 16 Rei-C4     0


来源:https://stackoverflow.com/questions/48297723/r-convert-adjacency-data-frame-to-edgelist-type-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!