Convert column to categorical in R

Convert Column to categorical in R is done using as.factor(). Let’s see how to convert column type to categorical in R with an example.

Let’s first create the dataframe

df1 = data.frame(Name = c('George','Andrea', 'Micheal','Maggie','Ravi','Xien','Jalpa'), 
                 Mathematics_score=c(45,78,34,89,66,72,87),
                 IS_PASS=c(0,1,0,1,1,1,1))
df1

so the dataframe will be

convert column to categorical in R 1

And the column types are

Str(df1)

convert column to categorical in R 2

IS_PASS column  is numerical.

 

Convert column to categorical in R:

Now let’s convert numerical IS_PASS column to categorical by using as.factor()

df1$IS_PASS = as.factor(df1$IS_PASS) # converting to categorical
Str(df1)

So the result is

convert column to categorical in R 3

 

                                                                                   

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts