0
0
R Programmingprogramming~10 mins

If-else statements in R Programming - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - If-else statements
Evaluate condition
Is condition TRUE?
NoExecute else block
Yes
Execute if block
End
The program checks a condition. If true, it runs the 'if' part; if false, it runs the 'else' part, then continues.
Execution Sample
R Programming
x <- 7
if (x > 5) {
  result <- "big"
} else {
  result <- "small"
}
Checks if x is greater than 5; assigns 'big' if true, otherwise 'small'.
Execution Table
StepCondition (x > 5)ResultBranch TakenVariable 'result'
17 > 5TRUEif block"big"
2End of if-else--"big"
💡 Condition is TRUE, so 'if' block runs and 'result' is set to 'big'.
Variable Tracker
VariableStartAfter Step 1Final
x777
resultundefined"big""big"
Key Moments - 2 Insights
Why does the else block not run when x is 7?
Because the condition x > 5 is TRUE at step 1, so the if block runs and the else block is skipped.
What happens if the condition is FALSE?
The else block runs instead, setting 'result' to 'small' as shown by the branch taken in the execution table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'result' after step 1?
A"big"
B"small"
Cundefined
D7
💡 Hint
Check the 'Variable result' column in row for step 1 in the execution table.
At which step does the program decide which branch to take?
AStep 2
BStep 1
CBefore Step 1
DAfter Step 2
💡 Hint
Look at the 'Condition' and 'Branch Taken' columns in the execution table.
If x was 3 instead of 7, what would 'result' be after step 1?
Aundefined
B"big"
C"small"
D3
💡 Hint
Think about the condition x > 5 and which branch runs when it is FALSE.
Concept Snapshot
If-else statements in R:
if (condition) {
  # code if TRUE
} else {
  # code if FALSE
}
Runs one block based on condition truth.
Useful for decision making.
Full Transcript
This visual execution shows how an if-else statement works in R. The program checks if x is greater than 5. Since x is 7, the condition is TRUE, so it runs the 'if' block and sets result to 'big'. The else block is skipped. Variables x and result are tracked before and after execution. Key moments clarify why the else block does not run and what happens if the condition is false. The quiz tests understanding of variable values and branch decisions based on the execution table.