ltong
ltong

Reputation: 543

R: Sequential Single Column to Two Columns

I have a dataframe like the following, where each individual (ID) travels to a location sequentially. I would like to restructure this dataframe so that I can get a From column and a To column for each ID

ID   location  order
1    6141500   1
1    6140690   2
2    6141450   1
2    6140430   2
2    6141450   3

Ideal output:

From       To  
6141500    6140690   
6141450    6140430
6140430    6141450   

Upvotes: 1

Views: 20

Answers (1)

Onyambu
Onyambu

Reputation: 79188

df %>%
  group_by(ID)%>%
  summarise(from = location, to = lead(location),.groups = 'drop')%>%
  na.omit()

# A tibble: 3 × 3
     ID    from      to
  <int>   <int>   <int>
1     1 6141500 6140690
2     2 6141450 6140430
3     2 6140430 6141450

Upvotes: 1

Related Questions