R Basic

How to Use as.factor() Function in R

The as.factor() function in R is used to convert a vector object to a factor.




input: It takes x as a column in an object of class or data frame.

Return value

It returns a “factor object”.

Example 1: Converting numeric vector to factor

mixed_vec <- c(1.1, 11, 2.2, 19)



[1] 1.1 11 2.2 19
Levels: 1.1 2.2 11 19

Example 2: Converting character vector to factor

char_vec <- c("zack", "john", "jian")



[1] zack john jian
Levels: cut synder zack

Example 3: Converting data frame column to factor

df <- data.frame(
  name = c("Krunal", "Ankit", "Rushabh"),
  score = c(85, 90, 78),
  subject = c("Math", "Math", "History"),
  grade = c("10th", "11th", "11th")

df$grade <- as.factor(df$grade)



[1] 10th 11th 11th
Levels: 10th 11th

Difference between as.factor() and factor()

The main difference between as.factor() and factor() is that as.factor() is an abbreviated form of factor() that can sometimes run faster. The as.factor() coerces its argument to a factor, while factor() allows for more optional arguments.

Based on my experience, I created a table that summarizes the key differences between the two functions:

Function Description
as.factor() Converts its argument to a factor.
factor() Converts its argument to a factor and allows for more optional arguments, such as levels, ordered, and exclude.

That’s it.

Recent Posts

R tapply() Function

The tapply() function is used to apply a function to subsets of a vector, categorized…

2 months ago

How to Use qnorm() function in R

The qnorm() function is used to calculate quantiles of the standard normal distribution (also known…

2 months ago

How to Create Strip Charts in R

To create simple strip charts in R, use the built-in stripchart() method. It provides a simpler…

2 months ago

How to Create Pie Charts in R [Real-life Project]

A pie chart is a data visualization type representing data in a circular format. Each…

2 months ago

R facet_grid() Function

The facet_grid() function is used when you want to create a matrix of panels defined…

2 months ago

How to Create Basic Ridgeline Plot in R

The ridgeline plot in R is used to visualize the distribution of a numerical value…

2 months ago