Get Vector Elements that Contain a Character in R (Example Code)

In this tutorial you’ll learn how to check whether a character is contained in a vector of character strings in R.

Creation of Example Data

my_string <- c("Yoyoyo",               # Character vector in R
               "Yayaya",
               "Yayayo",
               "Yipiyo",
               "XXXX")
my_string                              # Display character vector in RStudio console
# [1] "Yoyoyo" "Yayaya" "Yayayo" "Yipiyo" "XXXX"

Example: Applying grep() Function to Find Vector Elements with Particular Pattern in Character String

grep("yo", my_string, value = TRUE)    # Return matches
# [1] "Yoyoyo" "Yayayo" "Yipiyo"

Related Articles

Here, you can find some additional resources on topics such as vectors, character strings, and loops:

Leave a Reply

Your email address will not be published. Required fields are marked *

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