Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using mutate_each from dplyr to convert all numeric variables to factor

Tags:

r

dplyr

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

like image 460
Vincent Guyader Avatar asked Dec 06 '15 21:12

Vincent Guyader


2 Answers

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.

like image 55
Mike Avatar answered Sep 28 '22 10:09

Mike


today a better solution should be :

iris %>% mutate_if(is.numeric,as.factor)
like image 40
Vincent Guyader Avatar answered Sep 28 '22 09:09

Vincent Guyader