使用dplyr :: percent_rank()计算组内的百分位等级 [英] Use dplyr::percent_rank() to compute percentile ranks within group

查看:139
本文介绍了使用dplyr :: percent_rank()计算组内的百分位等级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下数据:

id    grpvar1    grpvar2    value
1     1          3          7.6
2     1          2          4
...
3     1          5          2

每个 id ,我想计算其 percent_rank()在由 grpvar1 grpvar2 组合定义的组中。

For each id, I want to compute the percent_rank() of its value within the group defined by the combination of grpvar1 and grpvar2.

使用 data.table ,我会去(假设我的数据在 data.frame 中称为 dataf

Using data.table, I would go (assuming I my data is in a data.frame called dataf:

library(data.table)

# Make dataset into a data.table.
dt <- data.table(dataf)

# Calculate the percentiles.
dt[, percrank := rank(value)/length(value), by = c("grpvar1", "grpvar2")]

dplyr 中的等效项是什么?

推荐答案

尝试:

 library(dplyr)
 dataf %>%
 group_by(grpvar1, grpvar2) %>% 
 mutate(percrank=rank(value)/length(value))

这篇关于使用dplyr :: percent_rank()计算组内的百分位等级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