We will here discuss several functions that are useful with grouped data frames.

- group_split()

This function divides the groups of a grouped data frame into separate tibbles.

df %>%
  slice(1:100) %>%
  group_by(Country) %>%
  group_split()
## <list_of<
##   tbl_df<
##     Invoice    : character
##     StockCode  : character
##     Description: character
##     Quantity   : double
##     InvoiceDate: datetime<UTC>
##     Price      : double
##     Customer ID: double
##     Country    : character
##   >
## >[2]>
## [[1]]
## # A tibble: 19 × 8
##    Invoice StockCode Description              Quantity InvoiceDate         Price
##    <chr>   <chr>     <chr>                       <dbl> <dttm>              <dbl>
##  1 489439  22065     CHRISTMAS PUDDING TRINK…       12 2009-12-01 09:28:00  1.45
##  2 489439  22138     BAKING SET 9 PIECE RETR…        9 2009-12-01 09:28:00  4.95
##  3 489439  22139     RETRO SPOT TEA SET CERA…        9 2009-12-01 09:28:00  4.95
##  4 489439  22352     LUNCHBOX WITH CUTLERY R…       12 2009-12-01 09:28:00  2.55
##  5 489439  85014A    BLACK/BLUE DOTS RUFFLED…        3 2009-12-01 09:28:00  5.95
##  6 489439  85014B    RED/WHITE DOTS RUFFLED …        3 2009-12-01 09:28:00  5.95
##  7 489439  16161P    WRAP ENGLISH ROSE              25 2009-12-01 09:28:00  0.42
##  8 489439  16169N    WRAP BLUE RUSSIAN FOLKA…       25 2009-12-01 09:28:00  0.42
##  9 489439  21491     SET OF THREE VINTAGE GI…        6 2009-12-01 09:28:00  1.95
## 10 489439  22333     RETRO SPORT PARTY BAG +…        8 2009-12-01 09:28:00  1.65
## 11 489439  85216     ASSORTED CAKES FRIDGE M…       12 2009-12-01 09:28:00  0.65
## 12 489439  21493     VINTAGE DESIGN GIFT TAGS       12 2009-12-01 09:28:00  0.85
## 13 489439  22130     PARTY CONE CHRISTMAS DE…       24 2009-12-01 09:28:00  0.85
## 14 489439  22064     PINK DOUGHNUT TRINKET P…       12 2009-12-01 09:28:00  1.65
## 15 489439  21731     RED TOADSTOOL LED NIGHT…       24 2009-12-01 09:28:00  1.65
## 16 489439  85232B    SET/3 RUSSIAN DOLL STAC…        6 2009-12-01 09:28:00  4.95
## 17 489439  84691     PACK 20 DOLLY PEGS             12 2009-12-01 09:28:00  0.85
## 18 489439  20749     ASSORTED COLOUR MINI CA…        2 2009-12-01 09:28:00  7.95
## 19 489439  POST      POSTAGE                         3 2009-12-01 09:28:00 18   
## # ℹ 2 more variables: `Customer ID` <dbl>, Country <chr>
## 
## [[2]]
## # A tibble: 81 × 8
##    Invoice StockCode Description              Quantity InvoiceDate         Price
##    <chr>   <chr>     <chr>                       <dbl> <dttm>              <dbl>
##  1 489434  85048     "15CM CHRISTMAS GLASS B…       12 2009-12-01 07:45:00  6.95
##  2 489434  79323P    "PINK CHERRY LIGHTS"           12 2009-12-01 07:45:00  6.75
##  3 489434  79323W    "WHITE CHERRY LIGHTS"          12 2009-12-01 07:45:00  6.75
##  4 489434  22041     "RECORD FRAME 7\" SINGL…       48 2009-12-01 07:45:00  2.1 
##  5 489434  21232     "STRAWBERRY CERAMIC TRI…       24 2009-12-01 07:45:00  1.25
##  6 489434  22064     "PINK DOUGHNUT TRINKET …       24 2009-12-01 07:45:00  1.65
##  7 489434  21871     "SAVE THE PLANET MUG"          24 2009-12-01 07:45:00  1.25
##  8 489434  21523     "FANCY FONT HOME SWEET …       10 2009-12-01 07:45:00  5.95
##  9 489435  22350     "CAT BOWL"                     12 2009-12-01 07:46:00  2.55
## 10 489435  22349     "DOG BOWL , CHASING BAL…       12 2009-12-01 07:46:00  3.75
## # ℹ 71 more rows
## # ℹ 2 more variables: `Customer ID` <dbl>, Country <chr>
df %>%
  slice(1:100) %>%
  group_by(Country, `Customer ID`) %>%
  group_split()
