简体   繁体   English

R:将嵌套循环中分配变量的输出保存为矩阵

[英]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. 我有一个使用两个矩阵M1和M2的嵌套for循环,在打印时可以得到想要的输出。 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. 由于我在for循环中分配了另一个变量“ y”来获取输出,因此我不确定如何将最终输出保存在矩阵中。 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. 当我这样分配时,我得到了多个NA值,零和一些输出值。

I'm new to for loop. 我是for循环的新手。 Any help will be much appreciated.Thanks! 任何帮助将不胜感激。谢谢!

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM