Reputation: 331
I am trying to write a function to iterate over two variables (i.e. region and event). However, sometimes I need to apply the function to analyse the data of each whole region without dividing it into events.
I wrote the following code:
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).
}
}
}
I wonder if there is a way to deactivate the second loop (i.e. event) if the variable events_included = FALSE
.
Upvotes: 1
Views: 161
Reputation: 331
I think that I found a solution to the issue by allowing the second loop to do only one iteration. I have added if (events_included == FALSE & event > 1) break
to my code as shown below:
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).
}
}
}
The main code is already tweaked to work with both cases so there is no problem in that regard.
Please let me know if there is any problem with my reasoning. And sorry because I did not explain the issue clearly.
Upvotes: 0
Reputation: 1369
Try this, using an if
statement.
You could put the if statement outside the loop, so it only checks once, this will speed up your code depending on the number of regions
then you can just copy the code over...
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
}
}
}
Edit
If you don't want to have to copy the code twice, just add the if statement after the region
for loop, but this will be a bit slower as for every region
, an if statement will been to be checked....
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 again, this forces you to copy code twice, if your region code is embedded with you events code, move the if statement inside the events
for loop... etc...
Upvotes: 2