Skip to content

Instantly share code, notes, and snippets.

@ramhiser
Created February 10, 2017 19:13
Show Gist options
  • Save ramhiser/93fe37be439c480dc26c4bed8aab03dd to your computer and use it in GitHub Desktop.
Save ramhiser/93fe37be439c480dc26c4bed8aab03dd to your computer and use it in GitHub Desktop.
Convert all character columns to factors using dplyr in R
library(dplyr)
iris_char <- iris %>%
mutate(Species=as.character(Species),
char_column=sample(letters[1:5], nrow(iris), replace=TRUE))
sum(sapply(iris_char, is.character)) # 2
iris_factor <- iris_char %>%
mutate_if(sapply(iris_char, is.character), as.factor)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species char_column
# "numeric" "numeric" "numeric" "numeric" "character" "character"
sapply(iris_factor, class)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species char_column
# "numeric" "numeric" "numeric" "numeric" "factor" "factor"
@Skepe
Copy link

Skepe commented Mar 11, 2025

Thanks a lot! I had a similar problem. It works beautyfully , but there was a complaint that mutate_if is deprecated. I changed it to the new syntax:
iris_factor <- iris %>% mutate(across(where(is.character), as.factor))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment