Make weighted edge list like pairs to data frame in R -


i have data set 3 columns.

x = c("x", "y", "z", "x", "y", "w") y = c("a", "b", "c" , "b", "a", "c") set.seed(3) z = sample(10,6) dat = data.frame(x, y, z) 

the dat looks like

 x y z 1 x 2 2 y b 8 3 z c 4 4 x b 3 5 y 9 6 w c 6 

i want transform above data format rows x , columns y , values in matrix z. want following:

      b    c x   2   3    0 y   9   8    0 z   0   0    4 w   0   0    6 

this similar edge list adjacency matrix, except data matrix not square. please help. thanks!

try

library(reshape2) acast(dat, x~y, value.var='z', fill=0) 

to rows in order expected result

acast(dat, factor(x, levels=unique(x))~y, value.var='z', fill=0) 

or @thelatemail commented

xtabs(z~x+y, data= dat)[unique(dat$x),] 

or modified version if both columns not in order

with(dat, xtabs(z ~ x + y)[unique(x), unique(y)]) 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -