Rana Usman
Rana Usman

Reputation: 1051

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.

Upvotes: 0

Views: 47

Answers (2)

tyluRp
tyluRp

Reputation: 4768

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    

Upvotes: 2

Bruno Vilela
Bruno Vilela

Reputation: 103

If I understood correct your question, you can use the following function:

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)

add_group2 <- function(df) {
  n <-length(group)
  group2 <- as.character(df$group[2:n])
  group2 <- c(group2, "-")
  group2[which(c(df$id[-n] - c(df$id[2:n]), 0) != 0)] <- "-"
  return(data.frame(df, group2))
}
add_group2(df)

Result should be:

 id group group2
1  1     a      b
2  1     b      c
3  1     c      d
4  1     d      -
5  2     a      b
6  2     b      -
7  1     c      d
8  1     d      -

Upvotes: 1

Related Questions