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
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.
today a better solution should be :
iris %>% mutate_if(is.numeric,as.factor)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With