Lists in R

Topic: Lists

Advertisement

Introduction

Lists are versatile data structures in R that can hold elements of different types and lengths. They are fundamental for storing complex data structures.

Creating Lists

# Using list() function
my_list <- list(
  name = "John",
  age = 30,
  scores = c(85, 90, 78),
  is_student = TRUE
)

# List with unnamed elements
simple_list <- list("apple", 42, TRUE, c(1, 2, 3))

Accessing List Elements

my_list <- list(
  name = "John",
  age = 30,
  scores = c(85, 90, 78)
)

# Using $ operator
my_list$name
my_list$age

# Using [[]] operator
my_list[[1]]
my_list[["name"]]

# Access nested elements
my_list$scores[1]

Modifying Lists

my_list <- list(name = "John", age = 30)

# Add new element
my_list$city <- "New York"

# Modify existing element
my_list$age <- 31

# Remove element
my_list$age <- NULL

List Functions

my_list <- list(a = 1, b = 2, c = 3)

length(my_list)      # Number of elements
names(my_list)       # Get element names
names(my_list) <- c("x", "y", "z")  # Set names
unlist(my_list)      # Convert to vector

Applying Functions to Lists

my_list <- list(a = c(1, 2, 3), b = c(4, 5, 6))

# lapply returns list
lapply(my_list, mean)

# sapply returns vector
sapply(my_list, mean)

# str() for structure
str(my_list)

Summary

Lists are incredibly flexible data structures that can hold heterogeneous data. They are extensively used in R programming.

Advertisement

Advertisement

Need More Practice?

Get personalized R programming help from ChatWhole's AI-powered platform.

Get Expert Help →