2.4.4 List

The last type of data structure I want to introduce to you is the list. Compared to matrices and data frames, its frequency of use in programming is not very high, but it is still very useful and reflects a higher level of understanding of R data structures. It is a versatile and powerful data structure that can hold an ordered collection of elements, which can be of different types. Unlike vectors, matrices, and data frames, lists can contain mixed data types, including other lists, vectors, data frames, and even functions. conversely, a data frame is essentially a type of list. Let’s see some examples

# Example 1 
y = list()
y[[1]] = 1:10 # In a list, we use double square brackets to slice. 
y[[2]] = letters[2:7]
y[[3]] = function(x){2*x}
y
y[[3]](2) # what is this?
# Example 2
y = list()
y$x = 1:10 # In a list, we also can use `$` to slice.
y$letters = letters[2:7]
y$double = function(x){2*x}
y
y$double(2) # Now, you understand why data frame is also a list.

Remark: Function is alo a kind of data type or structure in R. It has been investigated before, so we don’t discuss it here again.

Previous page | Lecture 2 Homepage | Next page

© 2024 Xijia Liu. All rights reserved.
Logo