How to Convert DataFrame Columns from Factors to Characters in R

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

  1. df: It is a dataframe object.
  2. 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

  1. data: It is the data object,
  2. 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

  1. .df: The dataframe to modify.
  2. .var: The variable to modify.
  3. .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.

Leave a Comment