Search code examples
raggregatequantileunification

(R): Calculate quantile by unique row value unification


I have a df like this:

> df<-data.frame(Client.code = 
c(100451,100451,100523,100523,100523,100525),dayref = c(24,30,15,13,17,5))
> df
    Client.code dayref
1      100451     24
2      100451     30
3      100523     15
4      100523     13
5      100523     17
6      100525      5

It is a one-year distribution of payments period from issue.

Usign this data above and given a df2 like this:

   Client.Code    Days
1  100451          16
1  100523          16
1  100460          35

As i have enough data for a reasonable quantile prob. calculations.I will like to know how to build a loop for assing to every row in this df2 of days a quantile according with the first df.


Solution

  • We can use data.table

    library(data.table)
    setDT(df)[, .(Quantile = quantile(dayref)), Client.code]
    

    Or with tidyverse

    library(dplyr)
    library(tidyr)
    df %>% 
       group_by(Client.code) %>%
       summarise(Quantile = list(quantile(dayref))) %>%
       unnest