← Back to R Course | Chapter 7: Data Structures | Lesson 2 of 7

Lists

In this page:

  1. Lists

Lists

A list can hold elements of different types and different lengths together, unlike a vector which requires uniform type. Elements are accessed with double brackets, list[[i]], to get the value itself, while single brackets, list[i], return a sub-list. Lists are R's flexible general-purpose container, similar to a struct or heterogeneous array in other languages.

Warning: list[1] returns a list containing the first element; list[[1]] returns the element itself -- mixing these up is a very common bug.

Example: Lists

markup
person <- list(name = "Alice", age = 30, active = TRUE)

print(person)
cat("Name:", person[["name"]], "\n")
cat("Name (dollar syntax):", person$name, "\n")
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.