title: aggregate data by means of every N row
body: <p>I want to aggregate the data of a column (each row represents a second) by getting the mean of every 60 row (mean value for every minute). The rows (Seconds per Measurement) differ between the subjects and dates.</p>
  <p><a href="https://i.stack.imgur.com/Ec4Cw.png" rel="nofollow noreferrer">This is how my data structure looks like (100 subjects multiple dates)</a></p>
  <p>I tried already the meanEveryN function but I guess the problem is, if the number of rows is not exactly dividable by 60 the function either centers, leftens or rightens the column when creating the means, which in turn results in &quot;wrong&quot; mean values. I checked that by getting the mean of my first 60 rows and compared it with the outcome of the meanEveryN function.</p>
  <p>I tried a work around to solve my &quot;problem&quot; by grouping my data by ID and date and creating a column &quot;min&quot; which gives every row a value representing the minute each row belongs to (defined by timestamp column &quot;TS_0&quot;).</p>
  <pre><code>df_min &lt;- data %&gt;% 
    group_by(date, ID) %&gt;% 
    mutate(min = ifelse(TS_0 &lt; 61, &quot;1&quot;,
                        ifelse(TS_0 &gt; 60 &amp; TS_0 &lt; 121, &quot;2&quot;,
                               ifelse(TS_0 &gt; 120 &amp; TS_0 &lt; 181, &quot;3&quot;, 
                                      ifelse(TS_0 &gt; 180 &amp; TS_0 &lt; 241, &quot;4&quot;,
                                             ifelse(TS_0 &gt; 240 &amp; TS_0 &lt; 301, &quot;5&quot;, &quot;0&quot;..............
  ))))))%&gt;% ungroup()
  
  </code></pre>
  <p>Grouping now by the new variable &quot;min&quot; gives me the correct means (if I wouldn't have such a long data frame).</p>
  <pre><code>df_min%&gt;%
    group_by(ID, date, min)%&gt;%
    summarise(mean = mean(MA, na.rm = TRUE))
  </code></pre>
  <p>My problem now is the length of my code above (ifelse function). Since I have subjects with more than 4500 rows I have around hundred nested ifelse, which creates an error. I think R is simply not able to nest more than 50. Does anyone has a more elegant way to aggregate my data? I know that my code as well as the way I am asking my question seems complicated. I am still a total noob and tried my best to make it as clear as possible.</p>