计算每组某些值的四分位数
calculate the quartiles of certain values per group
我想创建一个名为 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)))
不过好像不行。它不会产生任何称为百分位数的变量,也不会给我一个错误
这是你需要的吗?:
> df$percentile = ave(df$value, df$group, FUN=function(x) ecdf(x)(x))
回复:如果你想要 4,你可以:
df$percentile = factor(df$percentile)
levels(df$percentile) <- 1:4
我想创建一个名为 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)))
不过好像不行。它不会产生任何称为百分位数的变量,也不会给我一个错误
这是你需要的吗?:
> df$percentile = ave(df$value, df$group, FUN=function(x) ecdf(x)(x))
回复:如果你想要 4,你可以:
df$percentile = factor(df$percentile)
levels(df$percentile) <- 1:4