title: Fuzzy mapping in R
body: <p>I am trying to use agrep command for fuzzy matching. I have a data frame in which one column contains the audience response and another dataframe in which segment and subsegment are listed. the column audience response contains the words that are the name of the subsegment. For example:</p>
  
  <pre><code>pattern$audience
  [1] "(Deleted) Semasio Â» DE: Intent Â» Christmas Shopping"          
  [2] "(Old) AddThis - UK Â» Auto Â» General Â» Auto Enthusiasts"      
  [3] "(Old) AddThis - UK Â» Auto Â» General Â» Auto Intenders"        
  [4] "(Old) AddThis - UK Â» Financial Â» Social Â» Financial Shoppers"
  [5] "(Old) AddThis - UK Â» Food Â» Social"                           
  [6] "(Old) AddThis - UK Â» Health Â» Social Â» Health Influencers" 
  </code></pre>
  
  <p>Similarly I have another data frame called x that conatins the segment and sub-segment</p>
  
  <pre><code>x$segment               x$subsegment
  Shopping                Financial shoppers
  Travel                  Travel Europe
  Shopping                Christmas shopping
  </code></pre>
  
  <p>I want to write a function that does the fuzzy matching between pattern$Audience and x$subsegment and returns the subsegment for each of the audience response in a new column as pattern$subseg</p>
  
  <p>The resulting data set I need should be like this:</p>
  
  <pre><code>pattern$audience    x$segment               x$subsegment                
  [1] "(Deleted) Semasio Â» DE: Intent Â» Christmas C"            Shopping                Christmas shopping              
  [2] "(Old) AddThis - UK Â» Auto Â» General Â» Auto Enthusiasts"                         
  [3] "(Old) AddThis - UK Â» Auto Â» General Â» Auto Intenders"                           
  [4] "(Old) AddThis - UK Â» Financial Â» Social Â» Financial Shoppers"   Shopping                Financial shoppers              
  [5] "(Old) AddThis - UK Â» Food Â» Social"                                              
  [6] "(Old) AddThis - UK Â» Health Â» Social Â» Health Influencers"                  
  </code></pre>
  
  <p>Here's the code that I tried to write but it is not returning me the desired output:</p>
  
  <pre><code>x &lt;- rename(x, c("Segment" = "segment", "Sub Segment" = "subseg"))
  names(x)
  y &lt;- as.data.frame(x$subseg)
  y &lt;- rename(y, c("x$subseg" = "subseg"))
  
  
  n.match &lt;- function(pattern, x, ...) {
    for (i in 1:nrow(pattern)) {
          x &lt;- (agrep(y,pattern$audience[i],
                   ignore.case=TRUE, value = TRUE))
                x &lt;- paste0(x,"")
                pattern$subseg[i] &lt;- x
    }
    head(pattern)
      }
  </code></pre>
  
  <p>Can someone please help me correct my mistake.
  I would really appreciate your answer.
  Many thanks</p>