Group by one, add min and max for other

This is my first post. Please be gentle. :slight_smile:

How do I transform a into b?

library(tidyverse)

a <- tribble(
  ~col,   ~yr,
  "red",  2010,
  "red",  2012,
  "blue", 2007,
  "red",  2011,
  "blue", 2010,
  "red",  2007
)

b <- tribble(
  ~col,   ~yr_min, ~yr_max,
  "red",  2007,    2012,
  "blue", 2007,    2010
)

Hi there,

See below :slight_smile: And welcome to the forum!

library(tidyverse)

a <- tribble(
  ~col,   ~yr,
  "red",  2010,
  "red",  2012,
  "blue", 2007,
  "red",  2011,
  "blue", 2010,
  "red",  2007
)


output <- a %>% 
  group_by(col) %>% 
  summarise(yr_min = min(yr), yr_max = max(yr))

output
#> # A tibble: 2 x 3
#>   col   yr_min yr_max
#>   <chr>  <dbl>  <dbl>
#> 1 blue    2007   2010
#> 2 red     2007   2012

Created on 2021-10-30 by the reprex package (v2.0.0)

Thanks @GreyMerchant !

No problem :slight_smile: Feel free to mark it as the solution if it solved your problem.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.