Table of Contents
In R, you can convert a factor to character by using the as.character() function. This function takes in a vector of factors as an argument and returns a vector of characters. You can also use the as.character() function within a list to convert each element of the list from a factor to a character. An example of this is to use the lapply() function, which takes in a list and the as.character() function as arguments and returns a list with each element converted to character.
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"