What are Lists?
Lists are the R objects with numbers, strings, vectors and another list or matrix inside it.
Creating a List
Example to create a list containing numbers, strings, vectors, and logical values.
#creating a list
list_info <- list("Blue", "Yellow", c(12, 13, 14), TRUE, 13.12, 103.4)
print(list_info)
Output:
[[1]]
[1] "Blue"
[[2]]
[1] "Yellow"
[[3]]
[1] 12 13 14
[[4]]
[1] TRUE
[[5]]
[1] 13.12
[[6]]
[1] 103.4
Naming List Elements
Names can be given to list elements and can be accessed using the corresponding names.
Get familiar with the top R Interview Questions to get a head start in your career!
Example:
#Creating a list which contains a matrix and a vector
list_name <- list(matrix(c(1,2,3,4,5,6), nrow = 2), c("mon","tue","wed"))
#Naming elements in the list
names(list_name) <- c("Matrix", "half_week")
#displaying list
print(list_name)
Output:
$Matrix
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
$ half_week
[1] "mon" "tue" "wed"
Accessing List Elements
Index of the element of the list can be given access to Elements of the list.
Syntax:
list_name <- list(.,..,.)
names(list_name) <- c(.,.,.)
print(list_name[1])
Manipulating List Elements
Addition, subtraction or deleting and updating the list elements can be done;
Few examples are:
#Creating a list which contains a vector, a matrix and a list
list_name <- list(c("Mon", Tue", "Wed"), matrix(c(2,1,1,1,5,6), nrow =2), list("milk", 1.2)
#Naming elements in the list
names(list_name) <- c("half week", "Matrix", "A simple list")
#Creating an element at the end of list
list_name [4] <- "An Element"
print(list_name[4])
#Withdrawing the last element
list_name[4] <-NULL
#Output last element
print(list_name[4])
Output:
[[1]]
[1] " An Element
$
NULL
For the best of career growth, check out Intellipaat’s R Programming training Course in Singapore and get certified!
Merging Lists
Merging can be done by placing all lists into one list() function.
Example:
#Creating lists
lista <- list(2,4,6)
listb <- list("Jan", "Feb", "Mar")
#Merging lists
merge.list <- c(lista. listb)
#output merged list
print(merge.list)
Output:
[[1]]
[1] 2
[[2]]
[1] 4
[[3]]
[1] 6
[[4]]
[1] "Jan"
[[5]]
[1] "Feb"
[[6]]
[1] "Mar"
Converting List to Vector
Using unlist() function we can convert a list to a vector so that all the elements of the vector can be used for further data manipulation such as applying arithmetic operations.
Example:
#Creating lists
lista <- list(1:3)
listb <- list(4:6)
#Converting lists to vector
cva <- unlist(lista)
cvb <- unlist(listb)
print(cva)
print(cvb)
Output:
[1] 1 2 3
[1] 4 5 6