title: Taking the maximum value from a number of columns based on a subset of rows in another column
body: <p>This is my first question on StackOverflow. I am going to try my best to make it concise and explicit and I apologize if it's not. I am also new to R. I have looked around on StackOverflow for an answer to my question. I've found bits and pieces that could be helpful but I'm not sure at this point which methods would be the best to use or how to put it together to make it all work. </p>
  
  <p>I have a dataset like this, called "per1"   </p>
  
  <pre><code>   Day  Stat1 Stat2 Stat3
      10  2.12  1.84  2.11
      10  2.09  1.87  2.07
      10  2.08  1.92  2.07
      11  1.90  1.85  1.88
      11  1.87  1.85  1.93
      11  1.86  1.87  1.93
  </code></pre>
  
  <p>What I want to do is find the maximum value of the data in each "Stat" column for each Day. In other words, the rows that the maximum will be calculated from in each column are the rows that contain identical values in the Day column. The output would look like:</p>
  
  <pre><code>Day  MaxStat1  MaxStat2  MaxStat3
  10   2.12      1.92      2.11
  11   1.87      1.87      1.93
  </code></pre>
  
  <p>I want to make a loop that defines the number of unique values in the Day column and then uses that to define the rows that the maximum will be calculated from in each column. But I am stuck on how to get the max function to subset rows in each column based on the unique days. What I have so far is crude and I'm not even sure it follows proper R rules (again, new to R)</p>
  
  <pre><code>days &lt;- unique(per1$Day)
  stations &lt;- per1[,1:3]
  l &lt;- length(days)
  for (k in 1:l) {
  curr_day &lt;- subset(per1, per1$Day == days[k]) ##this defines the individual day
  curr_stn &lt;- stations[curr_day,] ##this is supposed to define the number of rows as the number of rows in curr_day
  for(i in 1:stations) {  ##loop over each column
  max[i] &lt;- max(stations[curr_day,curr_stn]) ##take the maximum for each column based on the number of rows for each curr_day
  }
  }
  </code></pre>
  
  <p>And I get</p>
  
  <pre><code>Error in stations[curr_day, ] : subscript out of bounds
  </code></pre>
  
  <p>So I figure this means I haven't defined my arguments properly. If anyone could help me out with the proper formatting for this loop it would be MUCH appreciated! Any other cleaner/faster methods would also be welcome. (I looked into "mapply" but couldn't figure out how to write the function that would define the # of rows of the Stat columns as the nuimber of rows per unique Day)</p>
  
  <p>Thank you for your time. </p>