Introduction
Factors are data objects used for the purpose of categorizing data and then storing them under levels. They can be used for storage of both strings and integers. Factors are only useful in the columns with a limited number of unique values. They are good in data analysis and statistical modeling.
Creation of Factors
To create factors in R, we use the factor() method and use a vector as the input. Consider the example given below showing how this function can be used:
- d <- c("East","West","East","North","North","East","West","West","West","East","North")
Let us now see the contents of the vector:
- > d <- c("East","West","East","North","North","East","West","West","West","East","North")
- > d
- [1] "East" "West" "East" "North" "North" "East" "West" "West" "West"
- [10] "East" "North"

To check whether d is a factor or not, we use the is.factor() attribute, as shown below:
- is.factor(d)
The script returns the following:
- > d <- c("East","West","East","North","North","East","West","West","West","East","North")
- > d
- [1] "East" "West" "East" "North" "North" "East" "West" "West" "West"
- [10] "East" "North"
- >
- > is.factor(d)
- [1] FALSE

Object d is not a factor. It is a vector. We need to call the factor() method and pass the name of the vector to it.
The vector will be changed to a factor:
- # Applying the factor function.
- factor_data <- factor(d)
- >
- > factor_data <- factor(d)
- >
Let us need the contents of the factor and determine whether d is a factor or not,
- is.factor(factor_data)
Execution of the program should give the following output:
- > is.factor(factor_data)
- [1] TRUE
- >
The output shows that we already have a factor. We have successfully created a factor from a vector by calling the factor() method.
We can also create a factor from a data frame. Once you have created a data frame having a column of text data, R treats the next column as categorical data and then creates factors on it. Consider the example given below showing how this can be done:
- # Creating the vectors for the data frame.
- height <- c(140,152,164,137,166,157,112)
- weight <- c(38,49,76,54,97,22,30)
- gender <- c("male","male","female","female","male","female","male")
- > height <- c(140,152,164,137,166,157,112)
- > weight <- c(38,49,76,54,97,22,30)
- > gender <- c("male","male","female","female","male","female","male")
Creating the data frame
- input_data <- data.frame(height,weight,gender)input_data <- data.frame(height,weight,gender)
Let us view the contents of the data frame:
- > input_data <- data.frame(height,weight,gender)
- > input_data
- height weight gender
- 1 140 38 male
- 2 152 49 male
- 3 164 76 female
- 4 137 54 female
- 5 166 97 male
- 6 157 22 female
- 7 112 30 male
Let us check whether the column gender is a factor or not:
- is.factor(input_data$gender)
It returns the following output:
- > is.factor(input_data$gender)
- [1] FALSE

Join the conversation! Your thoughts help the community grow.