title: Is there a way to loop through different levels of a factor for anomaly detection
body: <p>I am using the 'anomalize' package for anomaly detection. My data consists of three columns, the date, an agent (this is where the different levels come from), and the number of schedules that agent had on a particular day. I can run the anomaly detection just fine when I remove the 'agent' column and sum the number of consults by day using this code:</p>
  
  <pre><code>df &lt;- scheds %&gt;%
    group_by(date) %&gt;%
    summarise(
      new_scheds = sum(new_scheds)
    )
  df_ts &lt;- df %&gt;% rownames_to_column() %&gt;% as_tibble() %&gt;% 
    mutate(date = as.Date(date, format = "%m/%d/%Y")) %&gt;% select(-one_of('rowname'))
  
  df_ts &lt;- df_ts[order(df_ts$date),]
  ########## TS Decomp ###############
     df_ts %&gt;% 
    time_decompose(new_scheds, method = "stl", frequency = 5, trend = "auto") %&gt;%
    anomalize(remainder, method = "gesd", alpha = 0.05, max_anoms = 0.2) %&gt;%
    plot_anomaly_decomposition()
  </code></pre>
  
  <p>But I cannot find out how I would do this same type of thing for each agent individually without manually typing everything out and using filter(). I have tried the following loop with no luck:</p>
  
  <pre><code>agents &lt;- levels(ts_agents$agent)
  results &lt;- matrix(NA, length(agents))
  
  for(i in 1:length(agents)){
    ts_agents %&gt;% 
      time_decompose(new_scheds)[i] %&gt;%
      anomalize(remainder)[i] %&gt;%
      time_recompose()[i] %&gt;%
      plot_anomalies(time_recomposed = TRUE, ncol = 3, alpha_dots = 0.5)[i] }
  </code></pre>
  
  <p>but I get the following error:
  'Error in time_decompose(new_scheds) : object 'new_scheds' not found'
  Any tips or pointers would be greatly appreciated!</p>