How to Convert Character to Factor in R?
Last Updated :
19 Dec, 2021
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:
R
str_vec < - c ( "Geeks" , "For" , "Geeks" , "Programming" , "Coding" )
print ( "Original String" )
print (str_vec)
class (str_vec)
str_mod < - as.factor (str_vec)
print ( "Modified String" )
print (str_mod)
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:
R
data_frame < - data.frame (col1= c (1: 5),
col2= c ( "Geeks" , "For" , "Geeks" ,
"Programming" , "Coding" )
)
print ( "Original Class" )
class (data_frame$col2)
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"
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...