How to Check If Characters are Present in String in R

To check if characters are present in the R string, you can use the “grepl()” function. The “grepl()” function returns TRUE if the specified sequence of characters is present in the string and FALSE if the specified sequence of characters is not present in the string.

Example

string_first <- "TheLastOfUs"

value_first <- "L"

grepl(value_first, string_first)

value_second <- "G"

grepl(value_second, string_first)

Output

[1] TRUE
[1] FALSE

The first time, the grepl() function returns TRUE because the character “L” is present in the string “TheLastOfUs”.

The second time, the grepl() function returns FALSE because the character “G” is not present in the string “TheLastOfUs”.

Leave a Comment