## <list_of<
##   tbl_df<
##     Invoice    : character
##     StockCode  : character
##     Description: character
##     Quantity   : double
##     InvoiceDate: datetime<UTC>
##     Price      : double
##     Customer ID: double
##     Country    : character
##   >
## >[7]>
## [[1]]
## # A tibble: 19 × 8
##    Invoice StockCode Description              Quantity InvoiceDate         Price
##    <chr>   <chr>     <chr>                       <dbl> <dttm>              <dbl>
##  1 489439  22065     CHRISTMAS PUDDING TRINK…       12 2009-12-01 09:28:00  1.45
##  2 489439  22138     BAKING SET 9 PIECE RETR…        9 2009-12-01 09:28:00  4.95
##  3 489439  22139     RETRO SPOT TEA SET CERA…        9 2009-12-01 09:28:00  4.95
##  4 489439  22352     LUNCHBOX WITH CUTLERY R…       12 2009-12-01 09:28:00  2.55
##  5 489439  85014A    BLACK/BLUE DOTS RUFFLED…        3 2009-12-01 09:28:00  5.95
##  6 489439  85014B    RED/WHITE DOTS RUFFLED …        3 2009-12-01 09:28:00  5.95
##  7 489439  16161P    WRAP ENGLISH ROSE              25 2009-12-01 09:28:00  0.42
##  8 489439  16169N    WRAP BLUE RUSSIAN FOLKA…       25 2009-12-01 09:28:00  0.42
##  9 489439  21491     SET OF THREE VINTAGE GI…        6 2009-12-01 09:28:00  1.95
## 10 489439  22333     RETRO SPORT PARTY BAG +…        8 2009-12-01 09:28:00  1.65
## 11 489439  85216     ASSORTED CAKES FRIDGE M…       12 2009-12-01 09:28:00  0.65
## 12 489439  21493     VINTAGE DESIGN GIFT TAGS       12 2009-12-01 09:28:00  0.85
## 13 489439  22130     PARTY CONE CHRISTMAS DE…       24 2009-12-01 09:28:00  0.85
## 14 489439  22064     PINK DOUGHNUT TRINKET P…       12 2009-12-01 09:28:00  1.65
## 15 489439  21731     RED TOADSTOOL LED NIGHT…       24 2009-12-01 09:28:00  1.65
## 16 489439  85232B    SET/3 RUSSIAN DOLL STAC…        6 2009-12-01 09:28:00  4.95
## 17 489439  84691     PACK 20 DOLLY PEGS             12 2009-12-01 09:28:00  0.85
## 18 489439  20749     ASSORTED COLOUR MINI CA…        2 2009-12-01 09:28:00  7.95
## 19 489439  POST      POSTAGE                         3 2009-12-01 09:28:00 18   
## # ℹ 2 more variables: `Customer ID` <dbl>, Country <chr>
## 
## [[2]]
## # A tibble: 19 × 8
##    Invoice StockCode Description              Quantity InvoiceDate         Price
##    <chr>   <chr>     <chr>                       <dbl> <dttm>              <dbl>
##  1 489436  48173C    DOOR MAT BLACK FLOCK           10 2009-12-01 09:06:00  5.95
##  2 489436  21755     LOVE BUILDING BLOCK WORD       18 2009-12-01 09:06:00  5.45
##  3 489436  21754     HOME BUILDING BLOCK WORD        3 2009-12-01 09:06:00  5.95
##  4 489436  84879     ASSORTED COLOUR BIRD OR…       16 2009-12-01 09:06:00  1.69
##  5 489436  22119     PEACE WOODEN BLOCK LETT…        3 2009-12-01 09:06:00  6.95
##  6 489436  22142     CHRISTMAS CRAFT WHITE F…       12 2009-12-01 09:06:00  1.45
##  7 489436  22296     HEART IVORY TRELLIS LAR…       12 2009-12-01 09:06:00  1.65
##  8 489436  22295     HEART FILIGREE DOVE LAR…       12 2009-12-01 09:06:00  1.65
##  9 489436  22109     FULL ENGLISH BREAKFAST …       16 2009-12-01 09:06:00  3.39
## 10 489436  22107     PIZZA PLATE IN BOX              4 2009-12-01 09:06:00  3.75
## 11 489436  22194     BLACK DINER WALL CLOCK          2 2009-12-01 09:06:00  8.5 
## 12 489436  35004B    SET OF 3 BLACK FLYING D…       12 2009-12-01 09:06:00  4.65
## 13 489436  82582     AREA PATROLLED METAL SI…       12 2009-12-01 09:06:00  2.1 
## 14 489436  21181     PLEASE ONE PERSON  META…       12 2009-12-01 09:06:00  2.1 
## 15 489436  21756     BATH BUILDING BLOCK WORD        3 2009-12-01 09:06:00  5.95
## 16 489436  21333     CLASSIC WHITE FRAME             6 2009-12-01 09:06:00  2.95
## 17 489436  84596F    SMALL MARSHMALLOWS PINK…        8 2009-12-01 09:06:00  1.25
## 18 489436  84596L    BISCUITS SMALL BOWL LIG…        8 2009-12-01 09:06:00  1.25
## 19 489436  22111     SCOTTIE DOG HOT WATER B…       24 2009-12-01 09:06:00  4.25
## # ℹ 2 more variables: `Customer ID` <dbl>, Country <chr>
## 
## [[3]]
## # A tibble: 12 × 8
##    Invoice StockCode Description              Quantity InvoiceDate         Price
##    <chr>   <chr>     <chr>                       <dbl> <dttm>              <dbl>
##  1 489434  85048     "15CM CHRISTMAS GLASS B…       12 2009-12-01 07:45:00  6.95
##  2 489434  79323P    "PINK CHERRY LIGHTS"           12 2009-12-01 07:45:00  6.75
##  3 489434  79323W    "WHITE CHERRY LIGHTS"          12 2009-12-01 07:45:00  6.75
##  4 489434  22041     "RECORD FRAME 7\" SINGL…       48 2009-12-01 07:45:00  2.1 
##  5 489434  21232     "STRAWBERRY CERAMIC TRI…       24 2009-12-01 07:45:00  1.25
##  6 489434  22064     "PINK DOUGHNUT TRINKET …       24 2009-12-01 07:45:00  1.65
##  7 489434  21871     "SAVE THE PLANET MUG"          24 2009-12-01 07:45:00  1.25
##  8 489434  21523     "FANCY FONT HOME SWEET …       10 2009-12-01 07:45:00  5.95
##  9 489435  22350     "CAT BOWL"                     12 2009-12-01 07:46:00  2.55
## 10 489435  22349     "DOG BOWL , CHASING BAL…       12 2009-12-01 07:46:00  3.75
## 11 489435  22195     "HEART MEASURING SPOONS…       24 2009-12-01 07:46:00  1.65
## 12 489435  22353     "LUNCHBOX WITH CUTLERY …       12 2009-12-01 07:46:00  2.55
## # ℹ 2 more variables: `Customer ID` <dbl>, Country <chr>
## 
## [[4]]
## # A tibble: 4 × 8
##   Invoice StockCode Description Quantity InvoiceDate         Price `Customer ID`
##   <chr>   <chr>     <chr>          <dbl> <dttm>              <dbl>         <dbl>
## 1 489442  21955     UNION JACK…        2 2009-12-01 09:46:00  6.75         13635
## 2 489442  22111     SCOTTIE DO…        3 2009-12-01 09:46:00  4.95         13635
## 3 489442  22296     HEART IVOR…       12 2009-12-01 09:46:00  1.65         13635
## 4 489442  84899E    YELLOW + B…       12 2009-12-01 09:46:00  1.25         13635
## # ℹ 1 more variable: Country <chr>
## 
## [[5]]
## # A tibble: 23 × 8
##    Invoice StockCode Description              Quantity InvoiceDate         Price
##    <chr>   <chr>     <chr>                       <dbl> <dttm>              <dbl>
##  1 489437  22143     CHRISTMAS CRAFT HEART D…        6 2009-12-01 09:08:00  2.1 
##  2 489437  22145     CHRISTMAS CRAFT HEART S…        6 2009-12-01 09:08:00  2.1 
##  3 489437  22130     PARTY CONE CHRISTMAS DE…       12 2009-12-01 09:08:00  0.85
##  4 489437  21364     PEACE SMALL WOOD LETTERS        2 2009-12-01 09:08:00  6.75
##  5 489437  21360     JOY LARGE WOOD LETTERS          1 2009-12-01 09:08:00  9.95
##  6 489437  21351     CINAMMON & ORANGE WREATH        2 2009-12-01 09:08:00  6.75
##  7 489437  21352     EUCALYPTUS & PINECONE  …        2 2009-12-01 09:08:00  6.75
##  8 489437  35400     WOODEN BOX ADVENT CALEN…        2 2009-12-01 09:08:00  8.95
##  9 489437  20695     FLORAL BLUE MONSTER             3 2009-12-01 09:08:00  4.25
## 10 489437  37370     RETRO COFFEE MUGS ASSOR…       12 2009-12-01 09:08:00  1.25
## # ℹ 13 more rows
## # ℹ 2 more variables: `Customer ID` <dbl>, Country <chr>
## 
## [[6]]
## # A tibble: 6 × 8
##   Invoice StockCode Description Quantity InvoiceDate         Price `Customer ID`
##   <chr>   <chr>     <chr>          <dbl> <dttm>              <dbl>         <dbl>
## 1 489440  22350     CAT BOWL           8 2009-12-01 09:43:00  2.55         18087
## 2 489440  22349     DOG BOWL ,…        8 2009-12-01 09:43:00  3.75         18087
## 3 489441  22321     BIRD DECOR…       12 2009-12-01 09:44:00  0.72         18087
## 4 489441  22138     BAKING SET…        6 2009-12-01 09:44:00  4.25         18087
## 5 489441  84029E    RED WOOLLY…       36 2009-12-01 09:44:00  2.95         18087
## 6 489441  22111     SCOTTIE DO…       48 2009-12-01 09:44:00  4.25         18087
## # ℹ 1 more variable: Country <chr>
## 
## [[7]]
## # A tibble: 17 × 8
##    Invoice StockCode Description              Quantity InvoiceDate         Price
##    <chr>   <chr>     <chr>                       <dbl> <dttm>              <dbl>
##  1 489438  21329     DINOSAURS  WRITING SET         28 2009-12-01 09:24:00  0.98
##  2 489438  21252     SET OF MEADOW  FLOWER S…       30 2009-12-01 09:24:00  1.69
##  3 489438  21100     CHARLIE AND LOLA CHARLO…       30 2009-12-01 09:24:00  1.15
##  4 489438  21033     JUMBO BAG CHARLIE AND L…       30 2009-12-01 09:24:00  2   
##  5 489438  20711     JUMBO BAG TOYS                 60 2009-12-01 09:24:00  1.3 
##  6 489438  21410     COUNTRY COTTAGE  DOORST…       32 2009-12-01 09:24:00  2.5 
##  7 489438  21411     GINGHAM HEART  DOORSTOP…       32 2009-12-01 09:24:00  2.5 
##  8 489438  84031A    CHARLIE+LOLA RED HOT WA…       56 2009-12-01 09:24:00  3   
##  9 489438  84031B    CHARLIE LOLA BLUE HOT W…       56 2009-12-01 09:24:00  3   
## 10 489438  84032A    CHARLIE+LOLA PINK HOT W…       60 2009-12-01 09:24:00  1.9 
## 11 489438  84032B    CHARLIE + LOLA RED HOT …       56 2009-12-01 09:24:00  1.9 
## 12 489438  84519A    TOMATO CHARLIE+LOLA COA…       56 2009-12-01 09:24:00  2.15
## 13 489438  84519B    CARROT CHARLIE+LOLA COA…       60 2009-12-01 09:24:00  2.4 
## 14 489438  85132A    CHARLIE + LOLA BISCUITS…       60 2009-12-01 09:24:00  6.38
## 15 489438  85132C    CHARLIE AND LOLA FIGURE…       60 2009-12-01 09:24:00  6.4 
## 16 489438  85183A    CHARLIE & LOLA WASTEPAP…       60 2009-12-01 09:24:00  2.4 
## 17 489438  85183B    CHARLIE & LOLA WASTEPAP…       60 2009-12-01 09:24:00  2.4 
## # ℹ 2 more variables: `Customer ID` <dbl>, Country <chr>

The output is a list, arranged by the grouping columns, so every data frame can be accessed with the correct subsetting (based on indexes as the list is not named.)

dfs_list <- df %>%
  slice(1:100) %>%
  group_by(Country) %>%
  group_split()
dfs_list[[1]]
A tibble: 19 x 8

We can modify that by using setNames() though.

(named_dfs_list <- df %>%
  slice(1:100) %>%
  group_by(Country) %>%
  group_split() %>%
  setNames(unique(sort(df[1:100, ]$Country))))
## <list_of<
##   tbl_df<
##     Invoice    : character
##     StockCode  : character
##     Description: character
##     Quantity   : double
##     InvoiceDate: datetime<UTC>
##     Price      : double
##     Customer ID: double
##     Country    : character
##   >
## >[2]>
## $France
## # A tibble: 19 × 8
##    Invoice StockCode Description              Quantity InvoiceDate         Price
##    <chr>   <chr>     <chr>                       <dbl> <dttm>              <dbl>
##  1 489439  22065     CHRISTMAS PUDDING TRINK…       12 2009-12-01 09:28:00  1.45
##  2 489439  22138     BAKING SET 9 PIECE RETR…        9 2009-12-01 09:28:00  4.95
##  3 489439  22139     RETRO SPOT TEA SET CERA…        9 2009-12-01 09:28:00  4.95
##  4 489439  22352     LUNCHBOX WITH CUTLERY R…       12 2009-12-01 09:28:00  2.55
##  5 489439  85014A    BLACK/BLUE DOTS RUFFLED…        3 2009-12-01 09:28:00  5.95
##  6 489439  85014B    RED/WHITE DOTS RUFFLED …        3 2009-12-01 09:28:00  5.95
##  7 489439  16161P    WRAP ENGLISH ROSE              25 2009-12-01 09:28:00  0.42
##  8 489439  16169N    WRAP BLUE RUSSIAN FOLKA…       25 2009-12-01 09:28:00  0.42
##  9 489439  21491     SET OF THREE VINTAGE GI…        6 2009-12-01 09:28:00  1.95
## 10 489439  22333     RETRO SPORT PARTY BAG +…        8 2009-12-01 09:28:00  1.65
## 11 489439  85216     ASSORTED CAKES FRIDGE M…       12 2009-12-01 09:28:00  0.65
## 12 489439  21493     VINTAGE DESIGN GIFT TAGS       12 2009-12-01 09:28:00  0.85
## 13 489439  22130     PARTY CONE CHRISTMAS DE…       24 2009-12-01 09:28:00  0.85
## 14 489439  22064     PINK DOUGHNUT TRINKET P…       12 2009-12-01 09:28:00  1.65
## 15 489439  21731     RED TOADSTOOL LED NIGHT…       24 2009-12-01 09:28:00  1.65
## 16 489439  85232B    SET/3 RUSSIAN DOLL STAC…        6 2009-12-01 09:28:00  4.95
## 17 489439  84691     PACK 20 DOLLY PEGS             12 2009-12-01 09:28:00  0.85
## 18 489439  20749     ASSORTED COLOUR MINI CA…        2 2009-12-01 09:28:00  7.95
## 19 489439  POST      POSTAGE                         3 2009-12-01 09:28:00 18   
## # ℹ 2 more variables: `Customer ID` <dbl>, Country <chr>
## 
## $`United Kingdom`
## # A tibble: 81 × 8
##    Invoice StockCode Description              Quantity InvoiceDate         Price
##    <chr>   <chr>     <chr>                       <dbl> <dttm>              <dbl>
##  1 489434  85048     "15CM CHRISTMAS GLASS B…       12 2009-12-01 07:45:00  6.95
##  2 489434  79323P    "PINK CHERRY LIGHTS"           12 2009-12-01 07:45:00  6.75
##  3 489434  79323W    "WHITE CHERRY LIGHTS"          12 2009-12-01 07:45:00  6.75
##  4 489434  22041     "RECORD FRAME 7\" SINGL…       48 2009-12-01 07:45:00  2.1 
##  5 489434  21232     "STRAWBERRY CERAMIC TRI…       24 2009-12-01 07:45:00  1.25
##  6 489434  22064     "PINK DOUGHNUT TRINKET …       24 2009-12-01 07:45:00  1.65
##  7 489434  21871     "SAVE THE PLANET MUG"          24 2009-12-01 07:45:00  1.25
##  8 489434  21523     "FANCY FONT HOME SWEET …       10 2009-12-01 07:45:00  5.95
##  9 489435  22350     "CAT BOWL"                     12 2009-12-01 07:46:00  2.55
## 10 489435  22349     "DOG BOWL , CHASING BAL…       12 2009-12-01 07:46:00  3.75
## # ℹ 71 more rows
## # ℹ 2 more variables: `Customer ID` <dbl>, Country <chr>
named_dfs_list[["France"]]
A tibble: 19 x 8

