9

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

7
  • iris %>% mutate_each(funs(as.factor), which(sapply(., is.numeric))) %>% summary?
    – jeremycg
    Dec 6, 2015 at 21:58
  • @jeremycg > iris %>% mutate_each(funs(as.factor), which(sapply(., is.numeric))) %>% summary Error in lapply(X = X, FUN = FUN, ...) : object '.' not found Dec 6, 2015 at 22:00
  • works for me - do you have plyr loaded (you shouldn't)? Up to date with lastest dplyr version?
    – jeremycg
    Dec 6, 2015 at 22:01
  • dplyr 0.4.1 and plyr 1.8.2 ... both loaded. In a New R session I test this : library(plyr); library(dplyr); data(iris); iris %>% mutate_each(funs(as.factor), which(sapply(., is.numeric))) %>% summary Dec 6, 2015 at 22:04
  • yeah, try updating dplyr - 0.4.3 is out, and for me that exact command works in a new session
    – jeremycg
    Dec 6, 2015 at 22:07

2 Answers 2

30

today a better solution should be :

iris %>% mutate_if(is.numeric,as.factor)
1
  • How could we filter column names containing string width then convert these columns to factor?
    – ah bon
    Jan 17, 2022 at 9:42
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.