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,
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
>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With