EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials R Programming Tutorial Factors in R
Secondary Sidebar
R programming Tutorial
  • Data Structure
    • R list
    • Arrays in R
    • Data Frames in R
    • Factors in R
    • R Vectors
  • Basic
    • What is R Programming Language
    • Careers in R Programming
    • Install R
    • List of R Packages
    • Introduction of R Tools Technology
    • R Programming Language
    • DataSet in R
    • What is RStudio?
    • R-studio-Functions
    • R Packages
    • Time series?in R
    • R Data Types
    • R for data science
    • R Operators
    • R Data Frame
    • R Analytics Tool
    • R Tree Package
    • Vectors in R
  • Control statement
    • If Statement in R
    • If Else Statement in R
    • Else if in R
    • Switch Statement in R
  • Loops
    • Loops in R
    • For Loop in R
    • Nested For Loop in R
    • While Loop in R
    • Next in R
  • Chart/graphs
    • Graphs in R
    • Bar Charts in R
    • Pie Chart in R
    • Histogram in R
    • Line Graph in R
    • Plot Function in R
    • Scatterplot in R
    • R Boxplot labels
  • Regression in R
    • Simple Linear Regression in R
    • Linear Regression in R
    • Multiple Linear Regression in R
    • Logistic Regression in R
    • Poisson Regression in R
    • OLS Regression in R
    • P-Value in Regression
  • Anova in R
    • ANOVA in R
    • One Way ANOVA in R
    • Two Way ANOVA in R
  • Advanced
    • Statistical Analysis with R
    • R String Functions
    • Data Exploration in R
    • R CSV Files
    • KNN Algorithm in R
    • Sorting in R
    • lm Function in R
    • Hierarchical Clustering in R
    • R Normal Distribution
    • Binomial Distribution in R
    • Decision Tree in R
    • GLM in R
    • Arima Model in R
    • Linear Model in R
    • Predict Function in R
    • Survival Analysis in R
    • Standard Deviation in R
    • Statistical Analysis in R
    • Predictive Analysis?in R
    • T-test in R
    • Database in R
  • Programs
    • Functions in R
    • Boxplot in R
    • R Program Functions
    • Factorial in R
    • Random Number Generator in R
  • Interview question
    • R Interview Questions

Related Courses

R Programming Certification Course

Statistical Analysis Course Training

All in One Data Science Courses

Factors in R

By Priya PedamkarPriya Pedamkar

Factors in R

Introduction to Factors in R

Factors in R programming language is a type of variable that is of limited types in the data set. Factor variables are also resembled as categorical variables. The factor variables in R have a significant impact on data processing and data analysis. Machine learning algorithms process the factors differently as compared to continuous data. As a programmatic approach of the factor variables are converted to a corresponding integer variable while developing and generating the machine learning models and again mapped to its character values to represent the predictive analysis. An example of factors in R can be the group type of a particular product which is denoted as category1,category2,category3 in the data set.

Advantages of a Factor

  • It can store both integers and strings

1. In the case of integers

data = c(5,6,6,6,7,5,7,6,7,5,6,7)
factor_data = factor(data)
factor_data

Output

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

factors in R

2. In the case of strings

y = factor(c("Bike","Car","Cycle","Truck","Car","Bike","Cycle","Truck","Car","Bike"))
y

Output

Factors

y = factor(c("Bike","Car","Cycle","Truck","Car","Bike","Cycle","Truck","Car","Bike"),levels = c("Car","Bike","Cycle","Truck","Train"))
y

Output

factorial-2

  • Very useful when the columns have a limited number of unique values
Name Mode of Travel
John Truck
Shaw Car
Lee Cycle
Musan Bike
Lozy Truck
Riya Car
Mij Cycle

Here we have a limited number of unique values in column 2.

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,650 ratings)
  • It helps to rectify the strings with typos (Typing Errors).

How to Create a Factor in R?

We can create factors by using code factors ().

Explore more about factor().

