Skip to main content

Mastering Subsetting in R: Lists, Nested Lists, Matrices, and Using the Drop Argument

The Beginner’s Guide to Subsetting in R Programming:

Subsetting is a fundamental operation in R that allows you to select specific elements or subsets of data from vectors, lists, matrices, and data frames. Subsetting is a powerful technique that enables you to work with smaller, more manageable subsets of your data, and is an essential skill for any R programmer.

In this blog post, we will cover subsetting in R, including subsetting lists, nested lists, and matrices, as well as using the drop argument. We will also provide some practice materials for beginners to reinforce the concepts covered in this post.


Subsetting Vectors

The simplest form of subsetting in R is subsetting vectors. To subset a vector, you can use square brackets [] with an index or a sequence of indices.

# Create a vector
x <- c(1, 2, 3, 4, 5)

# Subsetting using an index
x[3] # Returns the third element (3)

# Subsetting using a sequence of indices
x[2:4] # Returns the second, third, and fourth elements (2, 3, 4)

Subsetting Lists

Lists are a type of object in R that can contain elements of different types, such as vectors, matrices, and even other lists. To subset a list, you can use square brackets [] with an index or a name.

# Create a list
my_list <- list(a = 1, b = c(2, 3, 4), c = matrix(1:9, nrow = 3))

# Subsetting using an index
my_list[[2]] # Returns the second element, which is a vector (2, 3, 4)

# Subsetting using a name
my_list[["c"]] # Returns the third element, which is a matrix

Subsetting Nested Lists

Nested lists are lists that contain other lists as elements. Subsetting nested lists can be more complex than subsetting simple lists, but the principles are the same. You can use multiple sets of square brackets [] to access the elements at different levels of nesting.

# Create a nested list
my_nested_list <- list(a = 1, b = list(c(2, 3), d = list(e = 4, f = 5)))

# Subsetting a nested list
my_nested_list[[2]][["d"]][["e"]] # Returns the value 4

Subsetting Matrices

Matrices are two-dimensional arrays in R that can contain elements of the same type. To subset a matrix, you can use square brackets [] with row and column indices.

# Create a matrix
my_matrix <- matrix(1:9, nrow = 3)

# Subsetting a matrix using row and column indices
my_matrix[2, 3] # Returns the value in the second row and third column (6)

# Subsetting a matrix using a sequence of row or column indices
my_matrix[1:2, 2:3] # Returns a sub-matrix containing the first two rows and second and third columns

Using the Drop Argument

The drop argument in subsetting is a logical value that is used when subsetting matrices. By default, when you subset a matrix with a single index, R will simplify the result to the lowest possible dimension, which means that it will return a vector instead of a matrix. The drop argument allows you to control this behavior.
For example, consider the following matrix:

my_matrix <- matrix(1:6, nrow = 2)
# [,1] [,2] [,3]
# [1,] 1 3 5
# [2,] 2 4 6

If you subset this matrix with a single index, R will return a vector:

my_matrix[1]
# [1] 1 2

This is because R is simplifying the result to the lowest possible dimension. To prevent this behavior and force R to return a matrix instead of a vector, you can set the drop argument to FALSE:

my_matrix[1, drop = FALSE]
# [,1] [,2]
# [1,] 1 5

Setting drop to FALSE tells R to keep the result as a matrix, even if the result has only one row or column.

Note that the drop argument only applies to matrices, and does not affect subsetting of vectors, lists, or other objects.

Overall, the drop argument is a useful tool for controlling the behavior of subsetting in R and can help ensure that you get the results you expect.

Practice Material:

Subsetting Vectors:
  • Create a vector of numbers from 1 to 10.
  • Subset the vector to get only the even numbers.
  • Subset the vector to get the last three elements.
  • Subset the vector to get the first four elements.
Subsetting Lists:
  • Create a list with two elements: a vector of even numbers and a vector of odd numbers.
  • Subset the list to get the first element (i.e., the vector of even numbers).
  • Subset the list to get the second element (i.e., the vector of odd numbers).
  • Subset the list to get the last three even numbers.
