as.factor() Function in R

as.factor() function is used to encode a vector as a factor. Usually, it converts a column with a numeric data type to a factor. This guide will demonstrate using the as.factor() function in R.



Here, x is the vector to be converted.

Example 1: Converting a Column from Numeric to Factor

We are using the default iris dataframe for this example. To check the characteristics of a dataframe, we use the str() function.



str function
Structure of the iris dataframe.

As you can see, the column Petal.Width has a numeric datatype. To convert it into a factor, run the following code:



Numeric to Factor
Converting the numeric datatype of the column to factor.

In this example, we have converted the Petal.Width column of the iris dataframe into a factor.

Example 2: Converting a Vector into a Factor

#creating a vector
heroes <-c('Batman', 'Superman','Thor', 'Ironman', 'Aquaman')
#converting vector to factor


[1] Batman Superman Thor Ironman Aquaman
Levels: Aquaman Batman Ironman Superman Thor

In this example, we have converted a vector into a factor using as.factor().

Leave a Comment