R Lists


R Lists

In this tutorial, we will learn about lists in R. We will cover the basics of creating, accessing, modifying, and performing operations on lists.


What is a List

A list in R is an object that can contain elements of different types, including numbers, strings, vectors, and even other lists. Lists are useful for grouping related but different types of data together.


Creating Lists

Lists can be created in R using the list() function:

my_list <- list(name = 'Alice', age = 25, scores = c(90, 85, 88))

The above code creates a list with three elements: a character string, a numeric value, and a numeric vector.



Creating a Simple List

  1. We start by creating a list named my_list using the list function.
  2. The list has three elements: name with a character value, age with a numeric value, and scores with a numeric vector.
  3. We print the list to the console to see its structure.

R Program

my_list <- list(name = 'Alice', age = 25, scores = c(90, 85, 88))
print(my_list)

Output

$name
[1] "Alice"

$age
[1] 25

$scores
[1] 90 85 88


Accessing List Elements

  1. We create a list named my_list with elements name, age, and scores.
  2. We access the name element using the dollar sign $ operator and print it.
  3. We access the scores element using double square brackets [[ ]] and print it.
  4. We access the second element of the scores vector within the list and print it.

R Program

my_list <- list(name = 'Alice', age = 25, scores = c(90, 85, 88))
print(my_list$name)
print(my_list[['scores']])
print(my_list$scores[2])

Output

[1] "Alice"
[1] 90 85 88
[1] 85


Modifying List Elements

  1. We create a list named my_list with elements name, age, and scores.
  2. We modify the age element by assigning a new value to it.
  3. We add a new element named gender to the list.
  4. We print the modified list to see the changes.

R Program

my_list <- list(name = 'Alice', age = 25, scores = c(90, 85, 88))
my_list$age <- 26
my_list$gender <- 'Female'
print(my_list)

Output

$name
[1] "Alice"

$age
[1] 26

$scores
[1] 90 85 88

$gender
[1] "Female"


Combining Lists

  1. We create two lists named list1 and list2 with different elements.
  2. We combine the two lists into a new list named combined_list using the c() function.
  3. We print the combined list to see the result.

R Program

list1 <- list(a = 1, b = 2)
list2 <- list(c = 'three', d = 4)
combined_list <- c(list1, list2)
print(combined_list)

Output

$a
[1] 1

$b
[1] 2

$c
[1] "three"

$d
[1] 4


Applying Functions to List Elements

  1. We create a list named my_list with elements name, age, and scores.
  2. We use the lapply() function to apply the mean function to the scores element of the list.
  3. We print the result to see the mean of the scores.

R Program

my_list <- list(name = 'Alice', age = 25, scores = c(90, 85, 88))
mean_scores <- lapply(my_list['scores'], mean)
print(mean_scores)

Output

$scores
[1] 87.66667