0
0
R Programmingprogramming~10 mins

Vector indexing (1-based) in R Programming - Step-by-Step Execution

Choose your learning style9 modes available
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.
Execution Sample
R Programming
vec <- c(10, 20, 30, 40)
index <- 2
value <- vec[index]
print(value)
This code picks the second element from the vector and prints it.
Execution Table
StepVariableValueActionOutput
1vecc(10, 20, 30, 40)Create vector
2index2Set index to 2
3valuevec[2]Access element at position 220
4print(value)Print the value20
5End of execution
💡 Index 2 is valid, so element 20 is returned and printed.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
vecundefinedc(10, 20, 30, 40)c(10, 20, 30, 40)c(10, 20, 30, 40)c(10, 20, 30, 40)
indexundefinedundefined222
valueundefinedundefinedundefined2020
Key Moments - 3 Insights
Why does R start counting vector positions from 1, not 0?
R uses 1-based indexing, so the first element is at position 1. This is shown in the execution_table where index 2 accesses the second element.
What happens if you try to access vec[0] in R?
Accessing vec[0] returns an empty vector because R does not use zero-based indexing. This differs from some other languages.
Why does vec[2] return 20 and not 10?
Because indexing starts at 1, vec[1] is 10 and vec[2] is 20, as shown in the execution_table step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'value' after step 3?
A30
B20
C10
Dundefined
💡 Hint
Check the 'value' variable in the execution_table row for step 3.
At which step is the vector 'vec' created?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column in the execution_table for vector creation.
If index was set to 3 instead of 2, what would 'value' be after step 3?
A20
B40
C30
D10
💡 Hint
Refer to the vector elements in variable_tracker and the meaning of index.
Concept Snapshot
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.
Full Transcript
This visual trace shows how vector indexing works in R, which uses 1-based counting. We create a vector with four numbers, then pick an index starting at 1. Accessing vec[2] returns the second element, 20. The variable tracker shows how variables change step by step. Key moments clarify why R starts at 1 and what happens if you use zero. The quiz tests understanding of variable values and indexing steps.