Question: I have two different data.frames "String" and "Keywords" with single columns as mentioned below. "String" has 50000 rows and "Keywords", 10000 rows. 

```
String
#I love New York  
#Live in Los Angeles  
#He stays in Yorkshire  
#Condo in Lowell  
# ...

Keywords 
#Ohio  
#Montreal  
#Los Vego  
#York  
#New York   
#Lowell    
#... 

```

The result should be stored in a dataframe with columns "String" and "Result" which looks as shown below 

```
Result  

#              String        Result  
#       I love New York    New York     
#   Live in Los Angeles          NA  
# He stays in Yorkshire        York  
#       Condo in Lowell      Lowell  

```

The string matching should be exact but can be case insensitive.

Answer: 
I do not think this is the most ideal solution, but it does work:

```
stringFrame <- data.frame(String = c("I love New York","Live in Los Angeles","He stays in Yorkshire","Condo in Lowell"),
                      stringsAsFactors = FALSE) 
 wordFrame   <- data.frame(Keywords = c("Ohio","Montreal","Los Vego","York","New York","Lowell"),
                      stringsAsFactors = FALSE)

 result <- stringFrame
 for (i in 1:dim(result)[1]){
  string = result[i,"String"]
  temp = ""
  for (word in wordFrame$Keywords){
    if (grepl(word,string,ignore.case=TRUE)){
      if (nchar(word) > nchar(temp)){
        result[i,"Result"] <- word
        temp <- word
      }
    }
  }
}

```

I saw in the title that you were looking for the longest word, so I updated the answer. Now you will always get

```
 String               Result
 I love New York    New York

```
You can use the `stringdist` package, which implements the longest common substring method. The `amatch` function can be used to match 'words' to your strings:

```
strings <- data.frame(string=c("I love New York","Live in Los Angeles",
  "He stays in Yorkshire","Condo in Lowell"), stringsAsFactors = FALSE)
words   <-c("Ohio","Montreal","Los Vego","York",
  "New York","Lowell")

library(stringdist) 

strings$result = words[amatch(strings$string, words, method="lcs", maxDist=1E6)]

```

AS @NickK commented this matches `Lives in Los Angeles` to `Los Vego`. In order to filter these partial matches out you can do

```
# filter out partial matches
match <- nchar(strings$string) - nchar(strings$result)  ==
  stringdist(strings$result, strings$string, method="lcs")
strings$result[!match] <- NA

```

This solution seems to be slightly slower than that of @NickK. Using his example data set, the solution above takes 486 seconds on my system, while his takes 416 seconds.