title: Aggregate conditional statements
body: <p>I'm trying to find an elegant solution to a problem without complex subsetting and/or line by line iteration. I will explain via example:</p>
  
  <pre><code># Load data
  df1 &lt;- mtcars
  
  # Can aggregate with simple math functions i.e. mean or sum
  hp_by_cyl &lt;- aggregate(hp ~ cyl, data=df1, mean)
  &gt; hp_by_cyl
    cyl        hp
  1   4  82.63636
  2   6 122.28571
  3   8 209.21429
  </code></pre>
  
  <p>Ok. But, in my real much more complex data I wish to aggregate a logical value - i.e. if x is true for any row belonging to category A then y =1. So to extend my example I can create a column with logical variable:</p>
  
  <pre><code>df1$logic &lt;- ifelse(df1$gear==4 &amp; df1$hp &lt; 150, 1, 0)
  # How do I aggregate the logical values levels of cyl to answer yes/no
  # if any car with x cylinders has 4 gears and &lt; 150 hp ?
  # So I want an finished table like this:
  cyl     logic
  4       1
  6       1
  8       0
  </code></pre>
  
  <p><strong>So my question is how to use the aggregate (or alternate) command to produce a table like this ?</strong> i.e. to combine the logical status, not the numeric value ?</p>
  
  <p>I also need to deal with encoded missing values also in reality so to emulate that complexity I will make one of the logic's 99:</p>
  
  <pre><code>df1[5, ]$logic &lt;- 99
  </code></pre>
  
  <p>If for a given level of <code>cyl</code> one value is 1, the 99 can be ignored - if however all others are 0 then the aggregate should be 99.</p>
  
  <p>Apologies if there is a simple answer I don't see in my real data it seems daunting. I could hack out a nasty solution but I know it will be very slow and I have a 14000 X 140 size dataset. Thanks in advance all.</p>