Q:

How to id the rows that are between a match of string in r

I would like to be able to identify the fruits that are between the bananas with a unique value and have the last banana also marked with this unique value. Everything else, like before the first banana or after the last banana or if there are two, three bananas in a row - is not of my interest - they can have 0 as value or be deleted. Please refer to the desired output if I sound too confusing. I hope someone has an idea. I've been googling and stackoverflowing without any success. I hope it is not ridiculously easy that no one even asked before.
  fruits <- c("apples", "pears","bananas", "cherries")
  customer <- rep(c(1:10), each = 3)
  set.seed(1236)
  df_fruits <- data.frame(customer = sample(customer, 30, replace = T),
                    fruits = sample(fruits,30, replace = T, prob=c(0.29,0.60,0.5,0.1)))
  df_fruits <- distinct(df_fruits,.keep_all = T)
  df_fruits

Desired output
    customer   fruits section
1         8    pears       0
2         7 cherries       0
3         5  bananas       0
4         5    pears       1
5        10  bananas       1
6         9    pears       2
7        10    pears       2
8         1   apples       2
9         1    pears       2
10        4    pears       2
11        6    pears       2
12        6 cherries       2
13        4   apples       2
14        8   apples       2
15        2    pears       2
16        1  bananas       2
17        8  bananas       0
18        9  bananas       0
19        3  bananas       0
20        3    pears       3
21        2  bananas       3

Thank you in advance!

A:

I wasn't sure I understood how you wanted to handle the bananas, but this might get you closer to what you need:
library(dplyr)

df_fruits %>%
  mutate(section = lag(cumsum(ifelse(fruits != lag(fruits) & fruits == "bananas", 1, 0)), default=0)) %>%
  filter (!(fruits == lag(fruits) & fruits == "bananas"))

customer   fruits section
1         8    pears       0
2         7 cherries       0
3         5  bananas       0
4         5    pears       1
5        10  bananas       1
6         9    pears       2
7        10    pears       2
8         1   apples       2
9         1    pears       2
10        4    pears       2
11        6    pears       2
12        6 cherries       2
13        4   apples       2
14        8   apples       2
15        2    pears       2
16        1  bananas       2
17        3    pears       3
18        2  bananas       3

Edit: I added filter to remove duplicate bananas which I just read was a consideration.

