What are factors in R ? Factors () are data objects that categorize the data or represent the categorical data, in order to store that data on multiple levels. The distinct values in factors are called levels. Factors can store integer as well as string values. This recipe demonstrates an example of factors with vectors as input.
Enter all the categorical values in a input vector x
x <- c("good","better","good","best","bad","bad")
Apply factor() function to x and storein output vector y
y <- factor(x)
Print y . The 'factors' are all values of input range and 'Levels' are the distinct values of the factors.
"Output of the code is": good better good best bad bad Levels: bad best better good
To check if the value is factor or not , is.factor() can be used , if it returns TRUE, the value is a factor, if it returns FALSE, the value is not a factor.