0
0
R Programmingprogramming~5 mins

Why lists hold mixed types in R Programming

Choose your learning style9 modes available
Introduction

Lists in R can hold different types of data together. This helps you keep related but different things in one place.

You want to store a number, a word, and a table all in one container.
You have results from different tests and want to keep them together.
You want to return multiple types of information from a function.
You want to group different objects like vectors, data frames, and functions.
You want to organize mixed data from a survey, like names and scores.
Syntax
R Programming
my_list <- list(123, "hello", TRUE, c(1, 2, 3))

A list is created using the list() function.

Each item inside can be a different type: number, text, logical, or vector.

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 holding a number, a string, and a logical value.
R Programming
mixed_list <- list(10, "apple", FALSE)
A list that contains a vector and another list inside it.
R Programming
nested_list <- list(c(1,2), list("a", "b"))
Sample Program

This program creates a list with mixed types: a number, a string, a logical, and a vector. Then it adds a data frame as a new item. It prints the list before and after adding the new item.

R Programming
my_list <- list(25, "R language", TRUE, c(5, 10, 15))

print("Before adding new item:")
print(my_list)

# Add a new item of a different type
my_list[[5]] <- data.frame(Name = c("Alice", "Bob"), Age = c(30, 25))

print("After adding new item:")
print(my_list)
OutputSuccess
Important Notes

Lists can hold any type of data, unlike vectors which hold only one type.

Access list items using double square brackets, like my_list[[1]].

Lists use more memory than vectors because they store different types.

Summary

Lists let you keep different types of data together.

Use list() to create them.

They are useful when you want to group mixed information in one place.