R Tutorial



R LISTS


Lists in R

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.

Creating a List

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.

Accessing List Elements

  • my_list$name → Access by name
  • my_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)

Modifying List Elements

my_list$age <- 26       # Update age
my_list$city <- "Delhi" # Add new element
my_list$scores <- NULL  # Remove scores
  

Nested Lists

Lists can also contain other lists:

nested_list <- list(
  id = 101,
  info = list(
    name = "Alice",
    grade = "A"
  )
)
nested_list$info$name   # Access nested element
  

Useful List Functions

  • length(list) – number of elements
  • names(list) – shows names of elements
  • str(list) – structure of the list
  • unlist(list) – flattens the list into a vector

Summary

  • Lists can hold different data types.
  • Use list() to create them.
  • Access with $, [[ ]], or [ ].
  • Modify by assignment or remove using NULL.
  • Lists can be nested inside other lists.

Practice Exercises

  • Create a list with your name, age, and a vector of your top 3 skills.
  • Access and print each element using both name and index methods.
  • Add a new element to your list (like your city).
  • Create a list that contains another list (nested).

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review