首页 > 解决方案 > 在函数中添加停止条件作为 R 中的输入参数

问题描述

我有类似以下循环的东西R,我可以在其中运行一段时间或迭代次数:

n_iteration <- 1

time_elapsed <-0
t1 <- Sys.time()

要在特定时间内运行它:

while (time_elapsed <= 10) {
  
  t2 <- Sys.time()
  time_elapsed <- time_elapsed + (t2-t1)
  print(paste0('Time elapsed:', time_elapsed, ' Iteration no:', n_iteration))
  
  n_iteration <- n_iteration+1
  
}

要运行多个循环:

while (n_iteration <= 10) {
  
  t2 <- Sys.time()
  time_elapsed <- time_elapsed + (t2-t1)
  print(paste0('Time elapsed:', time_elapsed, ' Iteration no:', n_iteration))
  
  n_iteration <- n_iteration+1
  
}

运行其中任何一个都可以解决问题。但是,如何将其包装在一个函数中,我可以在其中提及用于停止的标准?我想在不重复代码的情况下实现这一点。

我乏味且次优的方法:

loop_func <- function(stopping_criteria='STEPS') {
  n_iteration <- 1
  
  time_elapsed <-0
  t1 <- Sys.time()
  
  if(stopping_criteria=='TIME'){
    while (time_elapsed <= 10) {
      
      t2 <- Sys.time()
      time_elapsed <- time_elapsed + (t2-t1)
      print(paste0('Time elapsed:', time_elapsed, ' Iteration no:', n_iteration))
      
      n_iteration <- n_iteration+1
      
    }
  }else{
    while (n_iteration <= 10) {
      
      t2 <- Sys.time()
      time_elapsed <- time_elapsed + (t2-t1)
      print(paste0('Time elapsed:', time_elapsed, ' Iteration no:', n_iteration))
      
      n_iteration <- n_iteration+1
      
    }
  }
  
}

这可以在不复制while循环两次的情况下完成吗?

标签: rfunctionloops

解决方案


while您可以为循环编写另一个函数-

while_function <- function(x) {
  while (x <= 10) {
    t2 <- Sys.time()
    time_elapsed <- time_elapsed + (t2-t1)
    print(paste0('Time elapsed:', time_elapsed, ' Iteration no:', x))
    x <- x+1
    
  }
}

loop_func <- function(stopping_criteria='STEPS') {
  n_iteration <- 1
  time_elapsed <-0
  t1 <- Sys.time()
  if(stopping_criteria=='TIME'){
    while_function(time_elapsed)
  }else{
    while_function(n_iteration)
    }
}

推荐阅读