Home » How to Convert Factor to Character in R (With Examples)

How to Convert Factor to Character in R (With Examples)

by Erma Khan

You can use the following syntax to convert a factor to a character in R:

x character(x)

The following examples show how to use this syntax in practice.

Example 1: Convert Vector Factor to Character

The following code shows how to convert a factor vector to a character vector:

#create factor vector
x #view class
class(x)

[1] "factor"

#convert factor vector to character
x character(x)

#view class
class(x)

[1] "character"

Example 2: Convert Data Frame Column to Character

The following code shows how to convert a column from a factor to a character in a data frame:

#create data frame
df frame(name=factor(c('A', 'B', 'C', 'D')),
                 status=factor(c('Y', 'Y', 'N', 'N')),
                 income=c(45, 89, 93, 96))

#view class of each column
sapply(df, class)

     name    status    income 
 "factor"  "factor" "numeric" 

#convert name column to character
df$name character(df$name)

#view class of each column
sapply(df, class) 

       name      status      income 
"character"    "factor"   "numeric" 

Example 3: Convert All Factor Columns to Character

The following code shows how to convert all factor columns to character in a data frame:

#create data frame
df frame(name=factor(c('A', 'B', 'C', 'D')),
                 status=factor(c('Y', 'Y', 'N', 'N')),
                 income=c(45, 89, 93, 96))

#view class of each column
sapply(df, class)

     name    status    income 
 "factor"  "factor" "numeric" 

#convert name column to character
x factor)
df[x] character)

#view class of each column
sapply(df, class) 

       name       status      income 
"character"  "character"   "numeric" 

Example 4: Convert All Data Frame Columns to Character

The following code shows how to convert every column to character in a data frame:

#create data frame
df frame(name=factor(c('A', 'B', 'C', 'D')),
                 status=factor(c('Y', 'Y', 'N', 'N')),
                 income=c(45, 89, 93, 96))

#view class of each column
sapply(df, class)

     name    status    income 
 "factor"  "factor" "numeric" 

#convert all columns to character
df character)

#view class of each column
sapply(df, class) 

       name       status      income 
"character"  "character"  "characer" 

Additional Resources

How to Convert Character to Numeric in R
How to Convert a List to a Data Frame in R
How to Convert Strings to Dates in R
How to Convert Numbers to Dates in R

Related Posts