[R] creating upper triangular matrix

Bert Gunter gunter.berton at gene.com
Mon Nov 18 01:20:26 CET 2013


I believe matrix indexing makes Arun's complex code wholly unnececessary:

Starting with dat1 as above:

m <- matrix(0,4,4)
m[as.matrix(dat1[,1:2])] <- dat1[,3]

## yielding:
m

     [,1] [,2] [,3] [,4]
[1,]    0    2    1    1
[2,]    0    1    2    1
[3,]    0    0    0    2
[4,]    0    0    0    0

If you want to get rid of any nonzero diagonal entries:

diag(m) <- 0 ## does it.

Cheers,
Bert





On Sun, Nov 17, 2013 at 10:27 AM, arun <smartpink111 at yahoo.com> wrote:
> 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
>
>
> ______________________________________________
> R-help at 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.



-- 

Bert Gunter
Genentech Nonclinical Biostatistics

(650) 467-7374



More information about the R-help mailing list