首页 > 解决方案 > 激活/停用 R 中的循环

问题描述

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

我写了以下代码:

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.

标签: rloops

解决方案


试试这个,使用一个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
    }

  }
}

编辑

如果您不想复制代码两次,只需在regionfor 循环后添加 if 语句,但这会慢一点,因为对于 each region,将检查 if 语句....

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
    }
  }
}

如果再次,这会迫使您复制代码两次,如果您的区域代码嵌入了您的事件代码,则将 if 语句移动到eventsfor 循环中......等等......


推荐阅读