You can use the following syntax to convert a factor to a character in R:
x <- as.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 <- factor(c('A', 'B', 'C', 'D')) #view class class(x) [1] "factor" #convert factor vector to character x <- as.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 <- data.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 <- as.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 <- data.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 <- sapply(df, is.factor)
df[x] <- lapply(df[x], as.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 <- data.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 <- lapply(df, as.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