title: Replacing a value with user defined function in grouped data
body: <p>I come to an issue that replacing a value with another if the condition is met. I use my own function <code>data_manip</code> that I can assign or add any other condition when needed.</p>
  
  <p>However, when I try to use this <code>data_manip</code> function it changes all the values within that group with the assigned value. But the other values in that particular group do not met with this condition. </p>
  
  <p>Here is what I tried,</p>
  
  <pre><code>df &lt;- data.frame(percent = c(0.6, 0.7,1, 0.5,0.5,1,0.4,0.6,1), 
                   type = rep(c("good", "bad","ugly"),each=3), smoke=rep(c('Visky','Wine','Wine'),3),
                   sex=rep(c('male','male','female'),3))
  
  &gt; df
    percent type smoke    sex
  1     0.6 good Visky   male
  2     0.7 good  Wine   male
  3     1.0 good  Wine female
  4     0.5  bad Visky   male
  5     0.5  bad  Wine   male
  6     1.0  bad  Wine female
  7     0.4 ugly Visky   male
  8     0.6 ugly  Wine   male
  9     1.0 ugly  Wine female
  
  
  data_manip &lt;- function(x,gr){
    if(grepl('goo|ug',gr)&amp;&amp;x&lt;1){
      x[x==0.6] &lt;- 1
    }
      else
    x
  }
  
  df%&gt;%
    group_by(type)%&gt;%
    mutate(percent_new=data_manip(percent,type))
  </code></pre>
  
  <p>gives</p>
  
  <pre><code># A tibble: 9 x 5
  # Groups:   type [3]
    percent   type  smoke    sex percent_new
      &lt;dbl&gt; &lt;fctr&gt; &lt;fctr&gt; &lt;fctr&gt;       &lt;dbl&gt;
  1     0.6   good  Visky   male         1.0
  2     0.7   good   Wine   male         1.0
  3     1.0   good   Wine female         1.0
  4     0.5    bad  Visky   male         0.5
  5     0.5    bad   Wine   male         0.5
  6     1.0    bad   Wine female         1.0
  7     0.4   ugly  Visky   male         1.0
  8     0.6   ugly   Wine   male         1.0
  9     1.0   ugly   Wine female         1.0
  </code></pre>
  
  <p>I would like to keep original <code>percent</code> values if the condition is not for them. </p>
  
  <p>Expected output</p>
  
  <pre><code> # A tibble: 9 x 5
      # Groups:   type [3]
        percent   type  smoke    sex percent_new
          &lt;dbl&gt; &lt;fctr&gt; &lt;fctr&gt; &lt;fctr&gt;       &lt;dbl&gt;
      1     0.6   good  Visky   male         1.0
      2     0.7   good   Wine   male         0.7
      3     1.0   good   Wine female         1.0
      4     0.5    bad  Visky   male         0.5
      5     0.5    bad   Wine   male         0.5
      6     1.0    bad   Wine female         1.0
      7     0.4   ugly  Visky   male         0.4
      8     0.6   ugly   Wine   male         1.0
      9     1.0   ugly   Wine female         1.0
  </code></pre>