HI, You could try this: dat1<- read.table(text=" A B C D A 1 2 3 4 E 5 6 7 8 F 9 10 11 12 ",sep="",header=TRUE,stringsAsFactors=FALSE)
dat1$ID<-row.names(dat1) library(reshape2) dat1New<-melt(dat1,id.var="ID") dat2<- data.frame(expand.grid(ID=LETTERS[1:6],variable=LETTERS[1:6]),value=0) datM<-merge(dat1New,dat2,all=TRUE) res<-xtabs(value~ID+variable,data=datM) names(attr(res,"dimnames"))<-NULL res # A B C D E F #A 1 2 3 4 0 0 #B 0 0 0 0 0 0 #C 0 0 0 0 0 0 #D 0 0 0 0 0 0 #E 5 6 7 8 0 0 #F 9 10 11 12 0 0 #or res2<-dcast(datM,ID~variable,value.var="value",sum) row.names(res2)<- res2[,1] res2New<- res2[,-1] res2New # A B C D E F #A 1 2 3 4 0 0 #B 0 0 0 0 0 0 #C 0 0 0 0 0 0 #D 0 0 0 0 0 0 #E 5 6 7 8 0 0 #F 9 10 11 12 0 0 #or dat2<- expand.grid(ID=LETTERS[1:6],variable=LETTERS[1:6]) datM<-merge(dat1New,dat2,all=TRUE) dcast(datM,ID~variable,value.var="value",fill=0) # ID A B C D E F #1 A 1 2 3 4 0 0 #2 B 0 0 0 0 0 0 #3 C 0 0 0 0 0 0 #4 D 0 0 0 0 0 0 #5 E 5 6 7 8 0 0 #6 F 9 10 11 12 0 0 A.K. Hi, I wish to convert rectangular matrices such as this: A B C D A 1 2 3 4 E 5 6 7 8 F 9 10 11 12 into square ones with null rows and columns named with the missing names such as this: A B C D E F A 1 2 3 4 0 0 B 0 0 0 0 0 0 C 0 0 0 0 0 0 D 0 0 0 0 0 0 E 5 6 7 8 0 0 F 9 10 11 12 0 0 Could anyone give me a hand please. Thanks Mariki ______________________________________________ R-help@r-project.org 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.