Concept Flow - Vector indexing (1-based)
Start with vector
Choose index i (1-based)
Access element at position i
Return element value
End
In R, vectors start counting at 1. You pick an index starting from 1 to get the element at that position.
vec <- c(10, 20, 30, 40) index <- 2 value <- vec[index] print(value)
| Step | Variable | Value | Action | Output |
|---|---|---|---|---|
| 1 | vec | c(10, 20, 30, 40) | Create vector | |
| 2 | index | 2 | Set index to 2 | |
| 3 | value | vec[2] | Access element at position 2 | 20 |
| 4 | print(value) | Print the value | 20 | |
| 5 | End of execution |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| vec | undefined | c(10, 20, 30, 40) | c(10, 20, 30, 40) | c(10, 20, 30, 40) | c(10, 20, 30, 40) |
| index | undefined | undefined | 2 | 2 | 2 |
| value | undefined | undefined | undefined | 20 | 20 |
Vector indexing in R starts at 1. Use vec[i] to get the element at position i. Index 1 is the first element. Accessing index 0 returns empty. Always count positions starting from 1.
v when using indexing like v[1]?vv[1] selects the first element of the vector.vec in R?[] are used to access elements by position.vec[3] correctly accesses the third element.nums <- c(10, 20, 30, 40, 50) nums[2:4]
nums has elements 10, 20, 30, 40, 50 at positions 1 to 5.nums[2:4] selects elements at positions 2, 3, and 4 which are 20, 30, and 40.vals <- c(5, 10, 15, 20) print(vals[0])
vals[0] with vals[1] to access the first element.data <- c(3, 6, 9, 12, 15). How do you create a new vector containing only the 1st, 3rd, and 5th elements using vector indexing in R?c() inside square brackets to select multiple positions.data[c(1, 3, 5)] selects elements at these positions: 3, 9, and 15.Pass the test and this pattern moves unknown