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.

Syntax

as.factor(x)

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(iris)

Output

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:

iris$Petal.Width<-as.factor(iris$Petal.Width)
str(iris)

Output

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
as.factor(heroes)

Output

[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