# The as.factor() function in R

In R, the factor is a data type that categorizes and stores the data as levels. In this tutorial, we will show you how to use the as.factor() function and compare the function and the factor() function. Let’s move on.

## The as.factor() function in R

The as.factor() function transforms a vector into a factor. In our previous article, we talked about the factor() function to create a factor. Please take a visit if you need clarification about the factor data type.

Syntax:

as.factor(v)

Parameters:

• v: A vector to convert into a factor object.

## Examples of the as.factor() function

The as.factor() function is simple to understand and use. We will show you the usage of the function in the examples below.

### Use the as.factor() function with a vector

First, we will show you an example using the as.factor() function with a vector.

Code:

color <- c("red", "orange", "yellow", "orange", "red")
fact_object <- as.factor(color)

cat("The factor object from a vector is:\n")
print(fact_object)

Result:

The factor object from a vector is:
[1] red orange yellow orange red
Levels: orange red yellow

### Use the as.factor() function with a column

The as.factor() function can be applied to a data frame column. Look at the following example for detailed implementation.

Code:

shape <- c("square", "oval", "circle", "star", "heart")
color <- c("red", "orange", "yellow", "orange", "red")
df <- data.frame(shape, color)
fact_object <- as.factor(df\$color)

cat("The factor object from a column is:\n")
print(fact_object)

Result:

The factor object from a column is:
[1] red orange yellow orange red
Levels: orange red yellow

## Difference between the as.factor() and factor() function

The as.factor() function is considered as a wrapper for factor. It only makes a vector become a factor object, and there is no way to set “labels”, “levels” and “ordered” parameters when using the function. As a result, the function also spends less time than the factor() function to execute. Look at the following example to compare the runtime of two functions.

Code:

color <- c("red", "orange", "yellow", "orange", "red")

# Calcualte execution time for the factor() function
begin1 <- Sys.time()
result1 <- factor(color)
finish1 <- Sys.time()
time1 <- finish1 - begin1

# Calcualte execution time for the as.factor() function
begin2 <- Sys.time()
result2 <- as.factor(color)
finish2 <- Sys.time()
time2 <- finish2 - begin2

if (time1 < time2) {
cat("runtime of the factor() function is smaller")
} else {
cat("runtime of the as.factor() function is smaller")
}

Result:

runtime of the as.factor() function is smaller

## Summary

In summary, the as.factor() function transforms a vector into a factor object. The function is a wrapper of factor and runs faster than the factor() function.

Maybe you are interested:

Posted in R