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.

Reply via email to