Replace Value & Shift Data Frame If Certain Condition Met
<p>I've scraped data from a source online to create a data frame (<code>df1</code>) with <code>n</code> rows of information pertaining to individuals. It comes in as a single string, and I split the words apart into appropriate columns. </p>

<p>90% of the information is correctly formatted to the proper number of columns in a data frame (6) - however, once in a while there is a row of data with an extra word that is located in the spot of the 4th word from the start of the string. Those lines now have 7 columns and are off-set from everything else in the data frame. </p>

<p>Here is an example: </p>

<pre><code>Num Last-Name First-Name Cat. DOB Location

11 Jackson, Adam L 1982-06-15 USA
2 Pearl, Sam R 1986-11-04 UK
5 Livingston, Steph LL 1983-12-12 USA
7 Thornton, Mark LR 1982-03-26 USA
10 Silver, John RED LL 1983-09-14 USA


df1 = c(" 11 Jackson, Adam L 1982-06-15 USA",
    "2 Pearl, Sam R 1986-11-04 UK",
    "5 Livingston, Steph LL 1983-12-12 USA",
    "7 Thornton, Mark LR 1982-03-26 USA",
    "10 Silver, John RED LL 1983-09-14 USA")
</code></pre>

<p>You can see item #10 has an extra input added, the color <code>"RED"</code> is inserted into the middle of the string. </p>

<p>I started to run code that used <a href="/questions/tagged/stringr" class="post-tag" title="show questions tagged &#39;stringr&#39;" rel="tag">stringr</a> to evaluate how many characters were present in the 4th word, and if it was 3 or greater (every value that will be in the <code>Cat.</code> column is is 1-2 characters), I created a new column at the end of the data frame, assigned the value to it, and if there was no value (i.e. it evaluates to <code>FALSE</code>), input <code>NA</code>. I'm sure I could likely create a massive nested <code>ifelse</code> statement in a <a href="/questions/tagged/dplyr" class="post-tag" title="show questions tagged &#39;dplyr&#39;" rel="tag">dplyr</a> <code>mutate</code> (my personal comfort zone), but I figure there must be a more efficient way to achieve my desired result: </p>

<pre><code>Num Last-Name First-Name Cat. DOB Location Color

11 Jackson, Adam L 1982-06-15 USA NA
2 Pearl, Sam R 1986-11-04 UK NA
5 Livingston, Steph LL 1983-12-12 USA NA
7 Thornton, Mark LR 1982-03-26 USA NA
10 Silver, John LL 1983-09-14 USA RED
</code></pre>

<p>I want to find the instances where the 4th word from the start of the string is 3 characters or longer, assign that word or value to a new column at the end of the data frame, and shift the corresponding values in the row to the left to properly align with the others rows of data. </p>