Introduction to Lists

In R, a list is a generic vector containing other objects. For example, a list can contain a numeric vector, a character vector, and a logical vector. The list() function is used to create a list.

# A list containing a numeric vector, a character vector, and a logical vector
my_list <- list(
  numbers = c(1, 2, 3),
  characters = c("a", "b", "c"),
  logicals = c(TRUE, FALSE, TRUE)
)
print(my_list)
## $numbers
## [1] 1 2 3
## 
## $characters
## [1] "a" "b" "c"
## 
## $logicals
## [1]  TRUE FALSE  TRUE

Exercises

  1. Create a list named my_info that contains your name, your age, and whether you are a student or not.
# Your code here
my_info <- list(
  name = "Alif",
  age = 31,
  is_student = TRUE
)
typeof(my_info)
## [1] "list"
print(my_info)
## $name
## [1] "Alif"
## 
## $age
## [1] 31
## 
## $is_student
## [1] TRUE
  1. Access the age element from the my_info list.
# Your code here
my_info$age
## [1] 31
  1. Add a new element to the my_info list called hobbies that contains a vector of your hobbies.
# Your code here
my_info$hobbies <- c("Reading", "Music", "Working")
print(my_info)
## $name
## [1] "Alif"
## 
## $age
## [1] 31
## 
## $is_student
## [1] TRUE
## 
## $hobbies
## [1] "Reading" "Music"   "Working"
  1. Create an empty list named my_empty_list.
# Your code here
my_empty_list <- list()
print(my_empty_list)
## list()
  1. Get the length of the my_info list.
# Your code here
length(my_info)
## [1] 4
  1. Get the first element of the my_info list.
# Your code here
my_info[[1]]
## [1] "Alif"
  1. Get the last element of the my_info list.
# Your code here
my_info[[length(my_info)]]
## [1] "Reading" "Music"   "Working"
  1. Get the elements from the second to the third position in the my_info list.
# Your code here
my_info[2:3]
## $age
## [1] 31
## 
## $is_student
## [1] TRUE
  1. Remove the is_student element from the my_info list.
# Your code here
my_info$is_student <- NULL
print(my_info)
## $name
## [1] "Alif"
## 
## $age
## [1] 31
## 
## $hobbies
## [1] "Reading" "Music"   "Working"

Solutions

Click here for the solutions