How to convert a string to factor in R? When a data type is converted to another data type, it is known as data type casting. Data type casting is necessary when an output returned is a data type different than what we need to perform any further operations. The types of data types are integer, float, character, etc. Strings are values written in single (' ') or double ("") quotes. Factors () are data objects that categorize the data or represent the categorical data, in order to store that data on multiple levels. This recipe performs a conversion of string type to factor.
s <- c("good","bad","good","good","bad")
f <- as.factor(s) print(f) # the data gets classified as two factors -good and bad and are stored as levels. class(f)
good bad good good bad Levels: bad good