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.
It returns a “factor object”.
mixed_vec <- c(1.1, 11, 2.2, 19) as.factor(mixed_vec)
 1.1 11 2.2 19 Levels: 1.1 2.2 11 19
char_vec <- c("zack", "john", "jian") as.factor(char_vec)
 zack john jian Levels: cut synder zack
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) print(df$grade)
 10th 11th 11th Levels: 10th 11th
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:
|as.factor()||Converts its argument to a factor.|
|factor()||Converts its argument to a factor and allows for more optional arguments, such as |