title: How to avoid "operations are possible only for numeric, logical or complex types" when computing top 3 elements in each group
body: <p>I've got a matrix (AOD_median) that contains 4 column. I want to find the 3 largest data elements (by AOD) for each year and determine the month related to these elements. This is my data: </p>
  
  <pre><code>date      month year     AOD
  1-Mar-00    3   2000    0.226
  1-Apr-00    4   2000    0.454
  1-May-00    5   2000    0.328
  1-Jun-00    6   2000    0.314
  1-Jul-00    7   2000    0.354
  1-Aug-00    8   2000    0.282
  1-Sep-00    9   2000    0.278
  1-Oct-00    10  2000    0.183
  1-Nov-00    11  2000    0.173
  1-Dec-00    12  2000    0.21
  1-Jan-01    1   2001    0.171
  1-Feb-01    2   2001    0.281
  1-Mar-01    3   2001    0.241
  1-Apr-01    4   2001    0.269
  1-May-01    5   2001    0.292
  1-Jun-01    6   2001    0.222
  1-Jul-01    7   2001    0.322
  1-Aug-01    8   2001    0.268
  1-Sep-01    9   2001    0.276
  1-Oct-01    10  2001    0.169
  1-Nov-01    11  2001    0.16
  1-Dec-01    12  2001    0.15
  </code></pre>
  
  <p>and this is the <code>dput</code> text:</p>
  
  <pre><code>structure(list(X1 = c("1-Mar-00", "1-Apr-00", "1-May-00", "1-Jun-00", 
  "1-Jul-00", "1-Aug-00", "1-Sep-00", "1-Oct-00", "1-Nov-00", "1-Dec-00", 
  "1-Jan-01", "1-Feb-01", "1-Mar-01", "1-Apr-01", "1-May-01", "1-Jun-01", 
  "1-Jul-01", "1-Aug-01", "1-Sep-01", "1-Oct-01", "1-Nov-01", "1-Dec-01"
  ), X2 = c(3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 
  7, 8, 9, 10, 11, 12), X3 = c(2000, 2000, 2000, 2000, 2000, 2000, 
  2000, 2000, 2000, 2000, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 
  2001, 2001, 2001, 2001, 2001), X4 = c(0.226, 0.454, 0.328, 0.314, 
  0.354, 0.282, 0.278, 0.183, 0.173, 0.21, 0.171, 0.281, 0.241, 
  0.269, 0.292, 0.222, 0.322, 0.268, 0.276, 0.169, 0.16, 0.15)), class = c("tbl_df", 
  "tbl", "data.frame"), row.names = c(NA, -22L))
  </code></pre>
  
  <p>I tried doing this operation with the following code:</p>
  
  <pre><code>for(i in 2000:2001) {(d &lt;- as.matrix(AOD_median[which(AOD_median[,3]==i),]))&amp;
                       (order_AOD &lt;- d[order(d[,4], decreasing = TRUE)])&amp;
                        print(order_AOD[1:3,2])}
  </code></pre>
  
  <p>I expected to get a result like this:</p>
  
  <pre><code>"4" "7" "5" 
  "7" "2" "9"
  </code></pre>
  
  <p>Instead, I got this error:</p>
  
  <pre><code>Error in (d &lt;- as.matrix(AOD_median[which(AOD_median[, 3] == i), ])) &amp;  : 
    operations are possible only for numeric, logical or complex types
  </code></pre>