Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create binary relation matrix with R?

Tags:

r

matrix

I have a data.frame that looks like this.For example:

A;a 
B;a 
C;b 
D;c
A;b
A;d
C;c 

First pos = key , second pos = value. If key; value , then 1 ,if not then 0;

I would to create binary matrix from data, I would like to have this table format:

0 a b c d
A 1 1 0 1  
B 1 0 0 0
C 0 1 1 0
D 0 0 0 1

I could create matrix ,but not binary martix , because some lines are repeat My code:

 mydb2 <- structure(list(Key = c("A","B","C","D","E","A","A"), 
                   Value = c("b","c","e","a","f","g","g")), 
              .Names = c("", ""), class = "data.frame", 
              row.names = c(NA, -6L))
table(mydb2)

And out

enter image description here

how can I fix it?

like image 650
Dossanov Avatar asked Sep 04 '26 01:09

Dossanov


1 Answers

As @Wen pointed out in comments, read the data from file (containing no header line):

> t = read.table('test.txt',sep=';')
> t
  V1 V2
1  A  a
2  B  a
3  C  b
4  D  c
5  A  b
6  A  d
7  C  c

and use table command and convert it to binary matrix by updating all elements having values larger than 1 into value 1:

> t2 <- table(t$V1,t$V2)
> t2[t2 > 1] <- 1
> t2

    a b c d
  A 1 1 0 1
  B 1 0 0 0
  C 0 1 1 0
  D 0 0 1 0
like image 196
Heikki Avatar answered Sep 05 '26 15:09

Heikki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!