Convert a Vector into Factor in R Programming – as.factor() Function

as.factor() Function in detail

The as.factor() function in R is used to transform a given object, typically a vector, into a factor.

Syntax:

as.factor(object)

Parameters:

  • object: A vector that needs to be converted into a factor.

Example 1: Converting a Character Vector into a Factor

In this example, we convert a character vector representing different fruit names into a factor.

# Creating a character vector
fruits <- c("Apple", "Mango", "Banana", "Mango", "Apple")

# Converting the vector into a factor
factor_fruits <- as.factor(fruits)

print(factor_fruits)

Output:

[1] Apple  Mango  Banana Mango  Apple
Levels: Apple Banana Mango

Example 2: Converting a Numeric Character Vector into a Factor

Here, we apply the as.factor() function to a character vector containing numerical values.

# Creating a numeric character vector
numbers <- c("25.6", "10.4", "42.8", "5.3")

# Converting it into a factor
factor_numbers <- as.factor(numbers)

print(factor_numbers)

Output:

[1] 25.6 10.4 42.8 5.3
Levels: 10.4 25.6 42.8 5.3

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *