Search code examples
rfor-loopmatrixnested-loops

R:Save output for assigned variable in the nested for loop as a matrix


I have a nested for loop using two matrices M1 and M2 and I was able to get the output I want when I print it. As I have assigned another variable inside the for loop called 'y' to get my output, I'm not sure how I could save the final output in a matrix. These are my codes,

A<-c('a','a','a','b','b','b','c','c','c')
B<-c('a','b','c','a','b','c','a','b','c')
C<-c(0,1,2,1,0,3,2,3,0)
D<-data.frame(A,B,C)

library("reshape2")
M1<-acast(D, list(names(D)[1], names(D)[2]))
M2<-matrix(c(1000,800,500),nrow=3,ncol=1)

  for(i in 1:3)
  {
   for(j in 1:3)
   {
    y=0
     for(k in 1:3)
     {
      if(M1[i,k]<M1[i,j])
      {
       y=y+M2[k,1]
      }
     } 

     y=y-M2[i,1]
      if(y<0)
      {
        print(0)
      }
      else
      print(y)
    }
   }

I tried to define the output variable upfront and then assign to it.

  output<-matrix(0,9,1)

  for(i in 1:3)
  {
   for(j in 1:3)
   {
    y=0
     for(k in 1:3)
     {
      if(M1[i,k]<M1[i,j])
      {
       y=y+M2[k,1]
      }
     } 

     y=y-M2[i,1]
      if(y<0)
      {
        print(0)
      }
      else
      output[y]<-y
    }
   }

  output

When I assign like this, I get multiple NA values, zeros and some of the output values.

I'm new to for loop. Any help will be much appreciated.Thanks!


Solution

  • I was able to get the matrix I wanted by the below code

    output<-matrix(0,9,1)
    
    for(i in 1:3)
    {
     for(j in 1:3)
     {
      y=0
      for(k in 1:3)
      {
       if(M1[i,k]<M1[i,j])
       {
        y=y+M2[k,1]
       }
      } 
    
       y=y-M2[i,1]
       if(y<0)
       {
        output[j+(3*(i-1)),1]<-0
       }
       else
        output[j+(3*(i-1)),1]<-y
      }
     }
    
    View(output)