title: Extracting co-anomalies across shared time durations in R
body: <p>I need to extract co-anomalies from a data-frame which already contains univariate anomalies.</p>
  <pre><code># Libraries
  library(dplyr)
  library(lubridate)
  library(stringr)
  
  # Create input dataframe
  DF &lt;- data.frame(
    rowID = as.factor(c(1,2,3,4,5,6,7,8)),
    Start = as_datetime(c('2022-01-01 09:00:00', '2022-01-01 12:00:00', '2022-01-02 15:00:00',
                          '2022-01-02 23:30:00', '2022-01-03 00:10:00', '2022-01-29 00:10:00',
                          '2023-12-25 06:00:00', '2023-12-25 08:00:00')),
    Finish = as_datetime(c('2022-01-01 11:00:00', '2022-01-01 15:00:00','2022-01-03 01:00:00',
                           '2022-01-02 23:50:00', '2022-01-03 03:00:00', '2022-01-31 03:00:00',
                           '2023-12-25 11:00:00', '2023-12-25 12:00:00')),
    Process = c('Process1', 'Process2', 'Process1', 'Process2', 'Process3', 'Process3', 'Process3', 'Process3'),
    Anomaly = c('Y','N','Y','Y','Y', 'Y', 'Y', 'Y')
  ) %&gt;%
    arrange(Start, Process) %&gt;%
    mutate(Interval = interval(Start, Finish)) %&gt;%
    as_tibble()
  </code></pre>
  <p>I'm able to successfully tag co-anomalies which occurred over similar time periods as the process of interest (Process3).</p>
  <pre><code># Declare process of interest
  c &lt;- 'Process3'
  
  # Extract co-anomalies within and between Process3
  Result &lt;- DF %&gt;%
    filter(int_overlaps(Interval, Interval[Process == c]) == TRUE) %&gt;%
    mutate(coAnomaly = ifelse(Anomaly == 'Y', 'Y', 'N')) %&gt;%
    left_join(DF, ., by = c('rowID' = 'rowID')) %&gt;%
    select(contains('.x'), coAnomaly) %&gt;%
    rename_with(~str_remove(., '.x'))
  </code></pre>
  <p>The code correctly tags co-anomalies between process 3 and other processes. Although it makes errors when detecting process 3 against itself.</p>
  <p>Row 6 is an error, the anomaly doesn't co-occur <em>within</em> another Process3 or <em>between</em> any other process.</p>
  <p>I'm trying to correctly tag:</p>
  <ol>
  <li>Which Process3s co-occurred with other-processes (Between LHS)</li>
  <li>Which other-processes co-occurred with Process3s (Between RHS)</li>
  <li>Which Process3s co-occurred with Process3s (Within)</li>
  </ol>