简体   繁体   中英

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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM