[R] Creating x*y different contigency tables

Berend Hasselman bhh at xs4all.nl
Wed Sep 26 13:48:35 CEST 2012


On 26-09-2012, at 09:59, Loukia Spineli <spineliloukia26 at gmail.com> wrote:

> Dear all,
> 
> I am trying to construct  25x31 different matrices of 2x2 dimension. Here
> is the problem:
> 
> we have the following matrix
>                                                       matrix(c(54+s0,
> 43+s1, 56-s0, 67-s1), nrow=2, ncol=2, byrow=T)
> 
> the values for s0 and s1 are c(0:24) and c(0:31), respectively.
> 
> I wrote the following code without the desired results
> 
>                                            x<-0:24
>                                            y<-0:30
> 
>  results<-array(matrix(0,nrow=2,ncol=2,byrow=T),dim=c(2,2,25*31))
>                                                   for(i in 1:25){
>                                                        for(j in 1:31){
>                                                             for(k in
> 1:25*31){
> 
> results[,,k]<-array(matrix(c(54+x[i], 43+y[j], 56-x[i],
> 67-y[j]),nrow=2,ncol=2,byrow=T),dim=c(2,2,25*31))
>                                                             }
>                                                         }
>                                                     }
>                                                     results
> 
> I am trying to figure out what I am missing.

You don't need the third loop for( k in …
With for loops you can do this

x<-0:3
y<-0:5

mat.start <-  matrix(c(54, 43, 56, 67), nrow=2, ncol=2, byrow=T)
mat.start

Nx <- length(x)
Ny <- length(y)

results<-array(matrix(0,nrow=2,ncol=2,byrow=T),dim=c(2,2,Nx*Ny))    
k <- 1
for(i in 1:Nx){
    for(j in 1:Ny){
        results[,,k] <- mat.start + matrix(c(x[i], y[j], -x[i],-y[j]),nrow=2,ncol=2,byrow=T)
        k <- k+1
    }
}
results

Berend




More information about the R-help mailing list