Parseltongue
Parseltongue

Reputation: 11657

Assign unique id to consecutive rows within a grouping variable in 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?

Upvotes: 4

Views: 1841

Answers (3)

Onyambu
Onyambu

Reputation: 79198

Another option is to use the rep function:

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

Upvotes: 3

ThomasIsCoding
ThomasIsCoding

Reputation: 101064

Another dplyr option using ceiling + row_number()

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

Upvotes: 1

akrun
akrun

Reputation: 886948

We can use gl

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

Upvotes: 4

Related Questions