A list in R is a data structure that can hold elements of different types — such as numbers, strings, vectors, and even other lists. This makes lists one of the most flexible data structures in R.
Use the list() function:
my_list <- list( name = "John", age = 25, scores = c(85, 90, 95), passed = TRUE )
This list contains a string, a number, a numeric vector, and a logical value — all together.
my_list$name → Access by namemy_list[["scores"]] → Access by name (alternative)my_list[[2]] → Access by index (2nd element)my_list[3] → Returns a sub-list (not the element directly)my_list$age <- 26 # Update age my_list$city <- "Delhi" # Add new element my_list$scores <- NULL # Remove scores
Lists can also contain other lists:
nested_list <- list(
id = 101,
info = list(
name = "Alice",
grade = "A"
)
)
nested_list$info$name # Access nested element
length(list) – number of elementsnames(list) – shows names of elementsstr(list) – structure of the listunlist(list) – flattens the list into a vectorlist() to create them.$, [[ ]], or [ ].NULL.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!