R Convert Data Frame Columns from Factor to Character (2 Examples)
In this tutorial, I’ll show how to change vectors and data frame columns from factor to character class in the R programming language.
Example Data
data <- data.frame(col1 = c("L", "k", "AA", "k", "xixi"), # Creating some example data col2 = LETTERS[10:6], col3 = 11:15, col4 = "lala") data # Showing example data in console # col1 col2 col3 col4 # 1 L J 11 lala # 2 k I 12 lala # 3 AA H 13 lala # 4 k G 14 lala # 5 xixi F 15 lala |
data <- data.frame(col1 = c("L", "k", "AA", "k", "xixi"), # Creating some example data col2 = LETTERS[10:6], col3 = 11:15, col4 = "lala") data # Showing example data in console # col1 col2 col3 col4 # 1 L J 11 lala # 2 k I 12 lala # 3 AA H 13 lala # 4 k G 14 lala # 5 xixi F 15 lala
sapply(data, class) # Returning classes of all columns # col1 col2 col3 col4 # "factor" "factor" "integer" "factor" |
sapply(data, class) # Returning classes of all columns # col1 col2 col3 col4 # "factor" "factor" "integer" "factor"
Example 1: Converting Column Vector to Character Class
data$col1 <- as.character(data$col1) |
data$col1 <- as.character(data$col1)
# Convert first column to character
sapply(data, class) # Returning classes of all columns # col1 col2 col3 col4 # "character" "factor" "integer" "factor" |
sapply(data, class) # Returning classes of all columns # col1 col2 col3 col4 # "character" "factor" "integer" "factor"
Example 2: Converting All Factor Columns to Character Class
data[sapply(data, is.factor)] <- # Converting all factor variables to character class lapply(data[sapply(data, is.factor)], as.character) |
data[sapply(data, is.factor)] <- # Converting all factor variables to character class lapply(data[sapply(data, is.factor)], as.character)
sapply(data, class) # Returning classes of all columns # col1 col2 col3 col4 # "character" "character" "integer" "character" |
sapply(data, class) # Returning classes of all columns # col1 col2 col3 col4 # "character" "character" "integer" "character"
Further Resources & Related Tutorials
You may find some additional R tutorials on topics such as factors, numeric values,, and character strings below: