R

时间:2017-03-02 12:57:15

标签: r

我希望学习R,并且在一些谷歌搜索之后能够创建以下代码以找到text file中关键词的多次出现。

我有以下代码来查找关键字扩展

的多次出现
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)]

然而,这不起作用,因为我得到一个错误:

Error in (n - 2):(n + 2) : argument of length 0

如何解决此问题,然后使用以下代码为关键字扩展的所有多次出现提供输出:

lapply(which(grepl('expansion', d) == T), function(n){cat(d[(n - 1):(n + 1)])
})

感谢您的帮助。

0 个答案:

没有答案