Subsetting Nested Lists:
  • Create a nested list with two elements: a list of even numbers and a list of odd numbers, each containing three elements.
  • Subset the nested list to get the second even number.
  • Subset the nested list to get the last odd number.
  • Subset the nested list to get the first two even numbers.
Subsetting Matrices:
  • Create a matrix with 3 rows and 4 columns, filled with random numbers.
  • Subset the matrix to get the element in the first row and second column.
  • Subset the matrix to get the second row.
  • Subset the matrix to get the third column.
Drop Argument in Subsetting:
  • Create a matrix with 3 rows and 4 columns, filled with random numbers.
  • Subset the matrix to get the element in the first row and second column, with drop = TRUE.
  • Subset the matrix to get the second row, with drop = FALSE.
  • Subset the matrix to get the third column, with drop = TRUE. 

    MORE!

  • For more practice you should start swirl's lesson Six in R Programming. Complete download process of swirl and R Programming is here, click on the link!

  • You can look in to the practice and reading material that is provided in the text book, click here to download the textbook.
  • Lecture slides can be downloaded from here. It would be great if you go through them too.

These exercises will help you practice subsetting in R, including subsetting vectors, lists, nested lists, matrices, and using the drop argument. Good luck!


Comments

Popular posts from this blog

What is Data? And What is Data Science Process?

The Beginner’s Guide to Data & Data Science Process About Data: In our First Video today we talked about Data and how the Cambridge English Dictionary and Wikipedia defines Data, then we looked on few forms of Data that are: Sequencing data   Population census data ( Here  is the US census website and  some tools to help you examine it , but if you aren’t from the US, I urge you to check out your home country’s census bureau (if available) and look at some of the data there!) Electronic medical records (EMR), other large databases Geographic information system (GIS) data (mapping) Image analysis and image extrapolation (A fun example you can play with is the  DeepDream software  that was originally designed to detect faces in an image, but has since moved on to more  artistic  pursuits.) Language and translations Website traffic Personal/Ad data (e.g.: Facebook, Netflix predictions, etc.) These data forms need a lot of preprocessin...

Efficient Data Manipulation with Loop Functions in R: A Deep Dive into apply and mapply

The Beginner’s Guide to Loop Functions in R: In addition to lapply and sapply , R also has apply and mapply , which are other loop functions that are commonly used for data manipulation and analysis. In this blog post, we'll explain what these functions are, how they work, and provide some practice material for beginners to intermediate level. apply:  Apply a Function to a Matrix or Array apply is a loop function in R that applies a function to either rows or columns of a matrix or array. Here's the basic syntax: apply(matrix/array, margin, function) The matrix/array argument is the matrix or array you want to apply the function to, and the margin argument specifies whether you want to apply the function to rows or columns. margin = 1 applies the function to rows, while margin = 2 applies the function to columns. The function argument is the function you want to apply. For example, let's say we have a matrix of numbers and we want to apply the sum function to each row:...

Optimization Example of Lexical Scoping in R: Exploring optim, optimize, and nlm Functions

The Beginner’s Guide to Optimization Example of Lexical Scoping in R: When it comes to optimization in R, lexical scoping can be a useful tool for optimizing complex functions that involve multiple variables. In this blog post, we will explore how lexical scoping can be used to optimize a function using the NLL (negative log-likelihood) function , and how the optim, optimize, and nlm functions can be used to perform optimization in R. Optimizing the NLL Function using Lexical Scoping The NLL function is a common function used in optimization problems. It is defined as the negative log of the likelihood function, which is used to estimate the parameters of a statistical model. In R, the NLL function can be defined using lexical scoping, which allows us to pass arguments to the function and access variables from within the function. Here is an example of how to define the NLL function using lexical scoping in R: nll <- function(data, parameters) {   # Define local variables ...