HI,
May be this helps: dat1<- read.table(text=" Col1 Col2 Weight A D 0.1 B C 0.4 C M 0.6 D P 0.8 E W 1 F D 1.2 G C 3.1 H M 4 ",sep="",header=TRUE,stringsAsFactors=FALSE) vec1<- c(unique(dat1[,1]),unique(dat1[,2])) datNew<- expand.grid(vec1,vec1) colnames(datNew)<- colnames(dat1)[-3] library(plyr) dat2<-join(datNew,dat1,type="left") dat2$Weight[is.na(dat2$Weight)]<-0 m1<-xtabs(Weight~Col1+Col2,data=dat2) library(igraph) g <- graph.adjacency(m1, mode="directed", weighted=TRUE, diag=TRUE) get.adjacency(g) #11 x 11 sparse Matrix of class "dgCMatrix" # [[ suppressing 11 column names ‘A’, ‘B’, ‘C’ ... ]] # #A . . . 1 . . . . . . . #B . . 1 . . . . . . . . #C . . . . . . . . 1 . . #D . . . . . . . . . 1 . #E . . . . . . . . . . 1 #F . . . 1 . . . . . . . #G . . 1 . . . . . . . . #H . . . . . . . . 1 . . #M . . . . . . . . . . . #P . . . . . . . . . . . #W . . . . . . . . . . . #or library(reshape2) m2<-dcast(dat2,Col1~Col2,value.var="Weight",fill=0) row.names(m2)<- m2[,1] m2<- as.matrix(m2[,-1]) g1 <- graph.adjacency(m2, mode="directed", weighted=TRUE, diag=TRUE) get.adjacency(g1) #11 x 11 sparse Matrix of class "dgCMatrix" # [[ suppressing 11 column names ‘A’, ‘B’, ‘C’ ... ]] # #A . . . 1 . . . . . . . #B . . 1 . . . . . . . . #C . . . . . . . . 1 . . #D . . . . . . . . . 1 . #E . . . . . . . . . . 1 #F . . . 1 . . . . . . . #G . . 1 . . . . . . . . #H . . . . . . . . 1 . . #M . . . . . . . . . . . #P . . . . . . . . . . . #W . . . . . . . . . . . A.K. ----- Original Message ----- From: rn27in . <[email protected]> To: [email protected] Cc: Sent: Friday, June 14, 2013 2:43 AM Subject: [R] Need help on creating Adjacency matrix in R Hello everyone I am relatively new to R and wanted some help on creating adjacency matrix I have a dataset as given below and wanted to create an adjacency matrix in R. For creating an adjacency matrix, the matrix should be a square matrix. I tried creating a matrix directly, but it would not be a square matrix. Can any one help me out with this problem. Thanks Rohit Col 1 Col 2 Weight A D 0.1 B C 0.4 C M 0.6 D P 0.8 E W 1 F D 1.2 G C 3.1 H M 4 [[alternative HTML version deleted]] ______________________________________________ [email protected] mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. ______________________________________________ [email protected] mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.

