Grouping variables select first row (keep one column), last row (keep different column)

Viewed 79

I have the following table:

id  origin destination price
 1     A      B          2
 1     C      D          2
 2     A      B          3
 3     B      E          6
 3     E      C          6
 3     C      F          6

Basically what I want to do is to group it by id, select the first element from origin, and keep the last element from destination resulting in this table.

id  origin destination price
 1     A      D          2
 2     A      B          3
 3     B      F          6

I know how to select the first and last row, but not to do what I want.

df %>%
group_by(id) %>%
slice(c(1, n())) %>%
ungroup()

Is it possible to do this with dplyr or even with data.table?

2 Answers
Related