I am looking to learn R, and after a few google searches was able to create following code to find multiply occurrence of key words in a text file.
I have the following code to find multiply occurrences of key word expansion
url <- "http://www.textfiles.com/science/blackhol.txt"
file <- download.file(url = url, destfile ="blackhole.txt")
textfile <- "~/blackhole.txt"
text <-readLines(textfile)
library(qdap)
d <- sent_detect(text)
# grep the sentence with the keyword:
n <- which(grepl('[Ee]pansion', d) == T)
# Obtaining 2 sentences before keyword and 2 sentences after keyword:
d[(n - 2):(n + 2)]
However, this does not work as I obtain an error:
Error in (n - 2):(n + 2) : argument of length 0
How do I resolve this issue, and thereafter use following code below to provide output for all multiply occurrences of keyword expansion:
lapply(which(grepl('expansion', d) == T), function(n){cat(d[(n - 1):(n + 1)])
})
Thank you for your help.