Another Post on Lists

code
rtip
lists
Author

Steven P. Sanderson II, MPH

Published

January 20, 2023

Introduction

Manipulating lists in R is a powerful tool for organizing and analyzing data. Here are a few common ways to manipulate lists:

  1. Indexing: Lists can be indexed using square brackets “[ ]” and numeric indices. For example, to access the first element of a list called “mylist”, you would use the expression “mylist[1]”.
  2. Subsetting: Lists can be subsetted using the same square bracket notation, but with a logical vector indicating which elements to keep. For example, to select all elements of “mylist” that are greater than 5, you would use the expression “mylist[mylist > 5]”.
  3. Modifying elements: Elements of a list can be modified by assigning new values to them using the assignment operator “<-”. For example, to change the third element of “mylist” to 10, you would use the expression “mylist[3] <- 10”.
  4. Adding elements: New elements can be added to a list using the concatenation operator “c()” or the “append()” function. For example, to add the number 7 to the end of “mylist”, you would use the expression “mylist <- c(mylist, 7)”.
  5. Removing elements: Elements can be removed from a list using the “-” operator. For example, to remove the second element of “mylist”, you would use the expression “mylist <- mylist[-2]”.

Examples

Here is an example of how these methods can be used to manipulate a list in R:

mylist <- list(1,2,3,4,5)

# Indexing
mylist[[1]] # Returns 1
[1] 1
# Subsetting
mylist[mylist > 3] # Returns 4 & 5
[[1]]
[1] 4

[[2]]
[1] 5
# Modifying elements
mylist[[3]] <- 10
mylist # Returns 1 2 10 4 5 7
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 10

[[4]]
[1] 4

[[5]]
[1] 5
# Adding elements
mylist <- c(mylist, 7)
mylist # Returns 1 2 10 4 5 7
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 10

[[4]]
[1] 4

[[5]]
[1] 5

[[6]]
[1] 7
# Removing elements
mylist[-3]
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 4

[[4]]
[1] 5

[[5]]
[1] 7
mylist # Returns 1 2 4 5 7
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 10

[[4]]
[1] 4

[[5]]
[1] 5

[[6]]
[1] 7

Voila!