0

I want to turn a matrix into a long data.frame edge list of rows to columns like this:

  set.seed(666)
  mat <- matrix(sample(0:1,12,replace=TRUE),nrow=3)
  library(bipartite)
  as.data.frame(web2edges(mat, return = TRUE))

but i want names of the rows and columns to be in the output for the row and col columns not the number of the row.

but when i try this i get a duplicate row name error:

set.seed(666)
mat <- matrix(sample(0:1,12,replace=TRUE),nrow=3)
colnames(mat) <- letters[1:4]
rownames(mat) <- letters[5:7] 
library(bipartite)
as.data.frame(web2edges(mat, return = TRUE))

Error in data.frame(row = c("1", "3", "3", "1", "2"), col = c("4", "4", : duplicate row.names: g, e

Is there another easy way this can be achieved without using web2edges?

user1320502
  • 2,510
  • 5
  • 28
  • 46
  • 2
    Maybe set the rownames of the `web2edges()` result to NULL, then convert to a data.frame? Or just do `as.data.frame.table(mat)` straight up and then subset. – thelatemail Feb 05 '15 at 23:37
  • i like the table and subset option, @thelatemail if you want to answer I'd happily accept. – user1320502 Feb 06 '15 at 14:16
  • 1
    Possible duplicate of [Convert from n x m matrix to long matrix in R](http://stackoverflow.com/questions/30367922/convert-from-n-x-m-matrix-to-long-matrix-in-r) – rafa.pereira Apr 21 '17 at 14:24

1 Answers1

0

Data frames, unlike matrices, cannot have duplicate row names. So rather than changing the row and column names before web2edges, you will have to do it afterwards.

set.seed(666)
mat <- matrix(sample(0:1,12,replace=TRUE),nrow=3)
library(bipartite)

#data frame with numerical values in `row` and `col` columns:
ndf <- as.data.frame(web2edges(mat, return = TRUE))

#converting `row` and `col` columns to factors:
ndf$col <- factor(ndf$col, levels = 4:7, labels = letters[1:4])
ndf$row <- factor(ndf$row, levels = 1:3, labels = letters[5:7])

> ndf
  row col edge.weights
1   e   a            1
2   g   a            1
3   g   b            1
4   e   c            1
5   f   d            1
Curt F.
  • 4,690
  • 2
  • 22
  • 39