Search code examples
rgroup-bygroup

Ungrouping data frame - R


I have the following DF:

df <- data.frame(Type  = c("A", "A", "B"),
                 Day = c(1, 1, 1),
                 Hour = c(1,2,1),
                 Amount = c(2,3,2))

Type   Day   Hour   Amount
   A     1      1        2
   A     1      2        3
   B     1      1        2

And would like to end up with a DF with a number of rows equal to the sum of Amount, like this:

Type   Day   Hour   
   A     1      1        
   A     1      1        
   A     1      2        
   A     1      2        
   A     1      2        
   B     1      1        
   B     1      1     

In fact is "just" an ungroup. But I've been trying to find a function that does that and couldn't find anything. There's one in dplyr but it must be used after the group one.


Solution

  • You need the uncount() function from the package tidyr.

    library(tidyverse)
    
    df %>% uncount(Amount)
    
      Type Day Hour
    1    A   1    1
    2    A   1    1
    3    A   1    2
    4    A   1    2
    5    A   1    2
    6    B   1    1
    7    B   1    1