Q:

How not to dplyr::summarize on alphabetic order in R

I want to summarize relocations (between cities), based on a unique ID number.  A sample dataframe, with two unique ID's: 
  year ID city   adress
1 2013  1    B adress_1
2 2014  1    B adress_1
3 2015  1    A adress_2
4 2016  1    A adress_2
5 2013  2    B adress_3
6 2014  2    B adress_3
7 2015  2    C adress_4
8 2016  2    C adress_4

I have provided a sample code below.  The summaries are correct, except for one thing.  If, for example, a relocation is found between city B and city A, I want an output of relocation found from city B to city A (and number of times 1 = seen once in the dataframe).  However, because of the properties of the summary function (and the tendency to store output in alphabetic order), I get the following output 
tmp <- df %>% group_by(ID, city, adress) %>% summarize(numberofyears = n())

tmp <- tmp %>% 
  group_by(ID) %>% 
  #filter(n() >1) %>% 
  mutate(from = city[1], from_adres = adress[1], from_years = numberofyears[1],  to = city[2],
  to_adres = adress[2], to_years = numberofyears[2]) %>% 
  distinct(ID, .keep_all = TRUE) %>% select(-c(2:3))

# A tibble: 2 x 8
# Groups:   ID [2]
     ID numberofyears from  from_adres from_years to    to_adres to_years
  <dbl>         <int> <fct> <fct>           <int> <fct> <fct>       <int>
1     1             2 A     adress_2            2 B     adress_1        2
2     2             2 B     adress_3            2 C     adress_4        2

Which is wrong, because we know that adress_1 preceed adress_2.  When summarizing a relocation from City B to City C, I get the right results. 
It is a very small detail, but an important one as I tried to demonstrate.  Any suggestions would be very much appreciated!  

A:

Similar to @jyjek but this will allow for the possibility of more than one move per ID. 
library(tidyverse)

df <- data.frame(year = rep(2013:2016, 2),
                 ID = rep(1:2, each = 4),
                 city = c("B", "B", "A", "A", "B", "B", "C", "C"),
                 address = rep(1:4, each = 2),
                 stringsAsFactors = FALSE)

df %>% 
  group_by(ID, city, address) %>% 
  #note the first and last year at the address
  summarise(startyear = min(year),
            endyear = max(year)) %>% 
  #sort by ID and year
  arrange(ID, startyear) %>% 
  group_by(ID) %>% 
  #grab the next address for each ID
  mutate(to = lead(city),
         to_address = lead(address),
         to_years = lead(endyear) - lead(startyear) + 1,
         from_years = endyear - startyear + 1) %>% 
  #exclude the last row of each ID, since there's no next address being moved to
  filter(!is.na(to)) %>% 
  select(ID, from = city, from_address = address, from_years, to, to_address, to_years)

