[R] Insert null columns and rows into a matrix to make it square
arun
smartpink111 at yahoo.com
Sun Sep 1 03:25:19 CEST 2013
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
More information about the R-help
mailing list