0

I have an edge list like this

a   1
b   2
c   3
a   2
b   1

and I want to build it's incidence matrix which would be like:

    a   b   c   d
1   1   1   0   0
2   1   1   0   0
3   0   0   1   0
4   0   0   0   0

Any idea to do it?

TylerH
  • 19,065
  • 49
  • 65
  • 86
minoo
  • 451
  • 4
  • 18

2 Answers2

0

Using factor and add one more lvl

    df=read.table(text='A B
               a   1
               b   2
               c   3
               a   2
               b   1',header=T)

    levels(df$A)=c(levels(df$A),'d')
    df$B=as.factor(df$B)
    levels(df$B)=c(levels(df$B),'4')
    subset=table(df$B,df$A)

> subset

    a   b   c   d
1   1   1   0   0
2   1   1   0   0
3   0   0   1   0
4   0   0   0   0
BENY
  • 258,262
  • 17
  • 121
  • 165
  • Sorry and thank you for your time, but this is an example of a enormous network and is not applicable for large datasets. – minoo Jul 01 '17 at 14:20
  • 2
    Then can you explain your question a little bit more detail ? – BENY Jul 01 '17 at 14:57
  • @minoo [Here](https://solomonmessing.wordpress.com/2012/09/30/working-with-bipartiteaffiliation-network-data-in-r/) is an example of how to build a sparse matrix – lukeA Jul 01 '17 at 15:43
  • @Wen In my question types of the names of rows and columns are not important, just for each row of the data frame if mat[1,] and mat[,2] for example be in a row so in matrix we put 1 otherwise 0 and expand it for all inputs of the matrix – minoo Jul 02 '17 at 08:12
0
df<-cbind(df,1)

require(qdapTools)
incidence<-df[rep(seq_len(nrow(df)), df[,'1']), c('A', 'B')] %>%
{split(.[,'B'], .[,'A'])} %>%
  mtabulate()
minoo
  • 451
  • 4
  • 18