Lists let you store many different things together in one place. They help keep your data organized.
List creation in R Programming
my_list <- list(item1, item2, item3, ...)You use the list() function to create a list.
Items inside a list can be any type: numbers, text, or even other lists.
empty_list <- list()single_item_list <- list(42)
mixed_list <- list(10, "apple", TRUE)
nested_list <- list(1, list("a", "b"), 3)
This program creates a list with a name, age, a TRUE value, and a list of hobbies. Then it adds a new item to the list and prints the list before and after.
my_list <- list("John", 25, TRUE, list("reading", "swimming")) print("Before adding new item:") print(my_list) # Add a new item to the list my_list[[length(my_list) + 1]] <- "new item" print("After adding new item:") print(my_list)
Creating a list takes constant time, O(1), but adding items can take longer if you copy the list.
Lists use extra memory because they can hold different types of data.
Common mistake: Using parentheses () instead of list() to create a list.
Use lists when you need to store mixed data types or nested data. Use vectors when all data is the same type.
Lists store multiple items of any type together.
Use list() to create a list.
You can add items by assigning to a new position like my_list[[length(my_list) + 1]].