[R] Simplifying matrix computation

David Winsemius dwinsemius at comcast.net
Wed Jan 29 01:49:50 CET 2014


On Jan 27, 2014, at 8:04 AM, Carlo Giovanni Camarda wrote:

> Dear R-users,
> 
> I would like to know whether you know some trick for skipping some of 
> the steps in the example below (especially the last step in a way that 
> would make easier to be written succinctly in a text).
> 
> I could try to explain in words the whole process, but I'm sure the code 
> below would be clearer.

After looking at the code and output, I must disagree. The lack of any response from the rest of the readership suggests to me that I am not the only one who thinks a natural language description of the context and goals for this effort would help.

> 
> Thanks in advance for your help,
> Giancarlo
> 
> 
> ## data in matrices
> D <- matrix(1:15, 3, 5)
> T <- matrix(0, 3, 3)
> T[c(2,4,6,8)] <- 1
> 
> ## how to place the diag matrices of each row
> M0 <- matrix(0, nrow(T), sum(T))
> wr <- which(T==1, arr.ind=TRUE)[,2]
> wc <- 1:ncol(M0)
> M0[cbind(wr,wc)] <- 1
> 
> ## number of columns
> m <- ncol(D)
> ## non-zero positions
> M <- kronecker(M0, diag(m))
> ## which rows to take
> pos <- which(T==1, arr.ind=TRUE)[,1]
> ## filling up with data
> M[M!=0] <- t(D[wr,])
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> 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.

David Winsemius
Alameda, CA, USA




More information about the R-help mailing list