Cumulative sum loop dplyr

a tidyverse approach:

library(tidyverse)

library(magrittr)

# your data frame

t1 <- tribble( ~value, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1 )

# rle does the work here of figuring out how many rows in each group

t1$grp <- t1$value %>% rle %>% extract2("lengths") %>% seq_along %>% rep( t1$value %>% rle %>% extract2("lengths") )

# nesting

t2 <- t1 %>% group_by(grp) %>% nest

# generating the row types you asked for in your question

t2$data %<>% map( (i)

  i %>% 
    mutate(
      v2 = rep(
        c(" ", i$value %>% sum),
        c(i %>% nrow %>% subtract(1), 1)
      )
    )
  )

)

t2$data %>% list_rbind

should return

# A tibble: 10 × 2

value v2
<dbl> <chr> 1 1 " "
2 1 " "
3 1 "3"
4 0 " "
5 0 "0"
6 1 "1"
7 0 " "
8 0 "0"
9 1 " "
10 1 "2"

/r/rstats Thread