Q:

Add Previous Row to Corresponding Column by Group in R

I will post a reproducible Example.
id <- c(1,1,1,1,2,2,1,1)
group <- c("a","b","c","d","a","b","c","d")
df <- data.frame(id, group)

I want something like this as end result.
+====+========+========+
| id | group1 | group2 |
+====+========+========+
|  1 | a      | b      |
+----+--------+--------+
|  1 | b      | c      |
+----+--------+--------+
|  1 | c      | d      |
+----+--------+--------+
|  1 | d      | -      |
+----+--------+--------+
|  2 | a      | b      |
+----+--------+--------+
|  2 | b      | -      |
+----+--------+--------+
|  1 | c      | d      |
+----+--------+--------+
|  1 | d      | -      |
+----+--------+--------+

Just to mention the order of ID's matter. I have another column as timestamp.

A:

One solution with dplyr and rleid from data.table:
library(dplyr)

df %>% 
  mutate(id2 = data.table::rleid(id)) %>% 
  group_by(id2) %>% 
  mutate(group2 = lead(group))

# A tibble: 8 x 4
# Groups:   id2 [3]
     id group   id2 group2
  <dbl> <fct> <int> <fct> 
1  1.00 a         1 b     
2  1.00 b         1 c     
3  1.00 c         1 d     
4  1.00 d         1 NA    
5  2.00 a         2 b     
6  2.00 b         2 NA    
7  1.00 c         3 d     
8  1.00 d         3 NA    

