【问题标题】:for loop with conditions only on every 5th iteration仅在每 5 次迭代时带有条件的 for 循环
【发布时间】:2018-02-20 16:32:27
【问题描述】:

我正在尝试创建一个 for 循环来更新矩阵以进行每次迭代,但我希望它在每 5 次迭代时做一些不同的事情。如何在不制作多个 if 语句的情况下实现这一点。基本上,我如何简化以包含仅适用于每 5 次迭代的 for 循环。

这是我的代码:

NCols=5
NRows=5 
mymat<-matrix(runif(NCols*NRows), ncol=NCols) 
matlist <- list()
matlist[[1]] <- mymat

days <- 50

for (i in 2:days){
        matlist[[i]] <- matlist[[i-1]]*2
        if (i == 5){
                matlist[[i]][2,2] <- matlist[[i]][2,2]+1
          }
}

【问题讨论】:

  • if (i %% 5 == 0) 怎么样?
  • 您知道for (i in 2:days){ matlist[[i]] &lt;- matlist[[i-1]]*2 ...etc...} 计算指数吗?
  • @RuiBarradas 是的,我试着举一个简单的例子。这不是一个实际的计算。谢谢。
  • 谢谢@ytu。如果您愿意,请使用您的评论作为答案!
  • 我刚刚在下面发布了我的答案。如果满足您的需要,请查看并考虑接受它。谢谢。

标签: r nested


【解决方案1】:

您可以将if 语句写为:每当 i 除以 5 的余数等于 0 时。

在您的代码中用if (i %% 5 == 0) 替换if (i == 5) 即可。

【讨论】:

    【解决方案2】:

    您的循环似乎从 2 开始,因此第一个第五次迭代将在 i=6 时进行。因此,基于此代码将是:-

    NCols=5
    NRows=5 
    mymat<-matrix(runif(NCols*NRows), ncol=NCols) 
    matlist <- list()
    matlist[[1]] <- mymat
    
    days <- 50
    
    for (i in 2:days){
            matlist[[i]] <- matlist[[i-1]]*2
            if (i-1 %% 5 == 0){
                    matlist[[i]][2,2] <- matlist[[i]][2,2]+1
            }
    }
    

    但是如果你想要 i = 5, 10, 15 ....n 等等 :-

    NCols=5
    NRows=5 
    mymat<-matrix(runif(NCols*NRows), ncol=NCols) 
    matlist <- list()
    matlist[[1]] <- mymat
    
    days <- 50
    
    for (i in 2:days){
            matlist[[i]] <- matlist[[i-1]]*2
            if (i %% 5 == 0){
                    matlist[[i]][2,2] <- matlist[[i]][2,2]+1
            }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-02-09
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      • 2018-02-13
      • 2013-11-27
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多