Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code># start with the mtcars data frame (included with your installation of R) mtcars # pick your 'group by' variable gbv &lt;- 'cyl' # IMPORTANT NOTE: you can only include one group by variable here # ..if you need more, the `order` function below will need # one per inputted parameter: order( x$cyl , x$am ) # choose whether you want to find the minimum or maximum find.maximum &lt;- FALSE # create a simple data frame with only two columns x &lt;- mtcars # order it based on x &lt;- x[ order( x[ , gbv ] , decreasing = find.maximum ) , ] # figure out the ranks of each miles-per-gallon, within cyl columns if ( find.maximum ){ # note the negative sign (which changes the order of mpg) # *and* the `rev` function, which flips the order of the `tapply` result x$ranks &lt;- unlist( rev( tapply( -x$mpg , x[ , gbv ] , rank ) ) ) } else { x$ranks &lt;- unlist( tapply( x$mpg , x[ , gbv ] , rank ) ) } # now just subset it based on the rank column result &lt;- x[ x$ranks &lt;= 3 , ] # look at your results result # done! # but note only *two* values where cyl == 4 were kept, # because there was a tie for third smallest, and the `rank` function gave both '3.5' x[ x$ranks == 3.5 , ] # ..if you instead wanted to keep all ties, you could change the # tie-breaking behavior of the `rank` function. # using the `min` *includes* all ties. using `max` would *exclude* all ties if ( find.maximum ){ # note the negative sign (which changes the order of mpg) # *and* the `rev` function, which flips the order of the `tapply` result x$ranks &lt;- unlist( rev( tapply( -x$mpg , x[ , gbv ] , rank , ties.method = 'min' ) ) ) } else { x$ranks &lt;- unlist( tapply( x$mpg , x[ , gbv ] , rank , ties.method = 'min' ) ) } # and there are even more options.. # see ?rank for more methods # now just subset it based on the rank column result &lt;- x[ x$ranks &lt;= 3 , ] # look at your results result # and notice *both* cyl == 4 and ranks == 3 were included in your results # because of the tie-breaking behavior chosen. </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload