R Extract Rows where Data Frame Column Partially Matches Character String (Example Code)

This tutorial explains how to extract data frame rows based on a partial match of a character string in the R programming language.

Example Data

my_df <- data.frame(x1 = c("ABA", "CCCAB", "XXX", "YYY"),  # Example data
                    x2 = 1:4)
my_df                                                      # Print example data
#      x1 x2
# 1   ABA  1
# 2 CCCAB  2
# 3   XXX  3
# 4   YYY  4

Example: Finding Rows with Partial Match in Character String

install.packages("stringr")                                # Install & load stringr package
library("stringr")
my_df[str_detect(my_df$x1, "AB"), ]                        # Extract matching rows with str_detect
#      x1 x2
# 1   ABA  1
# 2 CCCAB  2

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top