How can I find the first location of specific words in a dataframe cell, and save the output in a new column in the same dataframe?
Ideally I want the first match for each of the words in dictionary.
df <- data.frame(text = c("omg coke is so awsme","i always preferred pepsi", "mozart is so overrated by yeah fanta makes my day, always"))
dict <- c("coke", "pepsi", "fanta")
Location can be N of characters or words preceding the dictionary word.
I've been playing around with the code found here, but I can't make it work.
For example, this code does the job, but only for one word, and for one string (rather than a df and dictionary)
my_string = "omg coke is so awsme"
unlist(gregexpr("coke", my_string))[1]
Desired output:
text location
1 omg coke is so awsme 2
2 i always preferred pepsi 4
3 mozart is so overrated by yeah fanta makes my day, always 7
Like I said, the location can also be string rather than word, if that is easier.