r - 在函数中添加停止条件作为 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
循环两次的情况下完成吗?
解决方案
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)
}
}
推荐阅读
- go - Go 没有将完整的数据写入文本文件
- optimization - 通过改变约束使约束优化变得可行
- javascript - 避免在 Raphael 中无意拖动
- sql - 在 SQL 中同时使用 AND 和 OR
- java - 在春季防止属性继承
- python - Python PyQt5 - 是否可以在 QTreeView 中添加要按下的按钮?
- javascript - 将天数增加到特定日期时出错
- java - 如何将多个文件写入 Android 设备上的用户可访问目录?
- python - 如何在不止一列上做熊猫样本?
- node.js - 如何从 MEAN 堆栈应用程序的组件 Ts 中的后端获取图像