Search code examples
rfunctionif-statementblock

R - how to execute certain blocks of code based on a set of conditions without using functions?


this might be a really fundamental question but im struggling to find a straight answer. I have a certain criteria at the start of my script that would involve executing certain blocks of code dependent on some conditions with A and B being certain blocks of code.

If Condition 1 is true. Run A+B

If Condition 2 is true. Run A

If Condition 3 is true. Run B

The conditions above will be setup so that only one of the three will be true. I have considered making A and B into separate functions (that dont have input arguements and just run whats in that block) but from searching I believe that it isnt best practice to do that. Is there a better way to do this? Thanks

Edit - adding the info that I would only like to maintain code blocks A and B as one entity. I.e. not have to maintain multiple copies of A and B throughout the script using loops.


Solution

  • As I mentioned above, I think that you can use blocks based on the condition, assuming you set the variable cond to 1, 2, or 3 (corresponding to above), I think that you should be able to do the following without needing to either maintain code for A & B more than once or use functions using the pseudocode below:

    if(cond == 1 | cond == 2) {
       RUN CODE A HERE
    }
    if(cond == 1 | cond == 3) {
       RUN CODE B HERE
    }