我有以下 df:
group = rep(seq(1,3),30)
variable = runif(90, 5.0, 7.5)
df = data.frame(group,variable)
Run Code Online (Sandbox Code Playgroud)
我需要 i) 按组定义分位数,ii) 将每个人分配给与她的组相关的分位数。
因此,输出将如下所示:
id group variable quantile_with_respect_to_the_group
1 1 6.430002 1
2 2 6.198008 3
.......
Run Code Online (Sandbox Code Playgroud)
有一种复杂的方法可以在每个组上使用循环和剪切功能,但它根本没有效率。有人知道更好的解决方案吗?
谢谢 !
在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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5493 次 |
最近记录: |