If we want to merge the data frames back, we can use bind_rows().

bind_rows(dfs_list)
A tibble: 100 x 8

The rows’ order might be different from the original data frame’s one as it is dictated by the grouping columns.

The function can be used directly without having to group_by() first,

df %>%
  slice(1:100) %>%
  group_split(Country)
## <list_of<
##   tbl_df<
##     Invoice    : character
##     StockCode  : character
##     Description: character
##     Quantity   : double
##     InvoiceDate: datetime<UTC>
##     Price      : double
##     Customer ID: double
##     Country    : character
##   >
## >[2]>
## [[1]]
## # A tibble: 19 × 8
##    Invoice StockCode Description              Quantity InvoiceDate         Price
##    <chr>   <chr>     <chr>                       <dbl> <dttm>              <dbl>
##  1 489439  22065     CHRISTMAS PUDDING TRINK…       12 2009-12-01 09:28:00  1.45
##  2 489439  22138     BAKING SET 9 PIECE RETR…        9 2009-12-01 09:28:00  4.95
##  3 489439  22139     RETRO SPOT TEA SET CERA…        9 2009-12-01 09:28:00  4.95
##  4 489439  22352     LUNCHBOX WITH CUTLERY R…       12 2009-12-01 09:28:00  2.55
##  5 489439  85014A    BLACK/BLUE DOTS RUFFLED…        3 2009-12-01 09:28:00  5.95
##  6 489439  85014B    RED/WHITE DOTS RUFFLED …        3 2009-12-01 09:28:00  5.95
##  7 489439  16161P    WRAP ENGLISH ROSE              25 2009-12-01 09:28:00  0.42
##  8 489439  16169N    WRAP BLUE RUSSIAN FOLKA…       25 2009-12-01 09:28:00  0.42
##  9 489439  21491     SET OF THREE VINTAGE GI…        6 2009-12-01 09:28:00  1.95
## 10 489439  22333     RETRO SPORT PARTY BAG +…        8 2009-12-01 09:28:00  1.65
## 11 489439  85216     ASSORTED CAKES FRIDGE M…       12 2009-12-01 09:28:00  0.65
## 12 489439  21493     VINTAGE DESIGN GIFT TAGS       12 2009-12-01 09:28:00  0.85
## 13 489439  22130     PARTY CONE CHRISTMAS DE…       24 2009-12-01 09:28:00  0.85
## 14 489439  22064     PINK DOUGHNUT TRINKET P…       12 2009-12-01 09:28:00  1.65
## 15 489439  21731     RED TOADSTOOL LED NIGHT…       24 2009-12-01 09:28:00  1.65
## 16 489439  85232B    SET/3 RUSSIAN DOLL STAC…        6 2009-12-01 09:28:00  4.95
## 17 489439  84691     PACK 20 DOLLY PEGS             12 2009-12-01 09:28:00  0.85
## 18 489439  20749     ASSORTED COLOUR MINI CA…        2 2009-12-01 09:28:00  7.95
## 19 489439  POST      POSTAGE                         3 2009-12-01 09:28:00 18   
## # ℹ 2 more variables: `Customer ID` <dbl>, Country <chr>
## 
## [[2]]
## # A tibble: 81 × 8
##    Invoice StockCode Description              Quantity InvoiceDate         Price
##    <chr>   <chr>     <chr>                       <dbl> <dttm>              <dbl>
##  1 489434  85048     "15CM CHRISTMAS GLASS B…       12 2009-12-01 07:45:00  6.95
##  2 489434  79323P    "PINK CHERRY LIGHTS"           12 2009-12-01 07:45:00  6.75
##  3 489434  79323W    "WHITE CHERRY LIGHTS"          12 2009-12-01 07:45:00  6.75
##  4 489434  22041     "RECORD FRAME 7\" SINGL…       48 2009-12-01 07:45:00  2.1 
##  5 489434  21232     "STRAWBERRY CERAMIC TRI…       24 2009-12-01 07:45:00  1.25
##  6 489434  22064     "PINK DOUGHNUT TRINKET …       24 2009-12-01 07:45:00  1.65
##  7 489434  21871     "SAVE THE PLANET MUG"          24 2009-12-01 07:45:00  1.25
##  8 489434  21523     "FANCY FONT HOME SWEET …       10 2009-12-01 07:45:00  5.95
##  9 489435  22350     "CAT BOWL"                     12 2009-12-01 07:46:00  2.55
## 10 489435  22349     "DOG BOWL , CHASING BAL…       12 2009-12-01 07:46:00  3.75
## # ℹ 71 more rows
## # ℹ 2 more variables: `Customer ID` <dbl>, Country <chr>

