title: Difficulty Cleaning a Data Frame Using Regexp in R
body: <p>I am relatively new to R and having difficulty cleaning up a data frame using regex. </p>
  
  <p>One of the columns of that data frame has strings such as: </p>
  
  <pre><code>  NUMERO_APPEL
  1          NNA
  2     VQ-40989
  3        41993
  4        41993
  5        42597
  6     VQ-42597
  7         DER8
  8   40001-2010
  </code></pre>
  
  <p>I would like to extract the 5 consecutive digits of the strings that have the following format <strong><em>and only the following format, all other strings will be replaced by NAs</em></strong>.</p>
  
  <pre><code>AO-11111
  VQ-11111
  11111
  </code></pre>
  
  <p>** Even if Case 8 contains 5 consecutive numbers, it will be replaced by NA as well... Furthermore, a more than or less than 5 digits long number would also be replaced by NA.</p>
  
  <blockquote>
    <p>Note that the 5 consecutive digits could be any number [0-9], but the characters 'AO-' and 'VQ-' are fixed (i.e. 'AO ' or 'VE-' would be replaced to NA as well.) </p>
  </blockquote>
  
  <p>This is the code that I currently have:</p>
  
  <pre><code># Declare a Function that Extracts the 1st 'n' Characters Starting from the Right!
   RightSubstring &lt;- function(String, n) {
       substr(String, nchar(String)-n+1, nchar(String))
   }
  
  # Declare Function to Remove NAs in Specific Columns!
  ColRemNAs &lt;- function(DataFrame, Column) {
      CompleteVector &lt;- complete.cases(DataFrame, Column)
      return(DataFrame[CompleteVector, ])
  
      Contrat$NUMERO_APPEL &lt;- RightSubstring(as.character(Contrat$NUMERO_APPEL), 5)
      Contrat$NUMERO_APPEL &lt;- gsub("[^0-9]", NA, Contrat$NUMERO_APPEL)
      Contrat$NUMERO_APPEL &lt;- as.numeric(Contrat$NUMERO_APPEL)
  
      # Efface les Lignes avec des éléments NAs.
      Contrat &lt;- ColRemNAs(Contrat, Contrat$NUMERO_COMMANDE)
      Contrat &lt;- ColRemNAs(Contrat, Contrat$NO_FOURNISSEUR)
      Contrat &lt;- ColRemNAs(Contrat, Contrat$NUMERO_APPEL)
      Contrat &lt;- ColRemNAs(Contrat, Contrat$MONTANT_INITIAL)
      Contrat &lt;- ColRemNAs(Contrat, Contrat$MONTANT_ACTUEL)
  }
  </code></pre>
  
  <p>Thanks in advance. Hope my explanations were clear!</p>