A factor in R is used to categorize data. For example:
The above are simple examples of factors.
To create a factor in R, we make use of the factor()
function.
factor(level(s))
The factor()
function takes the level(s) corresponding to the factor variable as its parameters.
The factor()
function returns an object class factor
.
# creating a factorHeight <- factor(c("Tall", "Average", "Short"))# printing the factorHeight
Height
using the factor()
function.Height
.To print only the levels corresponding to a factor variable, we use the levels()
function.
levels(factor)
The levels()
function takes the factor variable as its single parameter value.
# creating a factorHeight <- factor(c("Tall", "Average", "Short", "Average", "Short"))# printing the levelslevels(Height)