-
-
Save davan690/5c3b63e0427afcd810905c3fdb2664a8 to your computer and use it in GitHub Desktop.
Convert all character columns to factors using dplyr in R
This file contains hidden or 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