0

I have a data frame with a time column (POSIXct format in yyyy-mm-dd HH:MM:SS) and a status column (character format). For simple representation, let's assume, the status column has modes a,b, and c.

I need to change the mode of the 'status' column based on the following condition;

  • if a particular mode (for eg: b) appears for more than 5 sec, then keep the mode as 'b',
  • if more 'b' appears for less than 5 sec, roll back the current mode ('b') to its previous mode.

In my dataset, I need to apply the above condition for 30 sec, but for simple representation of the problem, I mentioned here the status change threshold as 5 sec.

Example Dataset:

Time (POSIXct) Status (Character)
2022-12-01 00:00:00 a
2022-12-01 00:00:01 a
2022-12-01 00:00:02 b
2022-12-01 00:00:03 b
2022-12-01 00:00:04 b
2022-12-01 00:00:05 b
2022-12-01 00:00:06 b
2022-12-01 00:00:07 c
2022-12-01 00:00:08 c
2022-12-01 00:00:09 b
2022-12-01 00:00:10 b
2022-12-01 00:00:11 a
2022-12-01 00:00:12 a
2022-12-01 00:00:13 a

Desired output:

Time (POSIXct) Status (Character)
2022-12-01 00:00:00 a
2022-12-01 00:00:01 a
2022-12-01 00:00:02 b
2022-12-01 00:00:03 b
2022-12-01 00:00:04 b
2022-12-01 00:00:05 b
2022-12-01 00:00:06 b
2022-12-01 00:00:07 c
2022-12-01 00:00:08 c
2022-12-01 00:00:09 c
2022-12-01 00:00:10 c
2022-12-01 00:00:11 a
2022-12-01 00:00:12 a
2022-12-01 00:00:13 a

I am not sure how I can proceed with changing the status based on the time column. Previously, I had to change the status, just based on the previous row mode and I used 'rle' and 'ifelse' conditions.

Thanks for your help.

Karthik
  • 117
  • 7

0 Answers0