rjen
rjen

Reputation: 1972

Groups from occurence of value in variable

I have a variable that looks like:

library(tibble)

data <- tibble(toBeGrouped = c(TRUE, sample(c(TRUE, FALSE), 9, replace = TRUE)))

data

# A tibble: 10 x 1
   toBeGrouped
   <lgl>      
 1 TRUE       
 2 FALSE      
 3 FALSE      
 4 FALSE      
 5 FALSE      
 6 TRUE       
 7 FALSE      
 8 FALSE      
 9 FALSE      
10 TRUE

I am trying to make a new variable that groups the existing variable by the occurrence of the value TRUE. That is:

# A tibble: 10 x 1
   toBeGrouped   groups
   <lgl>         <int>
 1 TRUE          1
 2 FALSE         1
 3 FALSE         1
 4 FALSE         1
 5 FALSE         1
 6 TRUE          2
 7 FALSE         2
 8 FALSE         2
 9 FALSE         2
10 TRUE          3

How can the variable 'groups' be created?

Upvotes: 1

Views: 43

Answers (1)

akrun
akrun

Reputation: 886938

We can use cumsum on the logical column to add 1 whenever there is a TRUE value as TRUE/FALSE is 1/0

library(dplyr)
data <- data %>%
           mutate(groups = cumsum(toBeGrouped))

data

data <- structure(list(toBeGrouped = c(TRUE, FALSE, FALSE, FALSE, FALSE, 
TRUE, FALSE, FALSE, FALSE, TRUE)), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

Upvotes: 2

Related Questions