【发布时间】:2018-10-20 03:23:35
【问题描述】:
我有一组句子,
{ cat ate rat, rat was killed, cat killed the rat, rat killed by rat}。
首先)我想搜索列 col2 中的值是否包含这些句子中的任何一个
Second ) 如果匹配,那么我想检查 Col3 中的日期是否在 col4 和 col5 中的开始日期和结束日期之间。
这是一个测试数据集
Id Col2 Col3 Col4 Col5
1 This cat 05-09-2001 04-10-2000 09-14-2001
2 This cat ate a rat 05-04-2011 05-01-2011 05-14-2011
3 Cat was killed 02-04-2015 02-01-2015 03-12-2015
4 Cat killed the rat 10-06-2014 09-20-2014 10-11-2014
5 Rat ran away 03-12-2008 04-12-2015 04-20-2015
这是预期的输出
Id Col2 Col3 Col4 Col5 Event
1 This cat 05-09-2001 04-10-2000 09-14-2001 No
2 Cat ate rat 05-04-2011 05-01-2011 05-14-2011 Yes
3 Cat died 02-04-2015 02-01-2015 03-12-2015 No
4 Cat killed the rat 10-06-2014 09-20-2014 10-11-2014 Yes
5 Rat ran away 03-12-2008 04-12-2015 04-20-2015 No
这就是 id 到目前为止所做的。下面的代码正在运行。我得到了我想要的结果,但这非常低效。它非常慢并且需要很长时间。特别是如果我的 df 包含 300 万行,我需要 10 天才能完成运行此代码。非常感谢任何有关解决此问题的有效方法的建议。
keywords
for (i in 1:NROW(Df)) {
if( NROW(Df[grep(paste0(keywords, collapse = "|"), Df$Col2[i]),]) > 0) {
if ( (Df$Col3[i] > Df$Col4[i]) & (Df$Col3[i] < Df$Col5[i]) ){
Df$Event <- "Yes"
} else {
Df$Event <- "No"
}
}
print(i)
}
【问题讨论】:
-
请使用
dput()(见R标签说明) -
另外我要补充一点,测试数据集和预期的输出不匹配。为什么 Col2 发生了变化?
标签: r string date filter text-mining