Vector Indexing
Extracting elements of a vector using subscripts:
In R, you can extract elements from a vector using subscripts (also known as indices). There are multiple ways to do this. Those are,
- Using Positive Indices
- Using Negative Indices
- Using Logical Indexing
- Using
:(colon operator) - Using Named Indices
Using Positive Indices:
Extract specific elements from vector by specifying their indices or positions.
Example:
> vec <- c(10, 20, 30, 40, 50)
> # First element
> print(vec[1])
[1] 10
> # Second element
> print(vec[2])
[1] 20
> # Multiple elements
> print(vec[c(1, 3, 5)])
[1] 10 30 50
Using Negative Indices:
Exclude specific elements from vector by specifying negative indices or positions.
Example:
> vec <- c(10, 20, 30, 40, 50)
> # Exclude first element
> print(vec[-1])
[1] 20 30 40 50
> # Exclude multiple elements
> print(vec[-c(2, 3)])
[1] 10 40 50
Using Logical Indexing:
In R, logical subscripts (or logical indexing) allow you to extract elements from a vector based on a logical condition.
Example:
> vec <- c(10, 20, 30, 40, 50)
> # Extract elements which are > 25
> print(vec[vec > 25])
[1] 30 40 50
> # Extract elements which are divisible by 20
> print(vec[vec %% 20 == 0])
[1] 20 40
> # Extract elements which are > 10 and < 50
> print(vec[vec > 10 & vec < 50])
[1] 20 30 40
> # Extract elements which are != 30
> print(vec[!(vec == 30)])
[1] 10 20 40 50
Using : (colon operator):
Extract a range or sequence of elements from vector using : (colon operator).
Example:
> vec <- c(10, 20, 30, 40, 50)
> # Extract sequence of elements
> print(vec[1:3])
[1] 10 20 30
> print(vec[2:4])
[1] 20 30 40
Using Named Indices:
If the vector is a named vector, we can extract elements using named indices.
Example:
> named_v <- c(a = 100, b = 200, c = 300)
> # Extract element using named index
> print(named_v["c"])
c
300
> print(named_v["b"])
b
200