TarJae
TarJae

Reputation: 78917

How to group dataset depending on row start

I have a dataset with 2 columns:

library(tidyverse)
col1 <- c("a", "b", "c", "d", "a", "b","c", "e", "f", "a", "b", "m", "l", "a", "z", "i")
col2 <- c(1:16)
df <- tibble(col1, col2)

How can I group col1 with id: starting each time when a is occurring in the row of col1.

Desired output:

enter image description here

Upvotes: 1

Views: 109

Answers (1)

tspano
tspano

Reputation: 701

You can do

df %>% group_by(id_Group = cumsum(col1=="a"))

Upvotes: 4

Related Questions