tags:

views:

77

answers:

3

Hi,

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,

+6  A: 

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.

JoFrhwld
worked like a charm.Thanks a lot
yO2gO
+3  A: 

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
> 
gd047
A: 

I'm guessing this is a weighted adjacency matrix for a graph. If so, you might be interested in the igraph package, to read the data as a weighted edge list.

Ken Williams