![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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 −
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$x)
Output
[1] "integer"
Check class of column y
Use class function to find whether column y is categorical or not −
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$y)
Output
[1] "character"
Check class of column z
Use class function to find whether column z is categorical or not −
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"
Advertisements