To check if a string contains only alphabets in R, you can use regular expressions or iterate through each character and check if it is an alphabet using functions like grepl
and gsub
.
In this example,
grepl
function to check if the string matches the pattern.containsOnlyAlphabets
to TRUE
, otherwise FALSE
.str1 <- 'HelloWorld'
pattern <- '^[A-Za-z]+$'
containsOnlyAlphabets <- grepl(pattern, str1)
print(paste('String contains only alphabets:', containsOnlyAlphabets))
String contains only alphabets: TRUE
In this example,
str2
with a value of 'Hello123'
.gsub
to remove non-alphabetic characters.containsOnlyAlphabets
to TRUE
, otherwise FALSE
.str2 <- 'Hello123'
str2 <- gsub('[^A-Za-z]', '', str2)
containsOnlyAlphabets <- nchar(str2) > 0
print(paste('String contains only alphabets:', containsOnlyAlphabets))
String contains only alphabets: FALSE
In this tutorial, we learned How to Check if String contains only Alphabets in R language with well detailed examples.