In R, you can select elements from a vector, list, or data frame using 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
# 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
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
my_vector.# Your code here
my_vector[5]
## [1] 5
my_vector.# Your code here
my_vector[c(2,4,6)]
## [1] 2 4 6
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"
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
my_matrix.# Your code here
my_matrix[1,]
## [1] 1 4 7
my_matrix.# Your code here
my_matrix[,3]
## [1] 7 8 9
my_matrix.# Your code here
diag(my_matrix)
## [1] 1 5 9
my_matrix.# Your code here
my_matrix[2,3]
## [1] 8
my_matrix.# Your code here
my_matrix[c(1,3), c(2,3)]
## [,1] [,2]
## [1,] 4 7
## [2,] 6 9
my_matrix that are greater
than 5.# Your code here
my_matrix[my_matrix>5]
## [1] 6 7 8 9