I have a time series dataset where participants did a series of actions, which are identified with codes (approx. 1-25). Participants could repeat any action any number of times. I am trying to collapse any sequential, repeated instances of action #6. The problem is that the action can be repeated 1,2,3,4 times in a session, then they did other actions, and then action #6 is repeated 1, 2 times again. I need both the 4 and 2. Problem is that the session and participant are the same so it's hard to collapse appropriately (keeping both sequences).
I have tried this code, courtesy of data frame cumulative run length encoding in R:
x <- rle(full_data2$action_name) ## run rle on the relevant column
new <- sequence(x$lengths) ## create a sequence of the lengths values
new = as.data.frame(new)
full_data2$rle = new
This did create a column with sequences in the data. But I am struggling to extract just the top number of all sequences for each student, with no other variables I can use to collapse.
How can I collapse this so the highest number of all RLE sequences is retained, within the session? In the sample data, I need 13, 6, and 2. Here is the dput output for the sample data:
structure(list(student_id = c(3935850L, 3935850L, 3935850L, 3935850L,
3935850L, 3935850L, 3935850L, 3935850L, 3935850L, 3935850L, 3935850L,
3935850L, 3935850L, 3935850L, 3935850L, 3935850L, 3935850L, 3935850L,
3935850L, 3935850L, 3935850L, 3935850L, 3935850L, 3935850L, 3935850L,
3935850L, 3935850L, 3935850L), act_time = structure(c(1L, 1L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 5L, 6L, 6L, 7L, 8L, 9L,
9L, 9L, 9L, 10L, 10L, 10L, 11L, 12L, 12L, 12L), .Label = c("2017-12-10 00:39:52",
"2017-12-10 00:40:17", "2017-12-10 00:40:18", "2017-12-10 00:40:19",
"2017-12-10 00:40:36", "2017-12-10 00:40:37", "2017-12-10 00:40:38",
"2017-12-10 00:40:42", "2017-12-10 00:41:03", "2017-12-10 00:41:04",
"2017-12-10 00:41:08", "2017-12-10 00:41:45"), class = "factor"),
code = c(25L, 19L, 25L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 19L, 25L, 6L, 6L, 6L, 6L, 6L, 6L, 19L, 25L,
6L, 6L), sequence = c(1L, 1L, 1L, 1L, 2L, 3L, 4L, 5L, 6L,
7L, 8L, 9L, 10L, 11L, 12L, 13L, 1L, 1L, 1L, 2L, 3L, 4L, 5L,
6L, 1L, 1L, 1L, 2L)), .Names = c("student_id", "act_time",
"code", "sequence"), row.names = c(NA, -28L), class = "data.frame")