代码之家  ›  专栏  ›  技术社区  ›  MoMo

激活/停用R中的循环

  •  1
  • MoMo  · 技术社区  · 5 年前

    我试图写一个函数来迭代两个变量(即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 .

    1 回复  |  直到 5 年前
        1
  •  2
  •   Hector Haffenden    5 年前

    试试这个,用一个 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 对于循环,但是对于每个 区域 ,将检查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语句移到 events for循环。。。等。。。

        2
  •  0
  •   MoMo    5 年前

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

    主代码已经进行了调整,可以处理这两种情况,因此在这方面没有问题。

    如果我的推理有什么问题,请告诉我。很抱歉,我没有解释清楚这个问题。