[R] Insert null columns and rows into a matrix to make it square
arun
smartpink111 at yahoo.com
Sun Sep 1 03:44:48 CEST 2013
HI,
Without converting to data.frame, you can also try:
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)
mat1<- as.matrix(dat1)
names1<-unique(c(colnames(mat1),rownames(mat1)))
mat2<- matrix(0,length(names1),length(names1),dimnames=list(names1,names1))
vec1<-paste0(colnames(mat1)[col(mat1)],rownames(mat1)[row(mat1)])
vec2<- paste0(colnames(mat2)[col(mat2)],colnames(mat2)[row(mat2)])
mat2[match(vec1,vec2)]<- mat1
mat2
# 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
A.K.
----- Original Message -----
From: arun <smartpink111 at yahoo.com>
To: R help <r-help at r-project.org>
Cc:
Sent: Saturday, August 31, 2013 9:25 PM
Subject: Re: Insert null columns and rows into a matrix to make it square
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