简体   繁体   English

在R中的循环中替换矩阵中的行

[英]Replacing rows in a matrix in a loop in R

I am trying to write a simple Markov model in R. To generate the Markov trace I created a empty matrix with ncol=number of states, and nrow=number of cycles. 我试图在R中编写一个简单的马尔可夫模型。为了生成马尔可夫跟踪,我创建了一个空矩阵,其中ncol =状态数,nrow =循环数。 I am writing a function using a loop to replace each row of the matrix with each cycle, but the loop is failing me. 我正在使用循环编写函数,用每个循环替换矩阵的每一行,但是循环使我失败了。

Rounds<-function(cycles,TransMatrix){
  for (i in 1:nrow(MarkovTrace)){
    MarkovTrace[i+1,]<-as.vector(MarkovTrace[i,]%*%TransMatrix)
  }
}

Any thoughts on why this is? 有什么想法为什么呢? I am able to do this manually outside of the loop, though. 不过,我可以在循环外部手动执行此操作。

MarkovTrace[2,]<-as.vector(MarkovTrace[1,]%*%TransMatrix)
MarkovTrace[3,]<-as.vector(MarkovTrace[2,]%*%TransMatrix)

Many thanks! 非常感谢!

You can use <<- operator to affect a variable from outer scopes. 您可以使用<<-运算符从外部作用域影响变量。 However also consider a coding style that obviates this need as it will make your code more re-usable and easier to debug. 但是,也请考虑避免这种需要的编码样式,因为它将使您的代码更可重用且更易于调试。

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

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