R按组进行分位数分配 [英] R quantile by groups with assignments
本文介绍了R按组进行分位数分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下df:
group = rep(seq(1,3),30)
variable = runif(90, 5.0, 7.5)
df = data.frame(group,variable)
我需要i)按组定义分位数,ii)根据每个人的组将每个人分配给她的分位数.
I need to i) Define quantile by groups, ii) Assign each person to her quantile with respect to her group.
因此,输出将如下所示:
Thus, the output would look like:
id group variable quantile_with_respect_to_the_group
1 1 6.430002 1
2 2 6.198008 3
.......
有一种复杂的方法可以在每个组上使用循环和剪切功能,但这根本没有效率.有人知道更好的解决方案吗?
There is a complicated way to do it with loops and cut function over each groups but it is not efficient at all. Does someone know a better solution ?
谢谢!
推荐答案
在data.table
中:
library(data.table)
setDT(df)[,quantile := cut(variable, quantile(variable, probs = 0:4/4),
labels = FALSE, include.lowest = TRUE), by = group]
>head(df)
# group variable quantile
# 1: 1 6.103909 2
# 2: 2 6.511485 3
# 3: 3 5.091684 1
# 4: 1 6.966461 4
# 5: 2 6.613441 4
这篇关于R按组进行分位数分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文