R dplyr - 使用mutate对数字变量进行分类 [英] R dplyr - categorize numeric variable with mutate
本文介绍了R dplyr - 使用mutate对数字变量进行分类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在我的 data.frame
对象中使用 dplyr
(和不知道该怎么做)。
I would like to a categorize numeric variable in my data.frame
object with the use of dplyr
(and have no idea how to do it).
没有 dplyr
,我可能会这样做:
Without dplyr
, I would probably do something like:
df <- data.frame(a = rnorm(1e3), b = rnorm(1e3))
df$a <- cut(df$a , breaks=quantile(df$a, probs = seq(0, 1, 0.2)))
,然后完成。但是,我强烈地希望使用一些 dplyr
函数( mutate
,我想) code> chain 我在 data.frame
中执行的其他操作的顺序。
and it would be done. However, I strongly prefer to do it with the use of some dplyr
function (mutate
, I suppose) in the chain
sequence of other actions I do perform over my data.frame
.
推荐答案
set.seed(123)
df <- data.frame(a = rnorm(10), b = rnorm(10))
df %>% mutate(a = cut(a, breaks = quantile(a, probs = seq(0, 1, 0.2))))
给:
a b
1 (-0.586,-0.316] 1.2240818
2 (-0.316,0.094] 0.3598138
3 (0.68,1.72] 0.4007715
4 (-0.316,0.094] 0.1106827
5 (0.094,0.68] -0.5558411
6 (0.68,1.72] 1.7869131
7 (0.094,0.68] 0.4978505
8 <NA> -1.9666172
9 (-1.27,-0.586] 0.7013559
10 (-0.586,-0.316] -0.4727914
这篇关于R dplyr - 使用mutate对数字变量进行分类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文