Search code examples
rdataframedplyrgrouping

Find the ratio between two groups


Essentially I have

Var1 Group Value
a    0     1 
b    0     2
c    0     3
a    1     2
b    1     10
c    1     9

I want to calculate a table with rows Var1 and a single column Div where for any value of Var1, the value of Div will be the division of the Value values for group 1 over group 2. Thus, the outcome should be

Var1 Div
a    .5
b    .2
c    .3333

I have achieved this by creating two tables (filter the table using Group, then divide the Value column of the two tables, and then create a new table). Is there a method or function in the tidyverse that achieves this using pipes?


Solution

  • Here are 2 alternatives to match Group in each Var1 stratum using match() and pivot_wider() respectively.

    library(dplyr)
    
    quux %>%
      summarise(Div = Value[match(0:1, Group)] %>% {.[1] / .[2]}, .by = Var1)
    
    #   Var1       Div
    # 1    a 0.5000000
    # 2    b 0.2000000
    # 3    c 0.3333333
    
    library(tidyr)
    
    quux %>%
      pivot_wider(names_from = Group, values_from = Value, names_prefix = 'grp') %>%
      mutate(Div = grp0 / grp1, .keep = "unused")
    
    # # A tibble: 3 × 2
    #   Var1    Div
    #   <chr> <dbl>
    # 1 a     0.5  
    # 2 b     0.2  
    # 3 c     0.333