Skip to main content
HomeAbout RLearn R

Factors in R Tutorial

Learn about the factor function in R, along with an example, and it's structure, order levels, renaming of the levels, and finally, with the ordering of categorical values.
Jun 2020  · 5 min read
banner

The factors are the variable in R, which takes the categorical variable and stores data in levels. The primary use of this function can be seen in data analysis and specifically in statistical analysis. Also, it helps to reduce data redundancy and to save a lot of space in the memory.

Note: A categorical variable is those variables that take values based on the labels or names. For example, the blood type of a human can be A, B, AB, or O.

factor function

Usage: Categorize the data which have less number of values.
Parameters:factor(v):v can be vector of values.

Let's see the example of a factor in action.

You can see below code where there are two categorical variables, namely "Male" and "Female", also called factor values.

gender <- c("Male","Female","Female","Male","Female")

Let's create a factor for the gender where 'factor(gender)' is used and saved to a variable called 'gender.factor'.

gender.factor <- factor(gender)
gender.factor
  1. Male
  2. Female
  3. Female
  4. Male
  5. Female
Levels:
  1. 'Female'
  2. 'Male'

The above code gives the output as below:

Male Female Female Male Female
Levels:
'Female' 'Male'

You can see above where values are printed the same as the input vector. Additionally, 'Levels', which are 'Female' and 'Male' are sorted alphabetically.

Structure of factor function

Let's examine the structure for factor function by using 'str(gender.factor)' in the code below.

str(gender.factor)
 Factor w/ 2 levels "Female","Male": 2 1 1 2 1 
Factor w/ 2 levels "Female","Male": 2 1 1 2 1

The above output shows that there is a factor of 2 levels. factor converts the character vector as gender into a vector of integer values. "Female" is the first level encoded as 1 whereas the "Male" is the second level, encoded as 2.

Also, the primary purpose of encoding from character to numeric is that the categories can belong, repeating is redundant, which can take a lot of space in the memory. But, using factor reduces all the burden to save up space in the memory.

Changing Order Levels

Let's change the order levels, so the levels of "Female" will become 2 and "Male" as 1.

Let's make a new factor for the gender by changing the levels of "Male" and "Female' by passing it as a vector input to the "levels". Finally, the resultant output is saved to the variable named "gender.factor2'.

gender.factor2 <- factor(gender,levels=c("Male","Female"))
gender.factor2
str(gender.factor2)
  1. Male
  2. Female
  3. Female
  4. Male
  5. Female
Levels:
  1. 'Male'
  2. 'Female'
 Factor w/ 2 levels "Male","Female": 1 2 2 1 2

The 'gender.factor2' is printed along with it's structure printed using 'str(gender.factor2)' where the following changes can be seen.

Male Female Female Male Female
 Levels:
'Male' 'Female'
 Factor w/ 2 levels "Male","Female": 1 2 2 1 2

The above code gives the output where the encoding of "Male" is 1, and "Female" is 2. It's different from 'gender.factor', which was opposite in the above code.

Renaming a Factor levels

Let's change the name of the vector values in the input by specifying the regular use of 'levels' as the first argument with values "Male" and "Female" and the expected changed vector values using 'labels' as the second argument with "Gen_Male" and "Gen_Female" respectively.

factor(gender,levels = c("Male","Female"),labels = c("Gen_Male","Gen_Female"))
  1. Gen_Male
  2. Gen_Female
  3. Gen_Female
  4. Gen_Male
  5. Gen_Female
Levels:
  1. 'Gen_Male'
  2. 'Gen_Female'
Gen_Male Gen_Female Gen_Female Gen_Male Gen_Female
 Levels:
'Gen_Male' 'Gen_Female'

The above code gives the output where the name is changed for "Male" to "Gen_Male" and "Female" to "Gen_Female".

Ordering a Categorical Variable

Let's look at a different example when dealing with ordinal categorical values where ordered matters. For instance, for the size of a pant, there might be a size which is considered as Large as "L", Extra Large as "XL" and Extra extra Large as "XXL" is arranged in ascending order. The code below contains the collection of vector input of characters "L", "XL" and "XXL" and stored to 'pant'. 'pant.factor' is the variable which has parameter containing levels arranged in ascending order as 'levels = c("L", "XL", "XXL")' and finally 'ordered = TRUE', which makes the sorting possible according to your need.

pant <- c("XL","L","XL","XXL","L","XL")
pant.factor <- factor(pant,ordered = TRUE,levels = c("L","XL","XXL"))
pant.factor
pant.factor[1] > pant.factor[2]
  1. XL
  2. L
  3. XL
  4. XXL
  5. L
  6. XL
Levels:
  1. 'L'
  2. 'XL'
  3. 'XXL'

TRUE

XL L XL XXL L XL
 Levels:'L'< 'XL' < 'XXL'
TRUE

The above output shows the normal output at first where all the vector values (XL, L, XL, XXL, L, XL) are printed out by using 'pant.factor'. The levels of vector values 'L' < 'XL' < 'XXL' are arranged in the ascending order, which is printed at the console. Also, 'pant.factor[1] > pant.factor[2]' compares whether "XL" is greater than "L", which results in TRUE being printed.

Congratulations

Congratulations, you have made it to the end of this tutorial!

In this tutorial, you have covered the factor function in R, along with an example, and its structure, order levels, renaming of the levels, and finally, with the ordering of categorical values.

If you would like to learn more about R, take DataCamp's Introduction to R course.

Check out out tutorial on Using Functions in R.
 

Topics

R Courses

Course

Introduction to R

4 hr
2.7M
Master the basics of data analysis in R, including vectors, lists, and data frames, and practice R with real data sets.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

Data Science in Finance: Unlocking New Potentials in Financial Markets

Discover the role of data science in finance, shaping tomorrow's financial strategies. Gain insights into advanced analytics and investment trends.

Shawn Plummer

9 min

5 Common Data Science Challenges and Effective Solutions

Emerging technologies are changing the data science world, bringing new data science challenges to businesses. Here are 5 data science challenges and solutions.
DataCamp Team's photo

DataCamp Team

8 min

Navigating R Certifications in 2024: A Comprehensive Guide

Explore DataCamp's R programming certifications with our guide. Learn about Data Scientist and Data Analyst paths, preparation tips, and career advancement.
Matt Crabtree's photo

Matt Crabtree

8 min

A Data Science Roadmap for 2024

Do you want to start or grow in the field of data science? This data science roadmap helps you understand and get started in the data science landscape.
Mark Graus's photo

Mark Graus

10 min

R Markdown Tutorial for Beginners

Learn what R Markdown is, what it's used for, how to install it, what capacities it provides for working with code, text, and plots, what syntax it uses, what output formats it supports, and how to render and publish R Markdown documents.
Elena Kosourova 's photo

Elena Kosourova

12 min

Introduction to DynamoDB: Mastering NoSQL Database with Node.js | A Beginner's Tutorial

Learn to master DynamoDB with Node.js in this beginner's guide. Explore table creation, CRUD operations, and scalability in AWS's NoSQL database.
Gary Alway's photo

Gary Alway

11 min

See MoreSee More