also with expressions.

df %>%
  slice(1:10) %>%
  group_split(Price_Rank = dense_rank(Price))
## <list_of<
##   tbl_df<
##     Invoice    : character
##     StockCode  : character
##     Description: character
##     Quantity   : double
##     InvoiceDate: datetime<UTC>
##     Price      : double
##     Customer ID: double
##     Country    : character
##     Price_Rank : integer
##   >
## >[8]>
## [[1]]
## # A tibble: 2 × 9
##   Invoice StockCode Description Quantity InvoiceDate         Price `Customer ID`
##   <chr>   <chr>     <chr>          <dbl> <dttm>              <dbl>         <dbl>
## 1 489434  21232     STRAWBERRY…       24 2009-12-01 07:45:00  1.25         13085
## 2 489434  21871     SAVE THE P…       24 2009-12-01 07:45:00  1.25         13085
## # ℹ 2 more variables: Country <chr>, Price_Rank <int>
## 
## [[2]]
## # A tibble: 1 × 9
##   Invoice StockCode Description Quantity InvoiceDate         Price `Customer ID`
##   <chr>   <chr>     <chr>          <dbl> <dttm>              <dbl>         <dbl>
## 1 489434  22064     PINK DOUGH…       24 2009-12-01 07:45:00  1.65         13085
## # ℹ 2 more variables: Country <chr>, Price_Rank <int>
## 
## [[3]]
## # A tibble: 1 × 9
##   Invoice StockCode Description Quantity InvoiceDate         Price `Customer ID`
##   <chr>   <chr>     <chr>          <dbl> <dttm>              <dbl>         <dbl>
## 1 489434  22041     "RECORD FR…       48 2009-12-01 07:45:00   2.1         13085
## # ℹ 2 more variables: Country <chr>, Price_Rank <int>
## 
## [[4]]
## # A tibble: 1 × 9
##   Invoice StockCode Description Quantity InvoiceDate         Price `Customer ID`
##   <chr>   <chr>     <chr>          <dbl> <dttm>              <dbl>         <dbl>
## 1 489435  22350     CAT BOWL          12 2009-12-01 07:46:00  2.55         13085
## # ℹ 2 more variables: Country <chr>, Price_Rank <int>
## 
## [[5]]
## # A tibble: 1 × 9
##   Invoice StockCode Description Quantity InvoiceDate         Price `Customer ID`
##   <chr>   <chr>     <chr>          <dbl> <dttm>              <dbl>         <dbl>
## 1 489435  22349     DOG BOWL ,…       12 2009-12-01 07:46:00  3.75         13085
## # ℹ 2 more variables: Country <chr>, Price_Rank <int>
## 
## [[6]]
## # A tibble: 1 × 9
##   Invoice StockCode Description Quantity InvoiceDate         Price `Customer ID`
##   <chr>   <chr>     <chr>          <dbl> <dttm>              <dbl>         <dbl>
## 1 489434  21523     FANCY FONT…       10 2009-12-01 07:45:00  5.95         13085
## # ℹ 2 more variables: Country <chr>, Price_Rank <int>
## 
## [[7]]
## # A tibble: 2 × 9
##   Invoice StockCode Description Quantity InvoiceDate         Price `Customer ID`
##   <chr>   <chr>     <chr>          <dbl> <dttm>              <dbl>         <dbl>
## 1 489434  79323P    PINK CHERR…       12 2009-12-01 07:45:00  6.75         13085
## 2 489434  79323W    WHITE CHER…       12 2009-12-01 07:45:00  6.75         13085
## # ℹ 2 more variables: Country <chr>, Price_Rank <int>
## 
## [[8]]
## # A tibble: 1 × 9
##   Invoice StockCode Description Quantity InvoiceDate         Price `Customer ID`
##   <chr>   <chr>     <chr>          <dbl> <dttm>              <dbl>         <dbl>
## 1 489434  85048     15CM CHRIS…       12 2009-12-01 07:45:00  6.95         13085
## # ℹ 2 more variables: Country <chr>, Price_Rank <int>

- .keep

There is a .keep argument that controls whether to keep or not the grouping columns inside the tables, the default is TRUE.

dfs_list_keep <- df %>%
  slice(1:100) %>%
  group_by(Country) %>%
  group_split(.keep = FALSE)
dfs_list_keep[[1]]
A tibble: 19 x 7

- group_nest()

group_nest() condenses a grouped data frame into a list column with one row for every combination of the grouping columns.

df %>%
  group_by(Country) %>%
  group_nest()
A tibble: 40 x 2
df %>%
  group_by(Country, `Customer ID`) %>%
  group_nest()
A tibble: 4401 x 3

Every tibble of the list column contains the rows relative to that combination of the grouping columns.

df %>%
  group_by(Country) %>%
  group_nest() %>%
  select(data) %>%
  slice(1) %>%
  tidyr::unnest(cols = c(data))
A tibble: 654 x 7
df %>%
  group_by(Country, `Customer ID`) %>%
  group_nest() %>%
  select(data) %>%
  slice(1) %>%
  tidyr::unnest(cols = c(data))
A tibble: 8 x 6

It can be used directly on an ungrouped data frame as well.

df %>%
  group_nest(Country)
A tibble: 40 x 2

We can unnest to the original data frame with the relative function from tidyr, but the rows’ order will be different, following the one of grouping columns.

df %>%
  group_by(Country) %>%
  group_nest() %>%
  tidyr:::unnest(cols = c(data))
A tibble: 525461 x 8

We can nest by expressions.

df %>%
  slice(1:100) %>%
  group_nest(Price_Rank = dense_rank(Price))
A tibble: 37 x 2

- .key

The function has two optional arguments: with .key we can change the name of the list column.

df %>%
  group_by(Country) %>%
  group_nest(.key = "list column")
A tibble: 40 x 2

- keep

And with keep we decide whether or not to keep the grouping columns in the list column’s tibbles (the default is FALSE, not keeping them).

df %>%
  group_by(Country) %>%
  group_nest() %>%
  select(data) %>%
  slice(1) %>%
  tidyr::unnest(cols = c(data))
