How to Check If Characters are Present in String in R

There are the following methods to check if characters are present in the string in R.

  1. Method 1: Using the grepl() function
  2. Method 2: Using str_detect() function from the stringr package.

Method 1: Using the grepl() function

You can use the grepl() function to check if characters are present in the string in R. It returns a Boolean value TRUE if the specified sequence of characters is present in the string and FALSE otherwise.

# define character to look for
character <- "KB"

# define string
string <- "Hey my name is KB"

# check if "KB" is in string
grepl(character, string)

character_2 <- "KL"

# check if "KL" is in string
grepl(character_2, string)

Output

[1] TRUE
[1] FALSE

In the above code example, we defined a character string character to look for and a string to search within.

The grepl() function checks if the character string character is present in the string. The output will be a logical value of TRUE if the character string is found and FALSE otherwise.

Then, a new character string character_2 is defined, and the grepl() function is used again to check if character_2 is present in the string. The output will be FALSE since character_2 is not present in the string.

Method 2: Using the str_detect() function

The str_detect() function is part of the stringr package in R. It detects the presence or absence of a certain pattern in a string. This function returns TRUE if the pattern is present in the string and FALSE otherwise.

library(stringr)

# define character to look for
character <- "KB"

# define string
string <- "Hey my name is KB"

# check if "KB" is in string
str_detect(string, character)

character_2 <- "KL"

# check if "KL" is in string
grepl(character_2, string)

Output

[1] TRUE
[1] FALSE

As expected, if the string contains a character, it returns TRUE otherwise FALSE.

That’s it.

Leave a Comment