as factor in R: How to Use as.factor() Function

To create a factor variable in R, use the factor function. Let’s talk about as.factor() function in R Language.

as.factor in R

The as.factor() is a built-in R function that converts a column from numeric to factor. The as.factor() method takes column or data frame x as an argument and returns the requested column specified as a factor rather than numeric.

Syntax

as.factor(x)

Parameters

x: The as.factor() function takes x as a column in an object of class or data frame.

Return value

It returns the original object of a class with the requested column specified as a factor rather than numeric.

Example

Let’s define a character vector using the c() function.

data <- c("m", "l", "a")

as.factor(data)

Output

[1] m l a
Levels: a l m

Using as.factor() function to the character object containing numbers

We can apply the as.factor() function to the integer vector and see the output.

data <- c("1.1", "11", "2.2", "22")

as.factor(data)

Output

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

How to Convert a Factor in R

To convert factors to text, use the as.character() function.

To convert factors to numbers, use the as.numeric() functions.

data <- c("zack", "synder", "cut")

as.factor(data)

Output

[1] zack synder cut
Levels: cut synder zack

To convert it into text, use the as.character() function.

data <- c("zack", "synder", "cut")

factr <- as.factor(data)

chr <- as.character(factr)

chr

Output

1] "zack" "synder" "cut"

Now, let’s convert a factor to numbers using as.numeric() function.

data <- c("zack", "synder", "cut")

factr <- as.factor(data)

intr <- as.numeric(factr)

intr

Output

[1] 3 2 1

Using the as.numeric() function to convert a factor to a numeric vector. You can see that in the output that the numeric codes correspond to the factor levels. For example, “zack corresponds to 3, “snyder corresponds to 2, and “cut” fits 1.

Conclusion

The as.factor() function is a wrapper for factor, allowing quick return if the input vector is already a factor.

That is it for this tutorial.

Leave a Comment