Site icon R-bloggers

Another Post on Lists

[This article was first published on Steve's Data Tips and Tricks, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
< section id="introduction" class="level1">

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]”.
< section id="examples" class="level1">

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!

To leave a comment for the author, please follow the link and comment on their blog: Steve's Data Tips and Tricks.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.