简体   繁体   中英

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

今天更好的解决方案应该是:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM