Indexing in Vectors
Great! Now you understand how to create a vector and assign names to its values.
To access specific elements within a vector, you can use indices. The index of the first element is 1
, the second element is 2
, and so on. To retrieve the n
-th element from a vector vec
, use the syntax vec[n]
. Additionally, if the vector elements have assigned names, you can extract the values by their names by enclosing the name in quotes and square brackets.
Now, let’s revisit the grades example:
Subject | Grade |
---|---|
Math | 80 |
Physics | 75 |
English | 95 |
Literature | 100 |
We'll extract the grade for Math
and the grade for Literature
.
It's also possible to access multiple elements simultaneously:
Task
Continuing from the previous exercise, you have a vector named prices
with each price assigned to a corresponding item name.
- Retrieve the price of
'Armchair'
using its name rather than its index. - Retrieve the prices for both the
'Dining table'
and'Dining chair'
using their indices.
Everything was clear?
Course Content
R Introduction: Part I
R Introduction: Part I
Indexing in Vectors
Great! Now you understand how to create a vector and assign names to its values.
To access specific elements within a vector, you can use indices. The index of the first element is 1
, the second element is 2
, and so on. To retrieve the n
-th element from a vector vec
, use the syntax vec[n]
. Additionally, if the vector elements have assigned names, you can extract the values by their names by enclosing the name in quotes and square brackets.
Now, let’s revisit the grades example:
Subject | Grade |
---|---|
Math | 80 |
Physics | 75 |
English | 95 |
Literature | 100 |
We'll extract the grade for Math
and the grade for Literature
.
It's also possible to access multiple elements simultaneously:
Task
Continuing from the previous exercise, you have a vector named prices
with each price assigned to a corresponding item name.
- Retrieve the price of
'Armchair'
using its name rather than its index. - Retrieve the prices for both the
'Dining table'
and'Dining chair'
using their indices.
Everything was clear?