开发者

Tab Delimited to Square Matrix

开发者 https://www.devze.com 2023-01-10 07:27 出处:网络
I have a tab delimited file like AB0.5 AC0.75 BD0.2 And I want to convert it to a square matrix, like ABCD

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.开发者_JAVA百科5    0.75     0
B             0      0      0.2 
C                    0       0
D                            0

How can I go about it in R? Thanks,


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.


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
> 


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消