Assign unique id to consecutive rows within a grouping variable in dplyr

Viewed 662

Let's say I have the following data.frame:

a <- data.frame(group = "A", value = rnorm(mean = 1, sd = 2, n = 150))
b <- data.frame(group = "B", value = rnorm(mean = 1, sd = 2, n = 150))
c <- data.frame(group = "C", value = rnorm(mean = 1, sd = 2, n = 150))
df <- bind_rows(a, b, c)

I'd like to create a unique ID for every consecutive pair of rows within a grouping variable (group), like:

df %>% group_by(group) %>% mutate(...)

So each "dyad" within a group should have a unique ID

Any ideas?

3 Answers

We can use gl

library(dplyr)
df <- df %>%
    group_by(group) %>% 
    mutate(id = as.integer(gl(n(), 2, n()))) %>%
    ungroup

Another dplyr option using ceiling + row_number()

df %>%
  group_by(group) %>%
  mutate(id = ceiling(row_number() / 2)) %>%
  ungroup()

Another option is to use the rep function:

df %>%
  group_by(group) %>%
  mutate(id = rep(seq(n()), each = 2, length = n())) %>%
  ungroup()
Related