I have a long list of strings, that share substrings. The list comes from event stream data, so there are tens of thousands of rows, but I'll simplify for this example; Pets:
+--------------------------------+
| Pets |
+--------------------------------+
| "one calico cat that's smart" |
| "German Shepard dog" |
| "A Chameleon that is a Lizard" |
| "a cute tabby cat" |
| "the fish guppy" |
| "Lizard Gecko" |
| "German Shepard dog" |
| "Budgie Bird" |
| "Canary Bird in a coal mine" |
| "a chihuahua dog" |
+--------------------------------+
dput output: structure(list(Pets = structure(c(8L, 6L, 1L, 3L, 9L, 7L, 6L, 4L, 5L, 2L),.Label = c("A Chameleon that is a Lizard", "a chihuahua dog", "a cute tabby cat", "Budgie Bird", "Canary Bird in a coal mine", "German Shepard dog", "Lizard Gecko", "one calico cat that's smart", "the fish guppy"), class = "factor")), .Names = "Pets", row.names = c(NA, -10L), class = "data.frame")
I want to add information based on the generic type of pet (dog, cat, etc) and I have a key table that holds this information:
+----------+----------------+
| key | classification |
+----------+----------------+
| "dog" | "canine" |
| "cat" | "feline" |
| "lizard" | "reptile" |
| "bird" | "avian" |
| "fish" | "fish" |
+----------+----------------+
dput output: structure(list(key = structure(c(3L, 2L, 5L, 1L, 4L), .Label = c("bird", "cat", "dog", "fish", "lizard"), class = "factor"), classification = structure(c(2L, 3L, 5L, 1L, 4L), .Label = c("avian", "canine", "feline", "fish", "reptile"), class = "factor")), .Names = c("key", "classification"), row.names = c(NA, -5L), class = "data.frame")
How do I use the "long string" from the Pets table to find relevant classification in the key table? The issue is, my lookup string contains the substring that is found in the key table.
I'm started by using grepl like this:
key[grepl(pets[1,1], key[ , 2]), ]
But this won't work because "calico cat" isn't in the key list, though "cat" is. The result I'm looking for would be "feline".
(Note: I can't simply switch things around because, in my own code, this sits within an apply function and loops through each row in the data. so, instead of pets[1,1] it's pets[n,1] In the end I intend to cbind the results onto the event stream data to do further analysis.)
I'm having trouble wrapping my head around how to do this. Any advice?