Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tab Delimited to Square Matrix

Tags:

r

I have a tab delimited file like

A   B   0.5
A   C   0.75
B   D   0.2

And I want to convert it to a square matrix, like

       A      B      C       D
A      0     0.5    0.75     0
B             0      0      0.2 
C                    0       0
D                            0

How can I go about it in R? Thanks,

like image 996
y2p Avatar asked Aug 04 '10 04:08

y2p


2 Answers

If you have the data in a data frame with the following column names:

Var1    Var2    value

you can use

xtabs(value ~ Var1 + Var2, data = df)

See the plyr package for some more general data reshaping functions also.

like image 107
JoFrhwld Avatar answered Oct 13 '22 13:10

JoFrhwld


Another approach (not as elegant as JoFrhwld's)

df<- read.table(textConnection("
Var1    Var2    value
A   B   0.5
A   C   0.75
B   D   0.2
"),header = T)


lev = unique(c(levels(df$Var1),levels(df$Var2)))
A = matrix(rep(0,length(lev)^2),nrow=length(lev))
colnames(A) = lev
rownames(A) = lev
apply(df,1,function(x) A[x[1],x[2]]<<-as.numeric(x[3]))

> A
  A   B    C   D
A 0 0.5 0.75 0.0
B 0 0.0 0.00 0.2
C 0 0.0 0.00 0.0
D 0 0.0 0.00 0.0
> 
like image 39
George Dontas Avatar answered Oct 13 '22 14:10

George Dontas