In this tutorial, we will learn about lists in R. We will cover the basics of creating, accessing, modifying, and performing operations on lists.
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.
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.
my_list
using the list
function.name
with a character value, age
with a numeric value, and scores
with a numeric vector.my_list <- list(name = 'Alice', age = 25, scores = c(90, 85, 88))
print(my_list)
$name [1] "Alice" $age [1] 25 $scores [1] 90 85 88
my_list
with elements name
, age
, and scores
.name
element using the dollar sign $
operator and print it.scores
element using double square brackets [[ ]]
and print it.scores
vector within the list and print it.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])
[1] "Alice" [1] 90 85 88 [1] 85
my_list
with elements name
, age
, and scores
.age
element by assigning a new value to it.gender
to the list.my_list <- list(name = 'Alice', age = 25, scores = c(90, 85, 88))
my_list$age <- 26
my_list$gender <- 'Female'
print(my_list)
$name [1] "Alice" $age [1] 26 $scores [1] 90 85 88 $gender [1] "Female"
list1
and list2
with different elements.combined_list
using the c()
function.list1 <- list(a = 1, b = 2)
list2 <- list(c = 'three', d = 4)
combined_list <- c(list1, list2)
print(combined_list)
$a [1] 1 $b [1] 2 $c [1] "three" $d [1] 4
my_list
with elements name
, age
, and scores
.lapply()
function to apply the mean
function to the scores
element of the list.my_list <- list(name = 'Alice', age = 25, scores = c(90, 85, 88))
mean_scores <- lapply(my_list['scores'], mean)
print(mean_scores)
$scores [1] 87.66667