R Lists
Lists in R are data structures that can hold elements of different types, such as numbers, strings, vectors, and even other lists. They are useful for organizing related data in a flexible way.
Key Topics
List Creation
Lists can be created using the list()
function.
# Creating a list
my_list <- list(name = "John", age = 25, scores = c(85, 90, 95))
print(my_list)
Output:
$name
[1] "John"
$age
[1] 25
$scores
[1] 85 90 95
[1] "John"
$age
[1] 25
$scores
[1] 85 90 95
Code Explanation: The list()
function is used to create a list containing elements of different data types: a character string, a numeric value, and a numeric vector.
Accessing List Elements
Elements of a list can be accessed using the dollar sign ($
) or double square brackets ([[ ]]
).
# Accessing elements
name <- my_list$name
age <- my_list[["age"]]
print(name)
print(age)
Output:
[1] "John"
[1] 25
[1] 25
Code Explanation: The $
operator and double square brackets [[ ]]
are used to access elements from the list my_list
.
Key Takeaways
- Lists can hold elements of different data types.
- The
list()
function is used to create lists in R. - Use the
$
operator or[[ ]]
to access elements in a list.