Skip to main content

Mastering Subsetting Techniques and Vectorized Operations in R: A Comprehensive Guide

The Beginner’s Guide Subsetting and Vectorized Operations in R:

Subsetting in R is a crucial part of data analysis and manipulation. It enables us to extract specific data elements from a larger dataset and perform operations on them. In this blog post, we will discuss several subsetting techniques in R, including partial matching, removing NA values, using the completecase function, vectorized operations on lists and matrices, and matrix multiplication and inverse.


Partial Matching

Partial matching in R is a useful technique for extracting subsets of data from larger datasets. It involves using a subset of a string to match against a larger string. For example, if you have a dataset with variable names such as "age", "height", and "weight", you can use partial matching to extract all variables that contain the substring "h". To do this, you can use the $ operator and the grep function as follows:

data <- data.frame(age = c(20, 30, 40), height = c(170, 180, 190), weight = c(70, 80, 90)) 
data$h <- data$height 
data[grep("h", names(data))]

In this example, we created a data frame with variables age, height, and weight. We then added a new variable, h, which is a copy of the height variable. Finally, we used grep to extract all variables that contain the substring "h" in their names. The resulting output is a data frame with variables height and h.

Removing NA Values

In R, we can remove NA values from a dataset using the na.omit function. This function removes all rows that contain NA values.

my_data <- data.frame(a = c(1, NA, 3), b = c(NA, 5, 6)) 
na.omit(my_data)

In this example, we have a data frame my_data with two columns and three rows. The second row contains NA values. We can use the na.omit function to remove this row.

Using completecase Function

The complete.cases function can be used to determine which rows of a data frame contain complete data, and we can subset the data using this function. Here is an example:

my_data <- data.frame(a = c(1, NA, 3), b = c(NA, 5, 6)) my_data[complete.cases(my_data), ]

In this example, we have a data frame my_data with two columns and three rows. The second row contains NA values. We can use the complete.cases function to determine which rows contain complete data and subset the data using this function.

Vectorized Operations on Lists and Matrices

In R, we can perform vectorized operations on lists and matrices. Vectorized operations enable us to perform an operation on all elements of a vector or matrix simultaneously. Here is an example:

my_list <- list(1:3, 4:6) 
my_list + 1

In this example, we have a list my_list with two vectors. We can perform a vectorized operation by adding 1 to each element of both vectors in the list.

my_matrix <- matrix(1:6, ncol = 2) 
my_matrix * 2

In this example, we have a matrix my_matrix with two columns and three rows. We can perform a vectorized operation by multiplying each element of the matrix by 2.

One more example, to calculate the square of each element in a vector, you can use the ^ operator as follows:

x <- c(1, 2, 3) 
x_squared <- x^2

In this example, we created a vector x with values 1, 2, and 3. We then used the ^ operator to calculate the square of each element in x and assign the result to a new vector, x_squared.

Matrix Multiplication and Inverse

Matrix multiplication and inverse are important operations in linear algebra and are frequently used in data analysis and machine learning. In R, you can perform matrix multiplication and inverse using built-in functions.

Matrix Multiplication in R:

In R, matrix multiplication can be performed using the %*% operator. This operator takes two matrices as input and returns their product. The number of columns in the first matrix should be equal to the number of rows in the second matrix.

For example, let's create two matrices A and B and perform matrix multiplication:

# create two matrices 
A <- matrix(c(1, 2, 3, 4), nrow = 2) 
B <- matrix(c(5, 6, 7, 8), nrow = 2) 
# perform matrix multiplication 
C <- A %*% B

In the above code, we created two matrices A and B with dimensions 2x2 and performed matrix multiplication using the %*% operator. The resulting matrix C will also be of dimensions 2x2.

Matrix Inverse in R:

In R, you can find the inverse of a matrix using the solve() function. The solve() function takes a matrix as input and returns its inverse. The matrix should be square and non-singular (i.e., its determinant should not be zero).

For example, let's create a matrix A and find its inverse:

