2017-09-17 53 views
1

我想創建一個稱爲百分數的變量,每組的某些值的四分位數。我有以下的數據集,我想創建的最後一個變量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))) 

但它似乎並沒有工作。它不會產生任何變量稱爲百分也不給我一個錯誤

+1

我想知道你是否想過使用'mutate()'。 – jazzurro

回答

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 
+0

足夠接近,但創建一個變量四分位數代表四分位數每個觀察,id在這種情況下 –

+0

也許這是更容易反向工作,這個例子中的答案是什麼,@AndresAzqueta – erasmortg

+0

是真的,我剛剛更新了問題。我已經意識到這是寫得很糟 –