title: Replace a data frame column based on regex
body: <p>I am trying to extract part of a column in a data frame using regular expressions. Problems I am running into include the facts that <code>grep</code> returns the whole value, not just the matched part, and that <code>str_extract</code> doesn't seem to work in a vectorized way.</p>
  
  <p>Here is what I'm trying. I would like <code>df$match</code> to show <code>alpha.alpha.</code> where the pattern exists and <code>NA</code> otherwise. How can I show only the matched part?</p>
  
  <p>Also, how I can I replace <code>[a-zA-Z]</code> in R regex? Can I use a character class or a POSIX code like <code>[:alpha:]</code>?</p>
  
  <pre><code>v1 &lt;- c(1:4)
  v2 &lt;- c("_a.b._", NA, "_C.D._", "_ef_")
  df &lt;- data.frame(v1, v2, stringsAsFactors = FALSE)
  
  df$match &lt;- grepl("[a-zA-Z]\\.[a-zA-Z]\\.", df$v2)
  df$match
  
  #TRUE FALSE  TRUE FALSE
  
  v2grep &lt;- grep("[a-zA-Z]\\.[a-zA-Z]\\.", df$v2, value = TRUE)
  
  df$match[df$match == TRUE] &lt;- v2grep
  df$match[df$match == FALSE] &lt;- NA
  
  df
  
  #v1  v2      match
  #1   _a.b._  _a.b._
  #2   &lt;NA&gt;    &lt;NA&gt;
  #3   _C.D._  _C.D._
  #4   _ef_    &lt;NA&gt;
  </code></pre>
  
  <p>What I want:</p>
  
  <pre><code>#v1  v2      match
  #1   _a.b._  a.b.
  #2   &lt;NA&gt;    &lt;NA&gt;
  #3   _C.D._  C.D.
  #4   _ef_    &lt;NA&gt;
  </code></pre>