Vincent Guyader
Vincent Guyader

Reputation: 3189

using mutate_each from dplyr to convert all numeric variables to factor

I'm trying to use mutate_each from dplyr to conver ALL the numeric variables of data set in factor.

library(dplyr)
data(iris)
tbl_df(iris) ->iris

# I can transform all variables in factor
iris %>% mutate_each(funs(as.factor)) %>% summary
# I can transform some variables in factor
iris %>% mutate_each(funs(as.factor),one_of("Sepal.Length", "Petal.Length")) %>% summary

but my goal is to tranform all numeric variables to factor so I try this :

iris %>% mutate_each(funs(as.factor),sapply(iris,is.numeric)) %>% summary # should be a good way, but it doesn't

another try

iris %>% mutate_each(funs(as.factor),one_of(names(iris)[sapply(iris,is.numeric)]))
# Error in one_of(vars, ...) : object 'iris' not found

iris %>% mutate_each(funs(as.factor),names(iris)[sapply(iris,is.numeric)])
#Error in one_of(vars, ...) : object 'iris' not found

# anyway the one_of function dont seems to work in mutate_each
vars<-names(iris)[sapply(iris,is.numeric)]
iris %>%   mutate_each_(funs(as.factor),one_of(c("Petal.Length", "Petal.Width")))
iris %>%   mutate_each_(funs(as.factor),one_of(vars))

# Without %>% This works
mutate_each(iris,funs(as.factor), one_of(c("Petal.Length", "Petal.Width"))) %>% summary

It's strange.. Any idea??

thks

Upvotes: 9

Views: 14546

Answers (2)

Mike
Mike

Reputation: 4370

Updated answer for dplyr version 1.06 and ahead (and a little before this too but I forget the version)

iris %>%
   mutate(across(where(is.numeric) , as.factor))

mutate_if() (and others) have been superseded by across() or the across() / where() combo within mutate.

Upvotes: 2

Vincent Guyader
Vincent Guyader

Reputation: 3189

today a better solution should be :

iris %>% mutate_if(is.numeric,as.factor)

Upvotes: 30

Related Questions