r - 激活/停用 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
.
解决方案
试试这个,使用一个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
for 循环后添加 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 语句移动到events
for 循环中......等等......
推荐阅读
- postgresql - 获取 AFTER TRUNCATE 触发器中受影响的行数的最简单方法是什么?
- python - flask wtf-forms SelectField 不断失败
- flow-project - 如何在流上使用 RL 算法?
- kdb - 查找列表列表中元素数量最多的列表
- python-3.x - 无法加载 Jupyter “ImportError:DLL 加载失败:找不到指定的模块。”
- r - 基于第一个和最后一个值的时间差
- javascript - 更新不相关的 Vue.js 变量导致模板中的输入值消失
- javascript - ReferenceError:运行 JEST 测试时未定义 cptable,错误在导入的模块中,而不是在我的代码中
- python - “tf.train.slice_input_producer()”的返回值是多少?
- c# - 如何使用字符串数组剪切 DataTable 的列?