简体   繁体   English

使用 dplyr 中的 mutate_each 将所有数值变量转换为因子

[英]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.我正在尝试使用 dplyr 中的 mutate_each 来转换因子中数据集的所有数字变量。

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) dplyr 1.06 版及更早版本的更新答案(在此之前也有一点,但我忘记了版本)

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

mutate_if() (and others) have been superseded by across() or the across() / where() combo within mutate. mutate_if()和其他)已经通过取代across()across() / where()发生变异内组合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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