A tibble: 654 x 7
df %>%
  group_by(Country) %>%
  group_nest(keep = TRUE) %>%
  select(data) %>%
  slice(1) %>%
  tidyr::unnest(cols = c(data))
A tibble: 654 x 8

Using unnest() on all the list column while keep = TRUE returns an error.

df %>%
  group_by(Country) %>%
  group_nest(keep = TRUE) %>%
  tidyr::unnest(cols = c(data))
Error in `tidyr::unnest()`:
! Can't duplicate names between the affected columns and the original
  data.
✖ These names are duplicated:
  ℹ `Country`, from `data`.
ℹ Use `names_sep` to disambiguate using the column name.
ℹ Or use `names_repair` to specify a repair strategy.

- group_trim()

group_trim() suppresses the levels of the factors used to group_by(), in case they are empty after a manipulation (in this case Lebanon).

df %>%
  group_by(factor(Country)) %>%
  filter(n() > 15) %>%
  group_trim() %>%
  group_keys()
A tibble: 39 x 1

- group_map()/modify()/walk()

With group_map() we can apply a function, with a formula syntax, to every group. The result is a list.

So if for example we want the average quantity for every country,

df %>%
  group_by(Country) %>%
  summarise(Avg_Quantity = mean(Quantity))
A tibble: 40 x 2

we can write:

df %>%
  group_by(Country) %>%
  group_map(~ mean(.x$Quantity))
## [[1]]
## [1] 30.66208
## 
## [[2]]
## [1] 12.06518
## 
## [[3]]
## [1] 9.485981
## 
## [[4]]
## [1] 11.36622
## 
## [[5]]
## [1] 82.29412
## 
## [[6]]
## [1] 3.048387
## 
## [[7]]
## [1] 11.61039
## 
## [[8]]
## [1] 12.13466
## 
## [[9]]
## [1] 7.889892
## 
## [[10]]
## [1] 530.4439
## 
## [[11]]
## [1] 19.51437
## 
## [[12]]
## [1] 10.31356
## 
## [[13]]
## [1] 12.90211
## 
## [[14]]
## [1] 13.17911
## 
## [[15]]
## [1] 11.89749
## 
## [[16]]
## [1] 30.34211
## 
## [[17]]
## [1] 11.66197
## 
## [[18]]
## [1] 15.2973
## 
## [[19]]
## [1] 10
## 
## [[20]]
## [1] 29.48214
## 
## [[21]]
## [1] 9.492063
## 
## [[22]]
## [1] 5.461538
## 
## [[23]]
## [1] 14.97403
## 
## [[24]]
## [1] 8.994186
## 
## [[25]]
## [1] 65.66378
## 
## [[26]]
## [1] 1.75
## 
## [[27]]
## [1] 21.30894
## 
## [[28]]
## [1] 10.26289
## 
## [[29]]
## [1] 10.78837
## 
## [[30]]
## [1] 14.57658
## 
## [[31]]
## [1] 14.98291
## 
## [[32]]
## [1] 14.34429
## 
## [[33]]
## [1] 57.91353
## 
## [[34]]
## [1] 18.57877
## 
## [[35]]
## [1] 33.57895
## 
## [[36]]
## [1] 10.92623
## 
## [[37]]
## [1] 13.30093
## 
## [[38]]
## [1] 9.116039
## 
## [[39]]
## [1] 11.01935
## 
## [[40]]
## [1] 7.314815

group_modify() instead returns a data frame, so we have to use it with functions whose output is of that class.

df %>%
  slice(1:100) %>%
  group_by(Country) %>%
  group_modify(~ rows_insert(.x, tibble(Invoice = "xxxxxx"), by = "Invoice"))
A tibble: 102 x 8
Groups: Country [2]

With group_walk() the function we apply will only be evaluated for its possible side effects and it will always return the input .x unaffected.

df %>%
  slice(1:100) %>%
  group_by(Country) %>%
  group_walk(~ rows_insert(.x, tibble(Invoice = "xxxxxx"), by = "Invoice"))

group_walk() can then be used, for example, to print plots (as that is a side effect of plot()) in the middle of a pipe.

df %>%
  slice(1:100) %>%
  group_by(Country) %>%
  group_walk(~ plot(.x$Quantity)) %>%
  group_map(~ mean(.x$Quantity))

## [[1]]
## [1] 11.52632
## 
## [[2]]
## [1] 18.97531

In all of these past examples .x referred to the object, that is the grouped data frame, that was piped into one of these three group_* functions but we can use .y as well when we want to refer to the grouping columns.

df %>%
  slice(1:100) %>%
  group_by(Country) %>%
  group_map(~ paste(.x$`Customer ID`, .y))
## [[1]]
##  [1] "12682 France" "12682 France" "12682 France" "12682 France" "12682 France"
##  [6] "12682 France" "12682 France" "12682 France" "12682 France" "12682 France"
## [11] "12682 France" "12682 France" "12682 France" "12682 France" "12682 France"
## [16] "12682 France" "12682 France" "12682 France" "12682 France"
## 
## [[2]]
##  [1] "13085 United Kingdom" "13085 United Kingdom" "13085 United Kingdom"
##  [4] "13085 United Kingdom" "13085 United Kingdom" "13085 United Kingdom"
##  [7] "13085 United Kingdom" "13085 United Kingdom" "13085 United Kingdom"
## [10] "13085 United Kingdom" "13085 United Kingdom" "13085 United Kingdom"
## [13] "13078 United Kingdom" "13078 United Kingdom" "13078 United Kingdom"
## [16] "13078 United Kingdom" "13078 United Kingdom" "13078 United Kingdom"
## [19] "13078 United Kingdom" "13078 United Kingdom" "13078 United Kingdom"
## [22] "13078 United Kingdom" "13078 United Kingdom" "13078 United Kingdom"
## [25] "13078 United Kingdom" "13078 United Kingdom" "13078 United Kingdom"
## [28] "13078 United Kingdom" "13078 United Kingdom" "13078 United Kingdom"
## [31] "13078 United Kingdom" "15362 United Kingdom" "15362 United Kingdom"
## [34] "15362 United Kingdom" "15362 United Kingdom" "15362 United Kingdom"
## [37] "15362 United Kingdom" "15362 United Kingdom" "15362 United Kingdom"
## [40] "15362 United Kingdom" "15362 United Kingdom" "15362 United Kingdom"
## [43] "15362 United Kingdom" "15362 United Kingdom" "15362 United Kingdom"
## [46] "15362 United Kingdom" "15362 United Kingdom" "15362 United Kingdom"
## [49] "15362 United Kingdom" "15362 United Kingdom" "15362 United Kingdom"
## [52] "15362 United Kingdom" "15362 United Kingdom" "15362 United Kingdom"
## [55] "18102 United Kingdom" "18102 United Kingdom" "18102 United Kingdom"
## [58] "18102 United Kingdom" "18102 United Kingdom" "18102 United Kingdom"
## [61] "18102 United Kingdom" "18102 United Kingdom" "18102 United Kingdom"
## [64] "18102 United Kingdom" "18102 United Kingdom" "18102 United Kingdom"
## [67] "18102 United Kingdom" "18102 United Kingdom" "18102 United Kingdom"
## [70] "18102 United Kingdom" "18102 United Kingdom" "18087 United Kingdom"
## [73] "18087 United Kingdom" "18087 United Kingdom" "18087 United Kingdom"
## [76] "18087 United Kingdom" "18087 United Kingdom" "13635 United Kingdom"
## [79] "13635 United Kingdom" "13635 United Kingdom" "13635 United Kingdom"

