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

Mastering Simulation in R Programming: A Beginner to Intermediate Guide

The Beginner’s Guide to Simulation in R: Simulation is the process of generating artificial data based on a set of assumptions or models. R programming provides a variety of functions and packages for simulating different types of data. In this blog post, we will cover the basics of simulation in R programming, including the most commonly used functions, distributions, and simulations using linear models. Functions for Simulation in R R programming provides various functions for simulation, such as: runif() – used to simulate data from a uniform distribution rnorm() – used to simulate data from a normal distribution rexp() – used to simulate data from an exponential distribution rgamma() – used to simulate data from a gamma distribution rpois() – used to simulate data from a Poisson distribution rbeta() – used to simulate data from a beta distribution rbinom() – used to simulate data from a binomial distribution rcauchy() – used to simulate data from a Cauchy distribution Distributio...