I need to spread an amount proportionally over several rows by ID

I have two datasets with a common ID but not the same level of granularity, and i need to join both files and spread the amount i have in df2 over several rows in df1 having the same common ID but have are split into contracts ....

I know that i need to 1st count the contracts i have by ID and then find a way to divide the amount proportionnaly

In general it will be easier to get help with a minimal reproducible example, or reprex. Sometimes making one will even show you where the problem is, which is always a great feeling!

I tried to make some fake data to reproduce your problem. If this not an accurate representation, please post some more detail about your problem:

library(tidyverse)

df1 <- tibble(grp = c(rep(1, 2), rep(2, 3)), contract = c(1:2, 1:3))
df2 <- tibble(grp = 1:2, value = c(173, 2142))

df1 %>% 
  group_by(grp) %>% 
  mutate(ct = n()) %>% 
  left_join(df2, by = "grp") %>% 
  mutate(prop_value = value / ct)
#> # A tibble: 5 x 5
#> # Groups:   grp [2]
#>     grp contract    ct value prop_value
#>   <dbl>    <int> <int> <dbl>      <dbl>
#> 1     1        1     2   173       86.5
#> 2     1        2     2   173       86.5
#> 3     2        1     3  2142      714  
#> 4     2        2     3  2142      714  
#> 5     2        3     3  2142      714

Created on 2021-05-21 by the reprex package (v2.0.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.