# How to check if a column is categorical in R data frame?

To check if a column is categorical in R data frame, we can follow the below steps −

• First of all, create a data frame.
• Use class function to check the class of the column.

## Create the data frame

Let's create a data frame as shown below −

Live Demo

x<-rpois(25,2)
y<-sample(LETTERS[1:4],25,replace=TRUE)
z<-factor(sample(c("Low","Medium","High"),25,replace=TRUE))
df<-data.frame(x,y,z)
df

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

   x y  z
1  4 D High
2  1 B High
3  1 C High
4  2 A Medium
5  3 B High
6  2 D Medium
7  2 C Low
8  1 A Low
9  5 D Medium
10 3 D Low
11 1 B Medium
12 3 B High
13 5 C Medium
14 4 C Medium
15 1 B High
16 1 C Low
17 3 A Medium
18 1 D Low
19 1 B High
20 1 D Medium
21 3 B High
22 4 A Low
23 2 C High
24 2 A Medium
25 5 B High

## Check class of column x

Use class function to find whether column x is categorical or not −

Live Demo

x<-rpois(25,2)
y<-sample(LETTERS[1:4],25,replace=TRUE)
z<-factor(sample(c("Low","Medium","High"),25,replace=TRUE))
df<-data.frame(x,y,z)

### Output

[1] "character"

## Check class of column z

Use class function to find whether column z is categorical or not −

Live Demo

x<-rpois(25,2)
y<-sample(LETTERS[1:4],25,replace=TRUE)
z<-factor(sample(c("Low","Medium","High"),25,replace=TRUE))
df<-data.frame(x,y,z)
class(df\$z)

### Output

[1] "factor"