title: Using grep to substitute values from one data frame to another in R
body: <p>I have a data frame that looks like this (df1):</p>
  
  <pre><code>options(stringsAsFactors = F)
  
  Car &lt;- c('Chevrolet', 'GM', 'Lexus', 'Ford', 'Mitsubishi', 'Audi')
  Alternative.Cars &lt;- c('Acura, Honda', NA, 'Nissan', 'Ferrari, Toyota, Tesla', 'Infiniti', 'Cadillac, Benz')
  contact &lt;- c('Mickey', 'Minnie', 'Daffy', 'Pluto', 'Donald', 'Goofy')
  numCars &lt;- c(0,0,0,0,0,0)
  df1 &lt;- data.frame(Car = Car, Alternative.Cars = Alternative.Cars, contact = contact, numCars = numCars)
  </code></pre>
  
  <p>and a second data frame that looks like this (df2):</p>
  
  <pre><code>CAR &lt;- c('Acura', 'Benz', 'Toyota', 'Nissan')
  years &lt;- c('Y2001,Y2003','Y2014', 'Y1999,Y2015,Y2016', 'Y2013')
  df2 &lt;- data.frame(CAR = CAR, years = years)
  </code></pre>
  
  <p>DF1 is a short list of car inventory that are currently out of stock.  DF2, is a list of cars with year and make.  You'll notice that DF2 has Car names that are listed only in the DF1$Alternative.Cars column.  For some reason, there was a huge mix up and it needs to be set straight.  I want to create a new column called 'Real.Car' that finds the car name from DF1$CAR within DF2$Alternative.Cars, so it looks like the data frame below (DF3):</p>
  
  <pre><code>Car         Alternative.Cars         Real.Car   contact  numCars years
  Chevrolet   Acura, Honda             Acura      Mickey      0    Y2001,Y2003  
  GM          &lt;NA&gt;                     &lt;NA&gt;       Minnie      0    &lt;NA&gt;
  Lexus       Nissan                   Nissan     Daffy       0    Y2013
  Ford        Ferrari, Toyota, Tesla   Toyota     Pluto       0   Y1999,Y2015,Y2016  
  Mitsubishi  Infiniti                 &lt;NA&gt;       Donald      0    &lt;NA&gt;
  Audi        Cadillac, Benz           Benz       Goofy       0    Y2014
  </code></pre>
  
  <p>I've tried looking across each row in df2 and finding the match in df1.  If there is a match, I want to save the years in a new column called 'years' but it isn't working out right: </p>
  
  <pre><code> for (i in 1:length(df2$CAR)) {
  
     singleEntry &lt;- as.data.frame(df2[1,])
  
     df1$Car &lt;- ifelse(grep(singleEntry, df1$Alternative.Cars), 
     singleEntry$years, df1$Car)
  
   }
  </code></pre>
  
  <p>Any help would be greatly appreciated! </p>