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
v[c(TRUE, FALSE, TRUE)]?vv where the index is TRUE -> Option Ax where values are greater than 5 using logical indexing?x > 5 creates a logical vector TRUE where elements are greater than 5.xx[x > 5] selects elements of x where the condition is TRUE.x[> 5]v <- c(10, 3, 7, 2, 9) v[v >= 7]
v >= 7nums <- c(4, 8, 15, 16, 23, 42) nums[nums > 10 & TRUE]
nums > 10 & TRUEnums > 10 returns a logical vector; AND with TRUE keeps it unchanged.nums, and syntax is correct, so no error occurs.temps <- c(23, NA, 19, 25, NA, 21), how can you use logical indexing to select only the non-missing values?is.na(temps) returns TRUE for missing values (NA) and FALSE otherwise.!is.na(temps) creates a logical vector TRUE where values are not missing.temps with this logical vectortemps.Pass the test and this pattern moves unknown