str_subset & str_which Functions in R (2 Examples)
This tutorial illustrates how use str_subset to keep only strings matching a pattern or how to apply the str_which function to find positions in a character string in the R programming language.
Table of contents:
- Creation of Example Data
- Example 1: str_subset Function in R
- Example 2: str_which Function in R
- Video, Further Resources & Summary
Let’s do this:
Creation of Example Data
In the examples for the str_subset and str_which functions, I’ll use the following vector of character strings.
x <- c("aaa", "bbb", "abc") # Create a vector of character strings
Furthermore, we need to install and load the stringr package of the tidyverse environment to R:
install.packages("stringr") # Install stringr R package library("stringr") # Load stringr R package
Example 1: str_subset Function in R
This first example illustrates how to use the str_subset function in the R programming language:
str_subset(x, "a") # Apply str_subset function # "aaa" "abc"
With the previous R code, we extracted all character strings of our vector, which are containing the letter “a”.
Example 2: str_which Function in R
We can also identify the location of the character strings containing a certain pattern. For this task, we can use the str_which function as follows:
str_which(x, "a") # Apply str_which function # 1 3
The RStudio console output shows the result: The character strings at position 1 and 3 of our vector are containing the letter “a”.
Video, Further Resources & Summary
I have recently released a video on my YouTube channel, which illustrates the R programming syntax of this article. You can find the video below.
The YouTube video will be added soon.
Besides the video, you may want to read the other posts of my website:
In summary: You learned in this article how to keep only strings matching a pattern and how to identify certain positions in a character string in R. Don’t hesitate to let me know in the comments, if you have additional questions.
Statistics Globe Newsletter