Created
February 10, 2017 19:13
-
-
Save ramhiser/93fe37be439c480dc26c4bed8aab03dd to your computer and use it in GitHub Desktop.
Convert all character columns to factors using dplyr in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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))