All of these functions can also be used on ungrouped data frames,

df %>%
  group_map(~ mean(.x$Quantity))
## [[1]]
## [1] 10.33767

with a custom function (that needs two arguments, hence the ..., even if they don’t do nothing in this instance),

custfun <- function(x, ...){
  head(x)
}
df %>%
  slice(1:100) %>%
  group_by(Country) %>%
  group_map(custfun)
## [[1]]
## # A tibble: 6 × 7
##   Invoice StockCode Description Quantity InvoiceDate         Price `Customer ID`
##   <chr>   <chr>     <chr>          <dbl> <dttm>              <dbl>         <dbl>
## 1 489439  22065     CHRISTMAS …       12 2009-12-01 09:28:00  1.45         12682
## 2 489439  22138     BAKING SET…        9 2009-12-01 09:28:00  4.95         12682
## 3 489439  22139     RETRO SPOT…        9 2009-12-01 09:28:00  4.95         12682
## 4 489439  22352     LUNCHBOX W…       12 2009-12-01 09:28:00  2.55         12682
## 5 489439  85014A    BLACK/BLUE…        3 2009-12-01 09:28:00  5.95         12682
## 6 489439  85014B    RED/WHITE …        3 2009-12-01 09:28:00  5.95         12682
## 
## [[2]]
## # A tibble: 6 × 7
##   Invoice StockCode Description Quantity InvoiceDate         Price `Customer ID`
##   <chr>   <chr>     <chr>          <dbl> <dttm>              <dbl>         <dbl>
## 1 489434  85048     "15CM CHRI…       12 2009-12-01 07:45:00  6.95         13085
## 2 489434  79323P    "PINK CHER…       12 2009-12-01 07:45:00  6.75         13085
## 3 489434  79323W    "WHITE CHE…       12 2009-12-01 07:45:00  6.75         13085
## 4 489434  22041     "RECORD FR…       48 2009-12-01 07:45:00  2.1          13085
## 5 489434  21232     "STRAWBERR…       24 2009-12-01 07:45:00  1.25         13085
## 6 489434  22064     "PINK DOUG…       24 2009-12-01 07:45:00  1.65         13085

and they all have a .keep argument, to preserve the grouping columns in the output.

df %>%
  slice(1:100) %>%
  group_by(Country) %>%
  group_map(custfun, .keep = TRUE)
## [[1]]
## # A tibble: 6 × 8
##   Invoice StockCode Description Quantity InvoiceDate         Price `Customer ID`
##   <chr>   <chr>     <chr>          <dbl> <dttm>              <dbl>         <dbl>
## 1 489439  22065     CHRISTMAS …       12 2009-12-01 09:28:00  1.45         12682
## 2 489439  22138     BAKING SET…        9 2009-12-01 09:28:00  4.95         12682
## 3 489439  22139     RETRO SPOT…        9 2009-12-01 09:28:00  4.95         12682
## 4 489439  22352     LUNCHBOX W…       12 2009-12-01 09:28:00  2.55         12682
## 5 489439  85014A    BLACK/BLUE…        3 2009-12-01 09:28:00  5.95         12682
## 6 489439  85014B    RED/WHITE …        3 2009-12-01 09:28:00  5.95         12682
## # ℹ 1 more variable: Country <chr>
## 
## [[2]]
## # A tibble: 6 × 8
##   Invoice StockCode Description Quantity InvoiceDate         Price `Customer ID`
##   <chr>   <chr>     <chr>          <dbl> <dttm>              <dbl>         <dbl>
## 1 489434  85048     "15CM CHRI…       12 2009-12-01 07:45:00  6.95         13085
## 2 489434  79323P    "PINK CHER…       12 2009-12-01 07:45:00  6.75         13085
## 3 489434  79323W    "WHITE CHE…       12 2009-12-01 07:45:00  6.75         13085
## 4 489434  22041     "RECORD FR…       48 2009-12-01 07:45:00  2.1          13085
## 5 489434  21232     "STRAWBERR…       24 2009-12-01 07:45:00  1.25         13085
## 6 489434  22064     "PINK DOUG…       24 2009-12-01 07:45:00  1.65         13085
## # ℹ 1 more variable: Country <chr>

- group_data()

group_data() stores, for each group, every row index pertaining to that group in a list column named .rows.

df %>%
  group_by(Country) %>%
  group_data()
A tibble: 40 x 2
df %>%
  group_by(Country) %>%
  group_data() %>%
  tidyr::unnest(cols = c(.rows))
A tibble: 525461 x 2

- group_rows()

group_rows() returns the rows’ indexes of every group as a list of ordered vectors.

df %>%
  group_by(Country) %>%
  filter(Country %in% c("Australia", "Lebanon")) %>%
  group_rows()
## <list_of<integer>[2]>
## [[1]]
##   [1]   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18
##  [19]  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36
##  [37]  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54
##  [55]  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72
##  [73]  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90
##  [91]  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108
## [109] 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
## [127] 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
## [145] 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
## [163] 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
## [181] 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
## [199] 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
## [217] 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
## [235] 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
## [253] 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
## [271] 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
## [289] 289 290 291 292 293 294 295 308 309 310 311 312 313 314 315 316 317 318
## [307] 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
## [325] 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
## [343] 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
## [361] 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
## [379] 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
## [397] 409 410 411 412 414 415 416 417 418 419 420 421 422 423 424 425 426 427
## [415] 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
## [433] 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
## [451] 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
## [469] 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
## [487] 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
## [505] 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
## [523] 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
## [541] 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
## [559] 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
## [577] 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
## [595] 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
## [613] 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
## [631] 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
## [649] 662 663 664 665 666 667
## 
## [[2]]
##  [1] 296 297 298 299 300 301 302 303 304 305 306 307 413

