ifelse before and after a value

Viewed 50

Here is a df for example:

test_df <- structure(list(plant_id = c("plant_1", "plant_1", "plant_1", "plant_1", "plant_1",
                                       "plant_2", "plant_2", "plant_2", "plant_2", "plant_2", 
                                       "plant_3", "plant_3", "plant_3", "plant_3", "plant_3",
                                       "plant_4", "plant_4", "plant_4", "plant_4", "plant_4"), 
                          skipped = c(0, 0, 0, 1, 0, 
                                      0, 0, 1, 0, 0,
                                      0, 0, 1, 0, 0, 
                                      0, 0, 1, 0,0)), 
                     row.names = c(NA, -20L), class = "data.frame", 
                     .Names = c("plant_sp", "skipped"))

I need the values in each group at the column "skipped" to be "0" if it comes before the "1" and "2" if it comes after. for exmaple at group "plant_1" I need it instead of beeing

"0,0,0,1,0" to be "0,0,0,1,2".

and at group 2 instead of

"0,0,1,0,0" to be "0,0,1,2,2".

a dplyr solution would be great!

Thanks a lot!

1 Answers

Using dplyr::group_by & if_else with base cumsum

library(dplyr)
test_df %>%
  group_by(plant_sp) %>%
  mutate(skipped = if_else(cumsum(skipped) == 0, 0,
    if_else(skipped == 1, 1, 2))) %>%
  ungroup()

Output

# A tibble: 20 x 2
   plant_sp skipped
   <chr>      <dbl>
 1 plant_1        0
 2 plant_1        0
 3 plant_1        0
 4 plant_1        1
 5 plant_1        2
 6 plant_2        0
 7 plant_2        0
 8 plant_2        1
 9 plant_2        2
10 plant_2        2
11 plant_3        0
12 plant_3        0
13 plant_3        1
14 plant_3        2
15 plant_3        2
16 plant_4        0
17 plant_4        0
18 plant_4        1
19 plant_4        2
20 plant_4        2
Related