title: How do I create a new column that that contains part of a string based on a pattern in R
body: <p>Apologies if this has been solved before, I haven't been able to find a solution to this problem. I am trying to pull out the letter &quot;N&quot; out of a sting including the -1 and +1 position and report it in a new column, there may be more than one instance of N in the string and i would like it to report all of them. I can filter the peptides containing N using
  <code>dt_contains_N &lt;-dt[str_detect(dt$Peptide, &quot;N&quot;),]</code>
  but I'm not sure how to extract it, I was thinking something like ,
  <code>dt_N_motif &lt;- dt[substring(dt$Peptide, regexpr(&quot;N&quot;, dt$Peptide) + 1)]</code>
  but im not sure how to include the N-position column information to extract the N-1, N and N+1 positions.
  For example a simplified view of my data table looks like:
  <code>dt &lt;- data.frame(Peptide= c(&quot;GESNEL&quot;, &quot;SADNNEW&quot;, &quot;SADNNEW&quot;), N_pos=c(4,4,5))</code>
  .
  .</p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>peptide</th>
  <th>N pos</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>GESNEL</td>
  <td>4</td>
  </tr>
  <tr>
  <td>SADNNEW</td>
  <td>4</td>
  </tr>
  <tr>
  <td>SADNNEW</td>
  <td>5</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p>and I would like it to look like this:</p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>peptide</th>
  <th>N pos</th>
  <th>Motif</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>GESNEL</td>
  <td>4</td>
  <td>SNE</td>
  </tr>
  <tr>
  <td>SADNNEW</td>
  <td>4</td>
  <td>DNN</td>
  </tr>
  <tr>
  <td>SADNNEW</td>
  <td>5</td>
  <td>NNE</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p>Any help would be great,</p>
  <p>Thanks!</p>