The as.factor() method in R Programming Language is used to convert the character vector to factor class.
Converting Character Vector To Factor
Syntax:
as.factor(char-vec)
where char-vec is the character vector
The class indicative of the data type of the vector can be obtained using the class() method. Upon conversion, the data type is returned as a factor.
class(fac-vec)
where char-vec is the character vector
Example:
# declaring a character vector
str_vec < - c("Geeks", "For", "Geeks", "Programming", "Coding")
print("Original String")
print(str_vec)
# getting the class of vector
class(str_vec)
str_mod < - as.factor(str_vec)
print("Modified String")
print(str_mod)
# getting the class of vector
class(str_mod)
Output
[1] "Original String" [1] "Geeks" "For" "Geeks" "Programming" "Coding" [1] "character" [1] "Modified String" [1] Geeks For Geeks Programming Coding Levels: Coding For Geeks Programming [1] "factor"
Converting DataFrame Column To Factor Column
Similarly, a dataframe column can be converted to factor type, by referring to the particular data column using df$col-name command in R.
Example:
# declaring a character vector
data_frame < - data.frame(col1=c(1: 5),
col2=c("Geeks", "For", "Geeks",
"Programming", "Coding")
)
print("Original Class")
# getting the class of vector
class(data_frame$col2)
# modifying the col2 of data frame
data_frame$col2 < - as.factor(data_frame$col2)
print("Modified Class")
class(data_frame$col2)
Output
[1] "Original Class" [1] "character" [1] "Modified Class" [1] "factor"