激活/禁用R中的循环

时间:2019-04-24 20:13:10

标签: r loops

我正在尝试编写一个函数来迭代两个变量(即region和event)。但是,有时我需要应用该函数来分析每个区域的数据,而不必将其划分为事件。

我编写了以下代码:

myfunction <- function(a, b, c, events_included = FALSE){
  for(region in c("A1", "A2", "A3", "A4")){
    for (event in 1:30){


      # The main code (tweaked to deal with the both cases in
      # which events_included = FALSE and TRUE).

    }
  }
}

我想知道是否存在一种方法来停用变量events_included = FALSE的第二个循环(即事件)。

2 个答案:

答案 0 :(得分:2)

使用if语句尝试此操作。 您可以将if语句放在循环之外,因此它仅检查一次,这将根据regions的数量来加快代码的速度,然后您可以将代码复制过来...

myfunction <- function(a, b, c, events_included = FALSE){
  if (events_included){
    for(region in c("A1", "A2", "A3", "A4")){
      for (event in 1:30){
        # The main code (tweaked to deal with the both cases in
        # which events_included = FALSE and TRUE).
      }
    }
  } else {
    for(region in c("A1", "A2", "A3", "A4")){
        # Just region
    }

  }
}

修改

如果您不想复制两次代码,只需在region for循环之后添加if语句,但这对于每个region来说会有点慢声明将被检查。...

myfunction <- function(a, b, c, events_included = FALSE){
  for(region in c("A1", "A2", "A3", "A4")){
    if (events_included){
      for (event in 1:30){
        # The main code (tweaked to deal with the both cases in
        # which events_included = FALSE and TRUE).
      }

      # Put region stuff here
    }
  }
}

如果再次出现,这将迫使您复制两次代码,如果您的区域代码已嵌入事件代码,则将events内的if语句移入循环...等等...

答案 1 :(得分:0)

我认为我通过允许第二个循环只进行一次迭代找到了解决该问题的方法。我已将if (events_included == FALSE & event > 1) break添加到我的代码中,如下所示:

myfunction <- function(a, b, c, events_included = FALSE){
  for(region in c("A1", "A2", "A3", "A4")){
    for (event in 1:30){
      if (events_included == FALSE & event > 1) break


      # The main code (tweaked to deal with the both cases in
      # which events_included = FALSE and TRUE).

    }
  }
}

主代码已经过调整,可以在两种情况下都可以使用,因此在这方面没有问题。

请让我知道我的推理是否有任何问题。抱歉,因为我没有清楚地说明问题。