1

I have a logical vector:

FALSE FALSE FALSE TRUE TRUE FALSE FALSE FALSE FALSE

I want to split this vector into three groups: the first one (3 first FALSE) the second one (2 TRUE) and the last one (two last FALSE). How can I do the loop to split the vector?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    `split(x, cumsum(c(0,diff(x)!=0)))` Taken from [here](https://stackoverflow.com/questions/29661269/increment-by-1-for-every-change-in-column-in-r). – Ronak Shah Oct 31 '17 at 01:23
  • 2
    `rleid(x)` in `data.table` too – thelatemail Oct 31 '17 at 01:32
  • 4
    Possible duplicate of [Increment by 1 for every change in column in R](https://stackoverflow.com/questions/29661269/increment-by-1-for-every-change-in-column-in-r) – Kevin Arseneau Oct 31 '17 at 01:39

1 Answers1

0

Here is a solution that assumes you want to define a group variable along side the logical vector in a data frame.

library(dplyr)

YourLogicalVector <- rep(c(FALSE, TRUE, FALSE), c(3, 2, 4))

data.frame(X = YourLogicalVector) %>%
  mutate(Boundary = X != lag(X, default = FALSE),
         Group = cumsum(Boundary))