0
0
R Programmingprogramming~5 mins

Factor creation in R Programming

Choose your learning style9 modes available
Introduction

A factor in R is used to store categorical data. It helps group values into categories, making it easier to analyze and summarize data.

When you have survey answers like 'Yes', 'No', or 'Maybe' and want to treat them as categories.
When you want to group data by types, such as colors: 'Red', 'Blue', 'Green'.
When preparing data for graphs that show categories instead of numbers.
When you want to save memory by storing repeated category labels efficiently.
Syntax
R Programming
factor(x, levels = NULL, labels = NULL, ordered = FALSE)

x is the vector of values you want to turn into categories.

levels lets you set the order or which categories to include.

Examples
Creates a factor from a character vector of colors.
R Programming
colors <- c('red', 'blue', 'red', 'green')
f <- factor(colors)
Creates a factor with levels in a specific order.
R Programming
sizes <- c('small', 'large', 'medium', 'small')
f <- factor(sizes, levels = c('small', 'medium', 'large'))
Creates an ordered factor where categories have a natural order.
R Programming
ratings <- c('low', 'high', 'medium')
f <- factor(ratings, ordered = TRUE, levels = c('low', 'medium', 'high'))
Sample Program

This program creates a factor from a list of colors, then prints the factor and its levels.

R Programming
colors <- c('red', 'blue', 'red', 'green')
f <- factor(colors)
print(f)
print(levels(f))
OutputSuccess
Important Notes

Factors store categories as numbers internally but show labels when printed.

Ordering factors is useful for comparisons and sorting.

Summary

Factors help manage categorical data in R.

You can set the order and labels of categories.

Use factors to make data analysis and plotting easier.