# create a matrix 
A <- matrix(c(1, 2, 3, 4), nrow = 2) 
# find inverse of the matrix 
inv_A <- solve(A)

In the above code, we created a matrix A with dimensions 2x2 and found its inverse using the solve() function. The resulting matrix inv_A will also be of dimensions 2x2.

Practice Exercises:

Here are some practice exercises for beginners on subsetting in R and vectorized operations:

  • Create two matrices A and B of dimensions 3x2 and 2x4 respectively. Perform matrix multiplication between the two matrices and store the result in a new matrix C.
  • Create a matrix A of dimensions 3x3 with random integer values. Find the inverse of the matrix using the solve() function and store the result in a new matrix inv_A.
  • Create a matrix A of dimensions 2x2 with random integer values. Check if the matrix is singular (i.e., its determinant is zero) using the det() function.
  • Create a matrix A of dimensions 3x3 with random integer values. Find the transpose of the matrix using the t() function.
  • Create a vector fruits containing the following fruits: "apple", "banana", "orange", "mango", "grape". Use partial matching to extract the index of the element "orange" in the vector.
  • Create a vector numbers containing the following elements: 3, 7, NA, 9, 4, NA. Remove the NA values from the vector using the na.omit() function and store the result in a new vector clean_numbers.
  • Create a data frame df with the following columns: "name", "age", "gender", "salary". Fill in some data such that there are some missing values (NAs) in the data frame. Use the complete.cases() function to identify the rows that have complete data (i.e., no missing values) and store them in a new data frame complete_df.
  • Create a list numbers_list containing two vectors: a <- c(1, 2, 3) and b <- c(4, 5, 6). Use vectorized operations to add the two vectors element-wise and store the result in a new vector sum_list.
  • Create a matrix m of size 3x3 with random integer values. Create a vector v of size 3 with random integer values. Use vectorized operations to multiply the matrix m with the vector v and store the result in a new vector mv.
  • Create two matrices a and b of size 3x3 with random integer values. Use the %*% operator to perform matrix multiplication between the two matrices and store the result in a new matrix c.
  • Create a matrix m of size 3x3 with random integer values. Use the solve() function to find the inverse of the matrix m and store the result in a new matrix inv_m.

For More!

  • For more practice you should head over to swirl's lesson 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 should give you a good understanding of subsetting in R, vectorized operations, and matrix multiplication and inverse. See you in the next lecture!

Comments

Popular posts from this blog

Introduction to R Markdown

The Beginner’s Guide to R Markdown! We’ve spent a lot of time getting R and R Studio working, learning about Functionalities of R Studio and R Packages - you are practically an expert at this! There is one major functionality of R/R Studio that we would be remiss to not include in your introduction to R -  Markdown! Functionalities in R Studio Introduction to R Packages What is R Markdown? R Markdown is a way of creating fully reproducible documents, in which both text and code can be combined. In fact, these lessons are written using R Markdown! That’s how we make things: bullets bold italics links or run inline r code And by the end of this lesson, you should be able to do each of those things too, and more! Despite these documents all starting as plain text, you can render them into HTML pages, or PDFs, or Word documents, or slides! The symbols you use to signal, for example,  bold  or  italics  is compatible with all of those formats. Wh...

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...

Introduction to Functions and Arguments in R Programming: Part 2

The Beginner’s Guide to Functions in R Programming: Functions are an essential part of programming, and they play a critical role in R programming. In R, a function is a set of instructions that perform a specific task. Functions in R can have several arguments, and their evaluation can be lazy or eager. In this blog post, we will explore functions in R, including their  "dot-dot-dot" or ellipsis  argument, lazy evaluation, and more . Ellipsis or "dot-dot-dot" Argument in R Functions The "dot-dot-dot" or ellipsis argument in R programming is a special argument that can be used in functions to represent a variable number of additional arguments that are not explicitly defined in the function. The ellipsis argument is represented by three dots ... and is typically used at the end of the function's argument list. When the function is called, any additional arguments provided by the user after the defined arguments are collected by the ellipsis argument an...