Skip to content

Instantly share code, notes, and snippets.

@thisisnic
Last active December 7, 2018 18:41
Show Gist options
  • Save thisisnic/70b8a3f6ce699ec333579b0da17f34f5 to your computer and use it in GitHub Desktop.
Save thisisnic/70b8a3f6ce699ec333579b0da17f34f5 to your computer and use it in GitHub Desktop.
tidyr::uncount() might come in handy if you want to transform a summary table to individual rows

Code:

library(tidyr)
library(tibble)
df <- data_frame(animal = c("cat", "dog"), toy = c("ball", "stick"), total = c(5, 6))
df

Output:

# A tibble: 2 x 3
  animal toy   total
  <chr>  <chr> <dbl>
1 cat    ball      5
2 dog    stick     6

Code:

uncount(df, total)

Output:

# A tibble: 11 x 2
   animal toy  
   <chr>  <chr>
 1 cat    ball 
 2 cat    ball 
 3 cat    ball 
 4 cat    ball 
 5 cat    ball 
 6 dog    stick
 7 dog    stick
 8 dog    stick
 9 dog    stick
10 dog    stick
11 dog    stick
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment