Concept Flow - Logical indexing
Start with vector
Create logical condition
Apply condition to vector
Select elements where condition is TRUE
Return filtered vector
Logical indexing uses a TRUE/FALSE condition to pick elements from a vector.
x <- c(5, 10, 15, 20, 25) cond <- x > 15 x[cond]
| Step | Action | Condition/Expression | Result | Output |
|---|---|---|---|---|
| 1 | Create vector x | c(5, 10, 15, 20, 25) | x = [5, 10, 15, 20, 25] | |
| 2 | Evaluate condition | x > 15 | cond = [FALSE, FALSE, FALSE, TRUE, TRUE] | |
| 3 | Apply logical indexing | x[cond] | Select elements where cond is TRUE | [20, 25] |
| 4 | End | No more steps |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| x | undefined | [5, 10, 15, 20, 25] | [5, 10, 15, 20, 25] | [5, 10, 15, 20, 25] | [5, 10, 15, 20, 25] |
| cond | undefined | undefined | [FALSE, FALSE, FALSE, TRUE, TRUE] | [FALSE, FALSE, FALSE, TRUE, TRUE] | [FALSE, FALSE, FALSE, TRUE, TRUE] |
| output | undefined | undefined | undefined | [20, 25] | [20, 25] |
Logical indexing in R: - Create a logical vector condition (e.g., x > 15) - Use it inside square brackets: x[condition] - Returns elements where condition is TRUE - Logical vector length should match x - Useful for filtering vectors easily