How to check if a character column only contains alphabets in R data frame?

To check if a character column only contains alphabets in R data frame, we can follow the below steps −

  • First of all, create a data frame with a character column.
  • Then, use grepl function to check if all the values in the column contains only alphabets.

Example 1

Let's create a data frame as shown below −

x<-sample(c("India","UK","USA","Japan","China2"),20,replace=TRUE)
df1<-data.frame(x)
df1

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

   x
1 India
2 USA
3 China2
4 USA
5 Japan
6 UK
7 China2
8 Japan
9 USA
10 Japan
11 Japan
12 Japan
13 Japan
14 India
15 Japan
16 UK
17 India
18 UK
19 India
20 USA

Check whether data frame column contains only alphabets

Using grepl function to check whether column x contains values only having alphabets −

x<-sample(c("India","UK","USA","Japan","China2"),20,replace=TRUE)
df1<-data.frame(x)
grepl("^[A-Za-z]+$",df1$x)

Output

[1] TRUE TRUE FALSE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE
[13] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

Example2

Let’s create a data frame as shown below −

y<-sample(c("1","23","14","11","1F","3"),20,replace=TRUE)
df2<-data.frame(y)
df2

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

   y
1  11
2  1F
3  1
4  11
5  23
6  1F
7  11
8  23
9  14
10 14
11 1F
12 14
13 1F
14 11
15 1
16 23
17 1F
18 1
19 3
20 23

Check whether data frame column contains only alphabets

Using grepl function to check whether column y contains values only having alphabets −

y<-sample(c("1","23","14","11","1F","3"),20,replace=TRUE)
df2<-data.frame(y)
grepl("^[A-Za-z]+$",df2$y)

Output

[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
Updated on: 2026-03-11T22:50:57+05:30

978 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements