retrieve a string from grep function in R

Viewed 57

I'm searching in some sentences some words using this code

sent <- c()
 for (w in my_words){
    my_selected_sentences <- grep(paste0('\\b', w, '\\b'), my_sentences, ignore.case = TRUE, value = TRUE, perl = TRUE)
    sent <- c(sent, my_selected_sentences)
  }

Now I'd like to add in the vector "sent" word or words that have been retrieved. For example

[1] here is the selected sentence.---"the", "sentence"

How I can do? thanks!

1 Answers

You can do something like this (used an artificial example):

my_sentences <- c('hi there','will you do it', 'i will go home', 'salt is good for health')
my_sentences_df <- data.frame(sentences = my_sentences, words_retrieved = "", stringsAsFactors = FALSE)
my_words <- c('will','salt','home')
sent <- c()
for (w in my_words){
  my_selected_sentences <- grep(paste0('\\b', w, '\\b'), my_sentences, ignore.case = TRUE, value = TRUE, perl = TRUE)
  my_sentences_df[grep(w, my_sentences_df$sentences),"words_retrieved"] <- 
    paste(my_sentences_df[grep(w, my_sentences_df$sentences),"words_retrieved"], w, sep = ", ")
  sent <- c(sent, my_selected_sentences)
}
my_sentences_df$words_retrieved <- sub('.', '', my_sentences_df$words_retrieved)
writeLines(with(my_sentences_df, paste0(my_sentences, " ---", words_retrieved)))
Related