You can use the following methods to check if a character is in a string in R:
Method 1: Check if Character is in String Using Base R
grepl(my_character, my_string, fixed=TRUE)
Method 2: Check if Character is in String Using stringr Package
library(stringr)
str_detect(my_string, my_character)
The following examples show how to use each method in practice.
Example 1: Check if Character is in String Using Base R
The following code shows how to check if “Doug” exists in a particular string in R:
#define character to look for
my_character <- "Doug"
#define string
my_string <- "Hey my name is Douglas"
#check if "Doug" is in string
grepl(my_character, my_string, fixed=TRUE)
[1] TRUE
Since “Doug” does exist in the string, the grepl() function returns TRUE.
Suppose we instead check if “Steve” exists in the string:
#define character to look for
my_character <- "Steve"
#define string
my_string <- "Hey my name is Douglas"
#check if "Steve" is in string
grepl(my_character, my_string, fixed=TRUE)
[1] FALSE
Since “Steve” does not exist in the string, the grepl() function returns FALSE.
Example 2: Check if Character is in String Using stringr Package
The following code shows how to use the str_detect() function from the stringr package to check if the string “Doug” exists in a particular string:
library(stringr)
#define character to look for
my_character <- "Doug"
#define string
my_string <- "Hey my name is Douglas"
#check if "Doug" is in string
str_detect(my_string, my_character)
[1] TRUE
The str_detect() function returns TRUE since “Doug” is in the string.
Note that we can also use the following syntax to check if several characters exist in the string:
library(stringr)
#define vector of characters to look for
my_characters <- c("Doug", "Steve", "name", "He")
#define string
my_string <- "Hey my name is Douglas"
#check if each character is in string
str_detect(my_string, my_characters)
[1] TRUE FALSE TRUE TRUE
From the output we can see:
- “Doug” exists in the string.
- “Steve” does not exist in the string.
- “name” exists in the string.
- “He” exists in the string.
Related: How to Use str_detect() Function in R (3 Examples)
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Remove Last Character from String in R
How to Find Location of Character in a String in R
How to Select Columns Containing a Specific String in R