![]() |
VOOZH | about |
In this article, we will discuss how to convert the Factor Class to the character Class in the R Programming Language.
To convert a single factor vector to a character vector we use the as.character() function of the R Language and pass the required factor vector as an argument.
Syntax:
character_vector <- as.character( Factor_vector )
Example:
Here, in this example, we have converted a factor vector to a character vector by using as.character() function.
Output:
Input vector: Geeks for Geek Input Data Class: factor Output vector: "Geeks" "for" "Geek" Output Data Class: character
To convert a known factor vector to a character vector we create a duplicate copy of the input data frame. Then use the as.character() function of the R Language and pass the required factor vector column of the data frame as an argument.
Syntax:
Output$factor_vector_column <- as.character( Output$factor_vector_column )
Example:
Here, in this example, we have converted a factor vector column to a character vector column by using as.character() function.
Output:
Input vector: x y 1 Geeks 1 2 for 2 3 Geek 3 Input Data Class: factor Output vector: x y 1 Geeks 1 2 for 2 3 Geek 3 Output Data Class: character
To convert a known factor vector to a character vector we create a duplicate copy of the input data frame. Then use is.factor() conditional statement to find the columns that have data class factor. Then use the as.character() function of the R Language and pass the identified factor vector column of the data frame as an argument.
Syntax:
factor_columns <- sapply(Output, is.factor) Output[factor_columns] <- lapply(Output[factor_columns], as.character)
Example:
Here, in this example, we have converted all factor vector columns to character vector columns by using as.character() function identified by is.factor() conditional statement.
Output:
Input dataframe: x y z 1 Geeks 1 Complete 2 for 2 Interview 3 Geek 3 Preparation Input Data Class: x y z "factor" "numeric" "factor" Output dataframe: x y z 1 Geeks 1 Complete 2 for 2 Interview 3 Geek 3 Preparation Output Data Class: x y z "character" "numeric" "character"
To convert all columns of the data frame into the character we use apply() function with as.character parameter. The lapply() function applies the given function to the provided data frame.
Syntax:
dataframe <- lapply(dataframe, as.character)
Example:
Here, in this example, we have converted all columns of the data frame to character vector columns by using as.character function using lapply() function.
Output:
Input dataframe: x y z 1 Geeks 1 Complete 2 for 2 Interview 3 Geek 3 Preparation Input Data Class: x y z "character" "numeric" "factor" Output dataframe: $x [1] "Geeks" "for" "Geek" $y [1] "1" "2" "3" $z [1] "Complete" "Interview" "Preparation" Output Data Class: x y z "character" "character" "character"