HappiomHappiom
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
Expand All Collapse All
  • R Code Examples
    • R Code to Create and Manipulate Vectors
    • R Code to Work with Data Frames
    • R Code to Handle Factors and Categorical Data
    • Example R Code for Basic Data Visualization with ggplot2
    • R Code to Aggregate Data Using dplyr
    • R Code to Apply Functions with lapply and sapply
    • R Code to Handle Missing Data
    • Example R Code for String Manipulation with stringr
    • R Code to Transform Data with tidyr
    • R Code to Perform ADF Test
    • R Code to Perform Data Import and Export with CSV
    • R Code for Filtering Data
    • R Code for Easily Summarizing Data
    • R Code to Perform Linear Regression for Statistical Analysis
    • R Code to Perform t-tests for Statistical Analysis
    • Example R Code for Time Series Analysis
    • R Code for Doing Web Scraping with Examples
    • R Code to Showcase Geospatial Analysis
    • Example R Code to Filter Multiple Conditions (for Data Manipulation)

R Code to Handle Factors and Categorical Data

Creating Factors

Factors are a key feature in R for handling categorical data. They are used to represent variables that have a fixed number of unique values or levels. This makes factors ideal for managing categorical data such as gender, color, or department.

  • In R, factors store both the values and their levels. This allows for efficient data analysis and manipulation.
  • Each factor level is assigned an integer, making it easier to perform operations on categorical variables.
  • You can create and inspect factors using simple commands. Functions like `levels()` and `table()` help explore the levels and frequencies of factors. This is crucial for understanding the distribution of categorical data.

Factors can also be modified and converted. You can change levels or recode factors to suit your analysis needs. Additionally, factors can be converted to numeric values when needed for further computations.

# Create a factor
color <- factor(c("red", "blue", "green", "blue", "red"))
color

Output:

[1] red  blue green blue red 
Levels: blue green red

Inspecting Factors

To inspect factors, use functions like levels() and table(). These functions show factor levels and frequencies.

# Check levels of the factor
levels(color)

# Count occurrences of each level
table(color)

Output for levels:

[1] "blue"  "green" "red" 

Output for table:

color
 blue green   red 
    2     1     2

Modifying Factor Levels

You can modify factor levels using levels() or by re-coding the factor.

# Recode factor levels
color <- factor(color, levels = c("blue", "green", "red", "yellow"))
color

# Add a new level to the factor
levels(color) <- c(levels(color), "yellow")
color

Output after recoding levels:

[1] red  blue green blue red 
Levels: blue green red yellow

Converting Factors to Numeric

To convert factors to numeric values, first convert them to characters. Then, convert the characters to numeric values.

# Convert factor to numeric
numeric_color <- as.numeric(color)
numeric_color

Output:

[1] 3 1 2 1 3

Handling Categorical Data in Data Frames

When working with data frames, categorical data is often represented as factors. You can convert columns to factors and perform operations.

# Create a data frame with categorical data
df <- data.frame(
  Name = c("Alice", "Bob", "Charlie", "Bob", "Alice"),
  Department = factor(c("HR", "Finance", "IT", "Finance", "HR"))
)
df

# Convert the Department column to a factor
df$Department <- factor(df$Department)
df

Output:

     Name Department
    1 Alice         HR
    2   Bob    Finance
    3 Charlie         IT
    4   Bob    Finance
    5 Alice         HR
Related Articles
  • R Code to Transform Data with tidyr
  • Example R Code for String Manipulation with stringr
  • R Code to Handle Missing Data
  • R Code to Apply Functions with lapply and sapply
  • R Code to Aggregate Data Using dplyr
  • Example R Code for Basic Data Visualization with ggplot2

No luck finding what you need? Contact Us

Previously
R Code to Work with Data Frames
Up Next
Example R Code for Basic Data Visualization with ggplot2
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2025 Happiom. All Rights Reserved.