1

我有一个大数据表,每行都有几行文本。我试图通过查找包含几个单词之一的行来对 data.table 进行子集化。这是我尝试过的。

textDt <- data.table(LinesOfText = c("There was a small frog.","Most of the 
time I ate chicken","There are so many places to stay here.","People on 
stackoverflow are tremendously helpful.","Why do grapefuits cause weird drug 
interactions?","If I were tiny I could fit in there"))

targetWords <- c("small","tiny","no room","cramped","mini")

targetDt <- textDt[targetWords %in% LinesOfText]

这总是会导致错误。我知道一定有一个简单的解决方案让我无法理解。

4

1 回答 1

1

我喜欢使用stringr,因为我相信它更快。所以这是一个基于此的解决方案:

library(stringr)
targetWords<- paste(targetWords, collapse = "|")
# "small|tiny|no room|cramped|mini"

targetDT<- textDt[str_detect(LinesOfText , targetWords)]
targetDT
#                           LinesOfText 
#1: If I were tiny I could fit in there
#2:             There was a small frog.
于 2018-05-10T19:45:03.100 回答