How to Convert Factor to Character in R

Here are the ways to convert factor to character in R:

  1. Convert a single factor vector to a character vector
  2. Convert factor vector columns to character vector columns in a data frame
  3. Convert factor vector columns to character vector columns in a data frame where columns are unknown
  4. Convert all columns of the Data frame into character

Method 1: Convert a single factor vector to a character vector

To convert a single factor vector to a character vector, you can “use the as.character() function.”

factor_vector <- factor(c("a", "b", "c"))

character_vector <- as.character(factor_vector)

character_vector

class(character_vector)

Output

[1] "a" "b" "c"
[1] "character"

Method 2: Convert factor vector columns to character vector columns in a data frame

If you know which columns are factors and want to convert them to character vectors, you can do this column by column.

df <- data.frame(x = factor(c("a", "b", "c")), y = c(1, 2, 3))

df$x <- as.character(df$x)

class(df$x)

Output

[1] "character"

Method 3: Convert Factor Vector Columns to Character Vector Columns in a Data Frame Where Columns are Unknown

If you don’t know which columns are factors, you can loop through the data frame to convert all factor columns to character columns.

df <- data.frame(x = factor(c("a", "b", "c")), y = c(1, 2, 3))

for (col in names(df)) {
  if (is.factor(df[[col]])) {
    df[[col]] <- as.character(df[[col]])
  }
}

class(df$x)

Output

[1] "character"
[1] "numeric"

Method 4: Convert all columns of the Data Frame into Character

To convert all columns to character types, regardless of their original types, you can “use the lapply() function.”

df <- data.frame(x = factor(c("a", "b", "c")), y = c(1, 2, 3))

df[] <- lapply(df, as.character)

class(df$x)
class(df$y)

Output

[1] "character"
[1] "character"

Conclusion

If you are just starting out, converting a single factor vector to a character vector using as.character() is straightforward and easy to understand.

If you are working with data frames and know which columns are factors, you can manually convert each. Understanding how to loop through columns to automatically convert unknown factor columns is also useful.

For complex data frames with many columns of unknown types, using the lapply() function for wholesale conversion is a robust approach. However, this approach should be used cautiously, as it will convert all columns, not just factors, to character vectors.

Related posts

Date to Character in R

DataFrame Columns from Factors to Characters in R

Character Vector to Numeric in R

DataFrame Column to Numeric in R

Leave a Comment