Understanding Factors in R | Beginning R Programming – Part 8

When working with categorical data or categories, it’s useful to treat these as factor levels. Learn how to cast character strings or numbers as factors so that they are treated as categories.

Categories or levels are referred to as factors in R
this R objects allows us
to treat categorical data accordingly
so that it’s not incorrectly interpreted
in the program as a number or a
string of text
if we have a look at the
structure of our “animal” data frame
we created in the video on vectors we can
see it includes three vectors here
“animals”, “weight”, and “class.tag”
if we look closely at “class.tag” here
we can see that this has been treated as an integer
number when it is in fact a class
represented as a number
or tagged that its number class
to treat this accordingly
we need to turn it into a factor so that
one, two, and three are factor levels
or class labels
So we can simply do this
using the “as.factor” function
or the “factor” function in R
So we’re going to override the numeric
“class.tag” vector and treat it as
a factor in our “animal” data set so
to do this we just simply refer to our data set
and we’re looking at the “class.tag” variable
gonna override this
by turning all those
values that we have there into factors
So, once again, in our “animal” data set
looking at our “class.tag” variable
So now if we look at the structure of “animals” data
We can see that it is treated accordingly
it is now factors so we have
three distinct factor levels
factor level 1, 2, & 3 as our kind of class labels
in the next video we’ll look at
calling pre-built functions in R

Download the Data Set
How to Install R

Part 9: 
Calling Pre-built Functions in R

Part 7: 
Working with Vectors in R

Full Series:
Beginning R Programming

More Data Science Material:
[Video] A/B Testing in Minutes
[Blog] R Algorithms in AI And Computing Forces Working Together
[Blog] R Language Programming for Excel Users


Rebecca Merrett
About The Author
- Rebecca holds a bachelor’s degree of information and media from the University of Technology Sydney and a post graduate diploma in mathematics and statistics from the University of Southern Queensland. She has a background in technical writing for games dev and has written for tech publications.


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>