- group_keys()

group_keys() returns a data frame with all the unique values of the grouping columns, if one,

df %>%
  group_by(Country) %>%
  group_keys()
A tibble: 40 x 1

and one with as many columns as the ones specified as arguments of group_by(), if several.

df %>%
  group_by(Country, `Customer ID`) %>%
  group_keys()
A tibble: 4401 x 2

In this case the number of rows depends on the number of unique existing combinations between the grouping columns.

df %>%
  group_by(StockCode, Description) %>%
  group_keys()
A tibble: 6963 x 2
df %>%
  group_by(StockCode) %>%
  slice(1) %>%
  group_by(StockCode, Description) %>%
  group_keys()
A tibble: 4631 x 2

The group_keys() are also what functions like summarise() and slice() order their output by.

df %>%
  group_by(Country) %>%
  summarise(Avg_Price = mean(Price))
A tibble: 40 x 2
df %>%
  group_by(Country, `Customer ID`) %>%
  summarise(Avg_Price = mean(Price))
`summarise()` has grouped output by 'Country'. You can override using the
`.groups` argument.
A tibble: 4401 x 3
Groups: Country [40]
df %>%
  group_by(Country, `Customer ID`) %>%
  slice(1)
A tibble: 4401 x 8
Groups: Country, Customer ID [4401]

- group_indices()

group_indices() returns a vector with a group identifier, in form of a digit, for every row of the data frame.

df %>%
  slice(1:100) %>%
  group_by(Country) %>%
  group_indices()
##   [1] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
##  [38] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 1
##  [75] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2

The indices are not assigned randomly, but following the order of the group_keys().

- group_vars()

group_vars() lists the grouping columns as a vector.

df %>%
  group_by(Country) %>%
  group_vars()
## [1] "Country"
df %>%
  group_by(Country, `Customer ID`) %>%
  group_vars()
## [1] "Country"     "Customer ID"

- groups()

groups() does the same, but as a list.

df %>%
  group_by(Country) %>%
  groups()
## [[1]]
## Country
df %>%
  group_by(Country, `Customer ID`) %>%
  groups()
## [[1]]
## Country
## 
## [[2]]
## `Customer ID`

- group_size()

group_size() supplies the size (as per the number of rows) of each group as a unnamed vector.

df %>%
  group_by(Country) %>%
  group_size()
##  [1]    654    537    107   1054     34     62     77    906    554    428
## [11]   9670    354   5772   8129    517     76     71     74    731    224
## [21]     63     13    154    172   2769     32    369    194   1101    111
## [31]    117   1278    902   1187     76    244    432 485852    310     54

As always, the order is dictated by the group_keys().

- n_groups()

n_groups() supplies the overall number of groups.

df %>%
  group_by(Country) %>%
  n_groups()
## [1] 40

- context

This family of functions, to be used inside a mutate() or summarise() / reframe() call, provides information about the groups.

- n()

n() returns the number of rows per group as a data frame.

df %>%
  group_by(Country) %>%
  summarise(n = n())
A tibble: 40 x 2

NAs are counted as one value.

df %>%
  group_by(`Customer ID`) %>%
  summarise(n = n()) %>%
  arrange(desc(n))
A tibble: 4384 x 2

n() can be used in other functions as well,

df %>%
  filter(Country == "Lebanon") %>%
  slice(n())
A tibble: 1 x 8

as a replacement of nrow(df) for when we altered the original data frame

df %>%
  filter(Country == "Lebanon") %>%
  slice(nrow(df))
A tibble: 0 x 8

and we don’t want to use the magrittr dot placeholder.

df %>%
  filter(Country == "Lebanon") %>%
  slice(nrow(.))
A tibble: 1 x 8

Here the data frame was not grouped, so n() provided the total number of rows, as if there was just one group.

- cur_group()

cur_group() returns one tibble for every combination of the grouping variables, with every one of them containing the relative group_keys().

df %>%
  group_by(Country) %>%
  summarise(data = cur_group())
A tibble: 40 x 2
df %>%
  group_by(Country) %>%
  summarise(data = cur_group()) %>%
  select(data) %>%
  slice(1) %>%
  tidyr::unnest(cols = c(data))
A tibble: 1 x 1
df %>%
  group_by(Country, `Customer ID`) %>%
  summarise(data = cur_group())
`summarise()` has grouped output by 'Country'. You can override using the
`.groups` argument.
A tibble: 4401 x 3
Groups: Country [40]
df %>%
  group_by(Country, `Customer ID`) %>%
  summarise(data = cur_group()) %>%
  ungroup() %>%
  select(data) %>%
  slice(1) %>%
  tidyr::unnest(cols = c(data))
`summarise()` has grouped output by 'Country'. You can override using the
`.groups` argument.
A tibble: 1 x 2

We can use cur_group() to apply manipulations that change depending on the group they are applied to, like filtering on only one group.

df %>%
  group_by(Country) %>%
  filter(cur_group()$Country != "United Kingdom" | Quantity > 10)
A tibble: 148280 x 8
Groups: Country [40]

In this example the first test checks, for every group, on whether the value of the Country column in the tibble provided by cur_group() is different from United Kingdom.

In case of TRUE, we will preserve every row, regardless of the second test, as we specified an OR condition.

In case of FALSE, we will preserve only the rows where the second test is TRUE, which are the ones where the Quantity > 10 and the country is United Kingdom.

We can also filter each group for a different value.

These different values must be stored in a tibble, and the correct one for each group will be accessed by subsetting it with the grouping column of the tibble returned by cur_group().

Min_Quantity <- tibble("France" = 2,
                       "Italy" = 10,
                       "Germany" = 5)
df %>%
  filter(Country %in% c("France", "Italy", "Germany")) %>%
  group_by(Country) %>%
  filter(Quantity >= Min_Quantity[[cur_group()$Country]])
A tibble: 11839 x 8
Groups: Country [3]

- cur_group_id()

cur_group_id() supplies a numeric identifier for every group, assigned following the order of the group_keys().

df %>%
  group_by(Country) %>%
  mutate(id = cur_group_id())
A tibble: 525461 x 9
Groups: Country [40]

- cur_group_rows()

cur_group_rows() returns the rows indices for every row of a grouped data frame, sorted by the group_keys().

df %>%
  group_by(Country) %>%
  reframe(row = cur_group_rows())
A tibble: 525461 x 2
df %>%
  group_by(Country, `Customer ID`) %>%
  reframe(row = cur_group_rows())
A tibble: 525461 x 3