Introduction to Indexing

In R, you can select elements from a vector, list, or data frame using indexing.

Vector Indexing

# A numeric vector
numeric_vector <- c(10, 20, 30, 40, 50)

# Select the third element
numeric_vector[3]
## [1] 30
# Select the first and third elements
numeric_vector[c(1, 3)]
## [1] 10 30

List Indexing

# A list
my_list <- list(
  name = "Charlie",
  age = 30,
  is_student = FALSE
)

# Select the 'age' element
my_list$age
## [1] 30
my_list[["age"]]
## [1] 30

Exercises

  1. Create a numeric vector named my_vector with the numbers 1 to 10.
# Your code here
my_vector <- c(1:10)
print(my_vector)
##  [1]  1  2  3  4  5  6  7  8  9 10
  1. Select the 5th element of my_vector.
# Your code here
my_vector[5]
## [1] 5
  1. Select the 2nd, 4th, and 6th elements of my_vector.
# Your code here
my_vector[c(2,4,6)]
## [1] 2 4 6
  1. Create a list named my_list with the same elements as in the example. Select the name element.
# Your code here
my_list <- list(
  name = "Charlie",
  age = 30,
  is_student = FALSE
)
my_list$name
## [1] "Charlie"
  1. Create a 3x3 matrix named my_matrix with numbers from 1 to 9.
# Your code here
my_matrix <- matrix(c(1:9), nrow = 3, ncol = 3)
print(my_matrix)
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
  1. Extract the first row of my_matrix.
# Your code here
my_matrix[1,]
## [1] 1 4 7
  1. Extract the last column of my_matrix.
# Your code here
my_matrix[,3]
## [1] 7 8 9
  1. Extract the diagonal elements of my_matrix.
# Your code here
diag(my_matrix)
## [1] 1 5 9
  1. Extract the element in the second row and third column of my_matrix.
# Your code here
my_matrix[2,3]
## [1] 8
  1. Extract the elements in the first and third rows and the second and third columns of my_matrix.
# Your code here
my_matrix[c(1,3), c(2,3)]
##      [,1] [,2]
## [1,]    4    7
## [2,]    6    9
  1. Extract the elements from my_matrix that are greater than 5.
# Your code here
my_matrix[my_matrix>5]
## [1] 6 7 8 9

Solutions

Click here for the solutions