These elaborate manipulations are unnecessary and inefficient. Use indexing
instead:

j <- 2*seq_len(nrow(A)/2)
b <- A[j,]*A[j-1,]
b
[,1] [,2] [,3]
[1,]    4   10   18
[2,]   63   64   63
[3,]   18   10    4

     [,1] [,2] [,3]
[1,]    4   10   18
[2,]   63   64   63
[3,]   18   10    4


     [,1] [,2] [,3]
[1,]    4   10   18
[2,]   63   64   63
[3,]   18   10    4

     [,1] [,2] [,3]
[1,]    4   10   18
[2,]   63   64   63
[3,]   18   10    4


     [,1] [,2] [,3]
[1,]    4   10   18
[2,]   63   64   63
[3,]   18   10    4





On Mon, Sep 2, 2013 at 7:25 AM, arun <smartpink...@yahoo.com> wrote:

> Hi,
> You could try:
>
> A<- matrix(unlist(read.table(text="
> 1 2 3
> 4 5 6
> 7 8 9
> 9 8 7
> 6 5 4
> 3 2 1
> ",sep="",header=FALSE)),ncol=3,byrow=FALSE,dimnames=NULL)
>
> library(matrixStats)
>
>  res1<-t(sapply(split(as.data.frame(A),as.numeric(gl(nrow(A),2,6))),colProds))
>  res1
> #  [,1] [,2] [,3]
> #1    4   10   18
> #2   63   64   63
> #3   18   10    4
>
>
>
>  
> res2<-t(sapply(split(as.data.frame(A),((seq_len(nrow(A))-1)%/%2)+1),colProds))
>  identical(res1,res2)
> #[1] TRUE
>
> #or
>  t(sapply(split(as.data.frame(A),as.numeric(gl(nrow(A),2,6))),function(x)
> apply(x,2,prod)))
>
> #or
> library(plyr)
>
>  
> as.matrix(ddply(as.data.frame(A),.(as.numeric(gl(nrow(A),2,6))),colProds)[,-1])
> #     V1 V2 V3
> #[1,]  4 10 18
> #[2,] 63 64 63
> #[3,] 18 10  4
>
> #or
> do.call(rbind,tapply(seq_len(nrow(A)),list(as.numeric(gl(nrow(A),2,6))),FUN=function(x)
> colProds(A[x,])))
> #or
> A1<- data.frame(A,ID=as.numeric(gl(nrow(At),2,6)))
>  aggregate(A1[,-4],list(A1[,4]),colProds)[,-1]
> #  X1 X2 X3
> #1  4 10 18
> #2 63 64 63
> #3 18 10  4
>
> #or
> library(data.table)
> At<- data.table(A1,key='ID')
> subset(At[,lapply(.SD,colProds),by=ID],select=-1)
> #   X1 X2 X3
> #1:  4 10 18
> #2: 63 64 63
> #3: 18 10  4
>
> A.K.
>
>
>
>
> Hello,
>
> I have this matrix :
> A =
> 1 2 3
> 4 5 6
> 7 8 9
> 9 8 7
> 6 5 4
> 3 2 1
>
> I would like to have this matrix (product of rows 2 by 2) :
> A =
> 4 10 18
> 63 64 63
> 18 10 4
>
> Is it possible to do that without a loop ?
>
> Thank you in advance !
>
> ______________________________________________
> R-help@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

Internal Contact Info:
Phone: 467-7374
Website:
http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-biostatistics/pdb-ncb-home.htm

        [[alternative HTML version deleted]]

______________________________________________
R-help@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.

Reply via email to