For each participant and each trial I need to check that for all the consecutive rows in CURRENT_ID, the first row has a value of 0 in the column A, and the last row has a value of 0 in the column B. If both conditions are fulfil, I would like to have a value of 0 in the new column C, if they are not I would like to have a value of 1.
head(mydf, 10)
#> # A tibble: 10 x 6
#> A B participant trial CURRENT_ID C
#> <dbl> <dbl> <chr> <dbl> <dbl> <dbl>
#> 1 0 1 ppt01 45 3 0
#> 2 1 0 ppt01 45 4 0
#> 3 0 1 ppt01 45 10 0
#> 4 0 0 ppt01 45 11 0
#> 5 1 0 ppt01 45 12 0
#> 6 0 1 ppt01 87 2 0
#> 7 1 0 ppt01 87 3 0
#> 8 1 1 ppt01 87 4 1
#> 9 1 1 ppt01 87 5 1
#> 10 0 1 ppt01 34 6 0
I need to consider every pair of consecutive rows (consecutive based on the values of CURRENT_ID) for each participant and trial. In the example above, rows 8 and 9 get a value of 1 in the new column C because row 8 has a 1 (instead of 0) in column A, and row 9 has a 1 (instead of 0) in column B.
Here an example how the rows should be compared, with participant ppt01 and trial 87
A B participant trial CURRENT_ID C
0 1 ppt01 87 2 0
1 0 ppt01 87 3 0
1 0 ppt01 87 3 0
1 1 ppt01 87 4 1
1 1 ppt01 87 4 1
1 1 ppt01 87 5 1
Data:
mydf <- structure(list(A = c(0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0,
1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0,
1, 1), B = c(1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1,
0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1
), participant = c("ppt01", "ppt01", "ppt01", "ppt01", "ppt01",
"ppt01", "ppt01", "ppt01", "ppt01", "ppt01", "ppt01", "ppt01",
"ppt01", "ppt01", "ppt01", "ppt01", "ppt01", "ppt01", "ppt01",
"ppt01", "ppt01", "ppt02", "ppt02", "ppt02", "ppt02", "ppt02",
"ppt02", "ppt02", "ppt02", "ppt02", "ppt02", "ppt02", "ppt02",
"ppt02", "ppt02", "ppt02", "ppt02"), trial = c(45, 45, 45, 45,
45, 87, 87, 87, 87, 34, 34, 34, 34, 34, 34, 8, 8, 8, 8, 8, 8,
87, 87, 87, 87, 55, 55, 55, 55, 55, 55, 22, 22, 22, 22, 22, 22
), CURRENT_ID = c(3, 4, 10, 11, 12, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 5, 6, 9, 10, 11, 12, 2, 3, 4, 5, 5, 6, 9, 10, 11, 12, 2,
3, 4, 10, 11, 12), C = c(0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
1, 0, 1, 1)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -37L), spec = structure(list(cols = list(
A = structure(list(), class = c("collector_double", "collector"
)), B = structure(list(), class = c("collector_double", "collector"
)), participant = structure(list(), class = c("collector_character",
"collector")), trial = structure(list(), class = c("collector_double",
"collector")), CURRENT_ID = structure(list(), class = c("collector_double",
"collector")), C = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1), class = "col_spec"))