factor(x = character(), levels, labels = levels, ordered = is.ordered(x))

Where,

X is a set of categorical data. As we already discussed it should be a string or integers.

Levels are set of value which can be taken by X. Levels contains all the unique value available in the column (x).

Labels as the name suggest labeling of the data available at X.

Ordered determines if the levels should be ordered in any particular order.

Example #1

y = factor(c("Bike","Car","Cycle","Truck","Car","Bike"))
y

Output:

factors in R

Example #2

y = factor(c("Bike","Car","Cycle","Truck","Car","Bike","Cycle","Truck","Car","Bike"),levels = c("Car","Bike","Cycle","Truck","Train"))
y

Output:

factors in R

In example 2 we can see that we can define “Levels” also.

Now let’s see more about factors by using Str(y).

y = factor(c("Bike","Car","Cycle","Truck","Car","Bike","Cycle","Truck","Car","Bike"),levels = c("Car","Bike","Cycle","Truck","Train"))
y

Output:

factors in R5

str(y)

Output:

factors

It is clearly seen that factors are stored as integer vectors and levels are stored as a character vector, and the individual elements are actually stored as indices.

  • Now we will see how to access components of a factor

y = factor(c("Bike","Car","Cycle","Truck","Car","Bike","Cycle","Truck","Car","Bike"),levels = c("Car","Bike","Cycle","Truck","Train"))
y

Output:

factors

y[2]     # helps to access 2nd element

Output:

factors

x[c(3, 4)]     # helps to access 3rd and 4th element

Output

factors

x[-1]     # access all except 1st element

Output:

factors

  • Now we will see how to modify a factor.

y = factor(c("Bike","Car","Cycle","Truck","Car","Bike","Cycle","Truck","Car","Bike"),levels = c("Car","Bike","Cycle","Truck","Train"))
y

Output:

factors

y[3] = "Truck"       #modifty third element
y

Output

factors

Adding to a factor:

y[10] = "Car"
y

Output:

fact

Please note that we can’t assign anything in a factor that is not a part of the levels.

y[4] = "Plane"Warning message:In `[<-.factor`(`*tmp*`, 4, value = "Plane") :  invalid factor level, NA generated

Output:

factors

In this example we can see that “Plane” is not a part of our level, hence we got a warning message which says “Plane” is an invalid factor level.

Convert Data into a Factor

Data Is Available in Plenty, and It Is Tough Every Time to Write Down a Complete Word in The Code, so For This, We Will Convert the Data Into a Factor First Then Convert the Factor Into a Character or Number as Per Our Convenience.

Let’s now work on some real data. Where we have 50 observations and applicants provide their work direction. Like John travel towards north for his job duties or Sam travel towards South direction for his work duties.

direction <- c("West", "East", "North","West", "South","East","South","East", "South","East", "South","West", "South","East","South","East", "South","South","West","East", "South","West", "South","East","South","East", "South","West","East", "South","West", "South","East","South","East", "South", "South","West", "South","West","East", "South","West", "South","East","South","East", "South", "South","West")
direction.factor = factor(direction)
direction.factor

Output:

Factors in R

Levels: East North South West

Now if we want to convert the factor into a character vector:

We will use as.character() code.

as.character(direction.factor)

Output:

Factors in R

Or we want to convert the factor into a numeric vector:

We will use as.numeric() Code.

as.numeric(direction.factor)

Output:

Factors in R

Recommended Articles

This is a guide to Factors in R. Here we discuss the introduction, Advantages of a factor, How to create a factor in R along with the Outputs. You can also go through our other suggested articles to learn more–

  1. Spark SQL Dataframe
  2. R Data Types
  3. Multidimensional Database
  4. AWS Data Pipeline
Popular Course in this category
R Programming Training (13 Courses, 20+ Projects)
  13 Online Courses |  20 Hands-on Projects |  120+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Statistical Analysis Training (15 Courses, 10+ Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
3 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more