如何使用dplyr按id过滤数据框组中列的前10个百分点

che*_*ens 4 r data-analysis percentile dataframe dplyr

我有以下数据框:

id   total_transfered_amount day
1       1000                 2
1       2000                 3
1       3000                 4
1       1000                 1
1       10000                4
2       5000                 3
2       6000                 4
2       40000                2
2       4000                 3
2       4000                 3
3       1000                 1
3       2000                 2
3       3000                 3
3       30000                3
3       3000                 3
Run Code Online (Sandbox Code Playgroud)

需要使用 dplyr 包preferabely分别为每个id过滤掉'total_transfered_amount'列中超过90个百分点的行,例如我需要过滤掉以下行:

2       40000                2
3       30000                3
Run Code Online (Sandbox Code Playgroud)

Mat*_*981 7

检查这个。我不明白为什么你的输出中有第一行

 dane <- data.frame(id = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3,3 ), total_trans = c(1000, 2000, 3000, 1000, 10000, 5000, 6000, 
                                                                                            40000, 4000, 4000, 1000, 2000, 3000, 30000, 3000), 
                       day = c(2, 3,4, 1, 4, 3, 4, 2, 3, 3, 1, 2, 3, 3, 3))

    library(dplyr)




dane %>% group_by(id) %>% filter(quantile(total_trans, 0.9)<total_trans)





      id total_trans   day   
  (dbl)       (dbl) (dbl) 
1     1       10000     4  
2     2       40000     2 
3     3       30000     3 
Run Code Online (Sandbox Code Playgroud)

  • 您要查找的 dplyr 命令是`dane %&gt;% group_by(id) %&gt;% filter(quantile(total_trans, 0.9)&lt;total_trans)` (2认同)

akr*_*run 1

我们可以用data.table

 library(data.table)
 setDT(df1)[,.SD[quantile(total_transfered_amount, 0.9) < 
                total_transfered_amount] , by = id]
 #    id total_transfered_amount day
 #1:  1                   10000   4
 #2:  2                   40000   2
 #3:  3                   30000   3
Run Code Online (Sandbox Code Playgroud)

或者我们可以使用base R

df1[with(df1, as.logical(ave(total_transfered_amount, id, 
              FUN=function(x) quantile(x, 0.9) < x))),]
#   id total_transfered_amount day
#5   1                   10000   4
#8   2                   40000   2
#14  3                   30000   3
Run Code Online (Sandbox Code Playgroud)