我正在尝试使用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
但我的目标是将所有数字变量转换为因子,所以我试试这个:
iris %>% mutate_each(funs(as.factor),sapply(iris,is.numeric)) %>% summary # should be a good way, but it doesn't
再试一次
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
这很奇怪..有什么想法?
THKS
今天更好的解决方案应该是:
iris %>% mutate_if(is.numeric,as.factor)