The as.factor() function in R is used to convert a vector object to a factor.
as.factor(input)
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)
Output
[1] 1.1 11 2.2 19
Levels: 1.1 2.2 11 19
char_vec <- c("zack", "john", "jian")
as.factor(char_vec)
Output
[1] 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)
Output
[1] 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:
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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
The tapply() function is used to apply a function to subsets of a vector, categorized…
The qnorm() function is used to calculate quantiles of the standard normal distribution (also known…
To create simple strip charts in R, use the built-in stripchart() method. It provides a simpler…
A pie chart is a data visualization type representing data in a circular format. Each…
The facet_grid() function is used when you want to create a matrix of panels defined…
The ridgeline plot in R is used to visualize the distribution of a numerical value…