title: R- How can I update column values only pertaining to rows where column contains beginning of a certain number?
body: <p>I have a dataset that looks as follows:</p>
  <pre><code>ex &lt;- data.frame(&quot;id&quot; =c(rep(1234,6)),
                   &quot;case&quot; = c(45,45,45,92,92,93),
                            &quot;cpt&quot; = c(20600,25263,8456,2345,9023,&quot;C1245&quot;),
                           &quot;date&quot;=c(&quot;2019-05-21&quot;, &quot;2019-08-22&quot;,&quot;2019-04-12&quot;,
                                    &quot;2019-03-01&quot;, &quot;2019-02-18&quot;, &quot;2019-03-12&quot;),
                           &quot;window&quot;=c(10,20,NA,45,NA,NA),
                           &quot;pay&quot;=c(520,140,2200,230,600,700))
  </code></pre>
  <p>I essentially have two questions:
  How can I update the cpt column with the cpt value corresponding to the row with the highest <em>pay</em> grouped by case <strong>only</strong> focusing on any row containing a cpt value beginning with number 2 AND following this, how I can update the window column to replace any value that isn't the maximum with NA (also only focusing on rows where cpt value starts with 2)</p>
  <p>I would like the final output to look like so:</p>
  <pre><code>ex1 &lt;- data.frame(&quot;id&quot; =c(rep(1234,6)),
                   &quot;case&quot; = c(45,45,45,92,92,93),
                   &quot;cpt&quot; = c(20600,20600,20600,2345,2345,&quot;C1245&quot;),
                   &quot;date&quot;=c(&quot;2019-05-21&quot;, &quot;2019-08-22&quot;,&quot;2019-04-12&quot;,
                            &quot;2019-03-01&quot;, &quot;2019-02-18&quot;, &quot;2019-03-12&quot;),
                   &quot;window&quot;=c(10,NA,NA,45,NA,NA),
                   &quot;pay&quot;=c(520,140,2200,230,600,700))
  </code></pre>
  <p>I have two codes</p>
  <pre><code>ex[, cpt:=cpt[which.max(pay)], by=case]
  
  ex %&gt;% group_by(case) %&gt;% mutate(window=replace(window, (pay &lt; max(pay)), NA)) %&gt;%
    setDT()
  </code></pre>
  <p>but both of these codes apply to the overall max value and will produce</p>
  <pre><code>ex2 &lt;- data.frame(&quot;id&quot; =c(rep(1234,6)),
                    &quot;case&quot; = c(45,45,45,92,92,93),
                    &quot;cpt&quot; = c(8456,8456,8456,9023,9023,&quot;C1245&quot;),
                    &quot;date&quot;=c(&quot;2019-05-21&quot;, &quot;2019-08-22&quot;,&quot;2019-04-12&quot;,
                             &quot;2019-03-01&quot;, &quot;2019-02-18&quot;, &quot;2019-03-12&quot;),
                    &quot;window&quot;=c(NA,NA,NA,NA,NA,NA),
                    &quot;pay&quot;=c(520,140,2200,230,600,700))
  </code></pre>
  <p>Is there any way I could alter the codes I have to get the output I'm looking for? Or any other code that might be more efficient? Thanks in advance!</p>