Factors in R Programming
In R programming, factors are variables that take on a limited number of different values. Factors are used to represent categorical data.
Some examples of factors:
- A common example of a factor is gender, which can have category values as Male and Female.
- A data field such as marital status may contain only values from single, married, separated, divorced, or widowed.
- For stocks, we can have them categorized as Large-cap, Mid-cap, and Small-cap
In R, the function factor() is used to encode a vector as a factor. In the following example, we first create a vector which for this example categorizes stocks as Large-cap, Mid-cap, and Small-cap. And then we use the factor() function to encode this vector as a factor.
1#The following vector classifies 5 stocks
2 stock_vector <- c("large-cap","small-cap" stock_factor
Test Your Knowledge
Check your understanding of this lesson with a short quiz.
