I want to find the Nth occurence of a word in an utterance and put [brackets] around it. I tried with various things but I think the closest I'm getting is with gsub but I can't have {copy-1} for the number of times in my regex. Any ideas? Can we put a variable in there? Thanks!
#creating my df
utterance <- c("we are not who we think we are", "they know who we are")
df <- data.frame(utterance)
df$occurences = str_count(df$utterance, "we")
df <- df %>% mutate(ID = row_number())
df <- df %>% uncount(occurences) %>% group_by(ID) %>% mutate(copy = row_number())
#this is my gsub
gsub("((?:we){copy-1}.*)we", "\\[we\\]", df$utterance)
This would be my result
utterance ID copy
<chr> <int> <int>
1 [we] are not who we think we are 1 1
2 we are not who [we] think we are 1 2
3 we are not who we think [we] are 1 3
4 they know who [we] are 2 1