title: How to apply a function for each level of a factor variable?
body: <p>I have a function like this: </p>
  
  <pre><code>remove_outliers&lt;-function(x){
  qnt&lt;- quantile(x,probs=0.99)
  y&lt;- x
  y[x&gt;qnt]&lt;- NA
  y}
  </code></pre>
  
  <p>The purpose is to remove outliers that are at the top 1% of the data (replace their value with NA). How can I apply this function across levels of a factor variable? </p>
  
  <p>For example, </p>
  
  <p>An original dataset with group A and B:</p>
  
  <pre><code>group share
  A     100
  A     50
  A     30
  A     10
  ...   ...
  B     100
  B     90
  B     80
  B     60
  ...   ...
  </code></pre>
  
  <p>Should end up like this:</p>
  
  <pre><code>group share
  A     NA
  A     50
  A     30
  A     10
  ...   ...
  B     NA
  B     90
  B     80
  B     60
  ...   ...
  </code></pre>
  
  <p>I already tried by, tapply, sapply, but these all change the structure of the dataset output. </p>