[R] creating upper triangular matrix

arun smartpink111 at yahoo.com
Sun Nov 17 19:27:07 CET 2013


Hi,
May be this helps:

dat1 <- read.table(text="
data data freq
1       2     2
1       3     1
1       4     1
2       3     2
2       4     1
2       2     1
3      4       2",sep="",header=TRUE) 
val<- unique(c(dat1[,1],dat1[,2]))
dat2 <-expand.grid(data=val,data.1=val)
library(plyr)
library(reshape2)
res <- dcast(join(dat2,dat1),data~data.1,value.var="freq",fill=0)
row.names(res) <- res[,1]
res1 <- as.matrix(res[,-1])
diag(res1) <-0

#or
 m1 <- matrix(0,length(val),length(val),dimnames=list(val,val))

 indx1 <- outer(colnames(m1),rownames(m1),paste,sep="")
 indx2 <- paste0(dat1[,1],dat1[,2])
m1[match(indx2,indx1)] <- dat1[,3]
 diag(m1) <- 0
 m1
#  1 2 3 4
#1 0 2 1 1
#2 0 0 2 1
#3 0 0 0 2
#4 0 0 0 0

A.K.


Hello , 
I am working on a project , 
i need to create an upper triangular matrix from the data in this form; 
data data freq 
1       2     2 
1       3     1 
1       4     1 
2       3     2 
2       4     1 
2       2     1 
3      4       2 

 to a triangular matrix in the following form : 
     1   2    3   4 
1    0  2    1   1 
2    0  0    2   1 
3    0  0    0   2 
4    0  0    0   0 

i am new to R please help 




More information about the R-help mailing list