1

我想创建一个名为 percentile 的变量,每组具有某些值的四分位数。我有以下数据集,我想创建最后一个变量percentile

  id group value
1  1     1     1
2  2     1     2
3  3     1     3
4  4     1     4
5  5     2    10
6  6     2    20
7  7     2    30
8  8     2    40

以下是预期的结果。

id group value percentile
1  1     1     1
2  1     2     2
3  1     3     3 
4  1     4     4
5  2     10    1
6  2     20    2
7  2     30    3
8  2     40    4

到目前为止,我已经尝试使用该库进行以下操作dplyr

df <- df  %>% group_by(group) %>% within(df, percentile <- as.integer(cut(value, quantile(value, probs=0:4/4), 
                                                              include.lowest=TRUE)))

但这似乎不起作用。它不会产生任何称为百分位数的变量,也不会给我一个错误

4

1 回答 1

1

这是你需要的吗?:

> df$percentile = ave(df$value, df$group, FUN=function(x) ecdf(x)(x))

回复:如果你想要 4,你可以:

df$percentile = factor(df$percentile)
levels(df$percentile) <- 1:4
于 2017-09-17T13:18:30.457 回答