Data Structure: List
↪ Creating a list
A list is used for storing an ordered set of elements. While a vector requires all its elements to be of the same type, a list allows different types of elements.
The list() function is used for creating a list.
x = list("Chimpanjee",10, 175.2)
x
---Output---
[[1]]
[1] "Chimpanjee"
[[2]]
[1] 10
[[3]]
[1] 175.2
Creating a list with a tag.
x = list(name="Chimpanjee", age=10, height=175.2) x
---Output--- $name [1] "Chimpanjee" $age [1] 10 $height [1] 175.2
Creating a list using as.list() function.
students = c("Mark","Philip","Mary")
x <- as.list(students)
x
---Output---
[[1]]
[1] "Mark"
[[2]]
[1] "Philip"
[[3]]
[1] "Mary"
Creating a list using vectors.
students = c("Mark","Philip","Mary")
grade = c(6,7,6)
class = list(students,grade)
class
---Output---
[[1]]
[1] "Mark" "Philip" "Mary"
[[2]]
[1] 6 7 6
Data Structure: List
↪ Accessing the list of elements
Take the previous example of a list class.
students = c("Mark","Philip","Mary")
grade = c(6,7,6)
class = list(students,grade)
The elements of the class list can be accessed using the index [[i]] or [i],
where 'i' is the corresponding index value of the list.
class[[1]] # Prints [1] "Mark" "Philip" "Mary" class[2] # [[1]] # [1] 6 7 6
Elements of a particular vector can be specified by using the required position enclosed in [[i]][j] format.
class[[1]][2] # Prints [1] "Philip"
When the list is created with tags, the elements can be accessed using the tag name.
x = list(name="Chimpanjee", age=10, height=175.2) x$name # Prints [1] "Chimpanjee"
