Skip to content

Instantly share code, notes, and snippets.

@brshallo
Last active November 24, 2021 17:31
Show Gist options
  • Select an option

  • Save brshallo/61a97577bd24aad7de4c0c1e284fe1d8 to your computer and use it in GitHub Desktop.

Select an option

Save brshallo/61a97577bd24aad7de4c0c1e284fe1d8 to your computer and use it in GitHub Desktop.
library(tidyverse)

penguins <- palmerpenguins::penguins %>% na.omit()

### ACTUALLY THE BEST WAY TO DO THIS WOULD BE LIKE:
# penguins %>% 
#   group_nest(species, year) %>% 
#   pivot_wider(names_from = year,
#               values_from = data)

penguins %>% 
  split(.$year) %>% 
  imap( ~group_nest(.x, species, .key = paste0("penguins", .y)) ) %>% 
  reduce(left_join, by = "species")
#> # A tibble: 3 x 4
#>   species         penguins2007       penguins2008       penguins2009
#>   <fct>     <list<tibble[,7]>> <list<tibble[,7]>> <list<tibble[,7]>>
#> 1 Adelie              [44 x 7]           [50 x 7]           [52 x 7]
#> 2 Chinstrap           [26 x 7]           [18 x 7]           [24 x 7]
#> 3 Gentoo              [33 x 7]           [45 x 7]           [41 x 7]

## An even worse alternative that I was doing initially was:
## using a call to rename() rather than using the .key argument in group_nest()... 
#   imap( ~group_nest(.x, species) %>% rename(!!.y := data) )
## But changed after seeing: https://community.rstudio.com/t/how-to-name-the-nesting-column-when-using-tidyr-nest-with-a-grouped-tibble/43196/2?u=brshallo

Created on 2021-11-24 by the reprex package (v2.0.0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment