0
0
R Programmingprogramming~5 mins

List creation in R Programming

Choose your learning style9 modes available
Introduction

Lists let you store many different things together in one place. They help keep your data organized.

When you want to group different types of data like numbers, words, and other lists.
When you need to keep related information together, like a person's name, age, and hobbies.
When you want to return multiple results from a function.
When you want to store data that can be changed or added to later.
Syntax
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.

Examples
This creates an empty list with no items.
R Programming
empty_list <- list()
A list with just one number inside.
R Programming
single_item_list <- list(42)
A list with a number, a word, and a TRUE value.
R Programming
mixed_list <- list(10, "apple", TRUE)
A list that contains another list inside it.
R Programming
nested_list <- list(1, list("a", "b"), 3)
Sample Program

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.

R Programming
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)
OutputSuccess
Important Notes

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.

Summary

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]].