Lists in R
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.
Example 1: Creating a Simple List
- We start by creating a list named
my_listusing thelistfunction. - The list has three elements:
namewith a character value,agewith a numeric value, andscoreswith a numeric vector. - 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
Example 2: Accessing List Elements
- We create a list named
my_listwith elementsname,age, andscores. - We access the
nameelement using the dollar sign$operator and print it. - We access the
scoreselement using double square brackets[[ ]]and print it. - We access the second element of the
scoresvector 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
Example 3: Modifying List Elements
- We create a list named
my_listwith elementsname,age, andscores. - We modify the
ageelement by assigning a new value to it. - We add a new element named
genderto the list. - 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"
Example 4: Combining Lists
- We create two lists named
list1andlist2with different elements. - We combine the two lists into a new list named
combined_listusing thec()function. - 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
Example 5: Applying Functions to List Elements
- We create a list named
my_listwith elementsname,age, andscores. - We use the
lapply()function to apply themeanfunction to thescoreselement of the list. - 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