R语言如何将停止条件设为函数入参且避免重复编写while循环
R语言循环多终止规则封装方案
核心思路是将while循环的停止条件做动态判定,仅保留一份循环体即可同时支持两种终止规则,还可扩展参数支持自定义阈值,避免硬编码。
优化后代码(基础版)
loop_func <- function(stopping_criteria = 'STEPS', threshold = 10) { n_iteration <- 1 time_elapsed <- 0 t1 <- Sys.time() # 动态判定循环终止条件,仅写一次循环体 while (if (stopping_criteria == 'TIME') time_elapsed <= threshold else n_iteration <= threshold) { t2 <- Sys.time() # 修正原时间计算逻辑:直接取当前时间与初始时间的差值,无需累加 time_elapsed <- as.numeric(difftime(t2, t1, units = "secs")) print(paste0('Time elapsed:', round(time_elapsed, 2), 's | Iteration no:', n_iteration)) n_iteration <- n_iteration + 1 } }
更高扩展性版本(switch实现)
如果后续需要新增其他终止规则,用switch写法更易维护:
loop_func <- function(stopping_criteria = 'STEPS', threshold = 10) { n_iteration <- 1 t1 <- Sys.time() while (switch(stopping_criteria, "TIME" = as.numeric(difftime(Sys.time(), t1, units = "secs")) <= threshold, "STEPS" = n_iteration <= threshold)) { time_elapsed <- as.numeric(difftime(Sys.time(), t1, units = "secs")) print(paste0('Time elapsed:', round(time_elapsed, 2), 's | Iteration no:', n_iteration)) n_iteration <- n_iteration + 1 } }
使用示例
- 按默认迭代次数运行(跑10次):
loop_func() - 按指定时长运行(跑10秒):
loop_func(stopping_criteria = "TIME") - 自定义迭代次数(跑20次):
loop_func(threshold = 20) - 自定义运行时长(跑5秒):
loop_func(stopping_criteria = "TIME", threshold = 5)
内容的提问来源于stack exchange,提问作者Shibaprasad
相关产品推荐
相关产品推荐

