gpt4 book ai didi

r - 使用dplyr中的mutate_each将所有数字变量转换为因数

转载 作者:行者123 更新时间:2023-12-04 04:51:29 24 4
gpt4 key购买 nike

我正在尝试使用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

真奇怪..
任何想法??

谢谢

最佳答案

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

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

关于r - 使用dplyr中的mutate_each将所有数字变量转换为因数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34123199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com