Here are the ways to convert data frame columns from factors to characters in R.
Method 1: Using lapply() and as.character() functions
The easiest way to convert dataframe columns from factor to characters in R is to “use the lapply() function along with the as.character() function”.
Syntax
lapply(X, FUN, …)
Parameters
- df: It is a dataframe object.
- FUN: The function to be applied to each element of the dataframe.
Example
df <- data.frame(
col1 = as.character(1:4),
col2 = factor(c("Red", "Green", "Blue", "Orange")),
col3 = factor(LETTERS[5:8])
)
sapply(df, class)
df[] <- lapply(df, as.character)
sapply(df, class)
Output
col1 col2 col3
"character" "factor" "factor"
col1 col2 col3
"character" "character" "character"
Method 2: Using the transform() function
The transform() method is “used to simulate modification in the data object specified in the argument list of this method”.
Syntax
transform(data, value)
Parameters
- data: It is the data object,
- value: The value to be added
Example
df <- data.frame(
col1 = as.character(1:4),
col2 = factor(c("Red", "Green", "Blue", "Orange")),
col3 = factor(LETTERS[5:8])
)
sapply(df, class)
df_col2 <- transform(df, col2 = as.character(col2))
df_col3 <- transform(df, col3 = as.character(col3))
sapply(df_col2, class)
sapply(df_col3, class)
Output
col1 col2 col3
"character" "factor" "factor"
col1 col2 col3
"character" "character" "factor"
col1 col2 col3
"character" "factor" "character"
Method 3: Using the dplyr package’s mutate_at() function
You can use the “mutate_at()” function from the dplyr package to convert a specific column to a character in R.
Syntax
mutate_at(.df, .vars, .funs)
Parameters
- .df: The dataframe to modify.
- .var: The variable to modify.
- .funs: The function to apply over the variable to be modified.
Example
library(dplyr)
df <- data.frame(
col1 = as.character(1:4),
col2 = factor(c("Red", "Green", "Blue", "Orange")),
col3 = factor(LETTERS[5:8])
)
sapply(df, class)
df <- df %>% mutate_at(
"col2", as.character,
)
sapply(df, class)
Output
col1 col2 col3
"character" "factor" "factor"
col1 col2 col3
"character" "character" "factor"
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.