Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading