如何使用r中的字符串向量对data.table进行子集化

时间:2018-05-10 19:16:23

标签: r string data.table

我有一个大的data.table,每行有文本行。我试图通过查找包含多个单词之一的行来对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]

这总是会导致错误。我知道必须有一个简单的解决方案让我望而却步。

1 个答案:

答案 0 :(得分: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.