[R] Sum results in a matrix

Petr Savicky savicky at cs.cas.cz
Wed Mar 14 16:05:47 CET 2012


On Wed, Mar 14, 2012 at 02:28:22AM -0700, RMSOPS wrote:
> thank you
> 
>    It is working, a question in the wake of the array.
> 
> with the following code I am creating a data frame to store the data without
> repeating the code is working.
>    The question is the best way to do this process in R
> 
> tab<-NULL
> for(i in 1: nrow(res4))
> {
>   for(j in i:nrow(res4))
>   {
>     #print(paste(i,"-",j,"-",res4[i,j]))
>     temp<-data.frame(i,j,res4[i,j])
>     tab<-rbind(tab,temp)
>   }
> }

Hi.

Try the following.

  # create a matrix
  res4 <- matrix(1:12, nrow=3, ncol=4)
  d <- dim(res4)
  ind <- expand.grid(i=1:d[1], j=1:d[2])
  cbind(ind, res4=c(res4))

     i j res4
  1  1 1    1
  2  2 1    2
  3  3 1    3
  4  1 2    4
  5  2 2    5
  6  3 2    6
  7  1 3    7
  8  2 3    8
  9  3 3    9
  10 1 4   10
  11 2 4   11
  12 3 4   12

Hope this helps.

Petr Savicky.



More information about the R-help mailing list