Tab Matrix Divided

I have a tab delimited file like

AB 0.5 AC 0.75 BD 0.2 

And I want to convert it to a square matrix, for example

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

How can I do this in R? Thanks,

+7
r
source share
3 answers

If you have 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 conversion functions.

+7
source share

Another approach (not as elegant as JoFrhwld's)

 df<- read.table(textConnection(" Var1 Var2 value AB 0.5 AC 0.75 BD 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 ABCD 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 > 
+3
source share

I assume this is a weighted adjacency matrix for the graph. If so, you might be interested in the igraph package to read the data as a list of weighted edges.

0
source share

All Articles