Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

dplyr

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?

like image 391
Parseltongue Avatar asked Oct 30 '25 19:10

Parseltongue


1 Answers

We can use gl

library(dplyr)
df <- df %>%
    group_by(group) %>% 
    mutate(id = as.integer(gl(n(), 2, n()))) %>%
    ungroup
like image 185
akrun Avatar answered Nov 02 '25 08:11

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!