2016-01-22 48 views
0

我是R的新手,一直在为此而苦苦挣扎。我想创建一个新列,检查列'text'中是否存在任何单词(“foo”,“x”,“y”),然后将该值写入新列。R:提取和粘贴关键字匹配

我有看起来像这样的数据帧:A->

id  text  time username 
1  "hello x"  10  "me" 
2  "foo and y" 5  "you" 
3  "nothing"  15  "everyone" 
4  "x,y,foo"  0  "know" 

正确的输出应为:

A2 - >

id  text  time username  keywordtag 
1  "hello x"  10  "me"   x 
2  "foo and y" 5  "you"   foo,y 
3  "nothing"  15  "everyone" 0 
4  "x,y,foo"  0  "know"  x,y,foo 

我有这样的:

df1 <- data.frame(text = c("hello x", "foo and y", "nothing", "x,y,foo")) 
terms <- c('foo', 'x', 'y') 
df1$keywordtag <- apply(sapply(terms, grepl, df1$text), 1, function(x) paste(terms[x], collapse=',')) 

哪个有效,但当我的needleList包含12k个单词并且我的文本有155k个行时崩溃R.有没有办法做到这一点,不会崩溃R?

+0

看起来效率很低。你为什么不研究已经解决这个问题的软件包。 –

+0

也许在stringr库中试试这样的东西:sapply(df1,function(x)str_extract_all(x,paste(terms,collapse =“|”))) – Wyldsoul

+0

'needleList'是什么? – steveb

回答

1

这是你所做的一切变化,以及评论中提出的内容。这使用dplyrstringr。可能有更有效的方法,但这可能不会导致您的R会话崩溃。

library(dplyr) 
library(stringr) 

terms  <- c('foo', 'x', 'y') 
term_regex <- paste0('(', paste(terms, collapse = '|'), ')') 

### Solution: this uses dplyr::mutate and stringr::str_extract_all 
df1 %>% 
    mutate(keywordtag = sapply(str_extract_all(text, term_regex), function(x) paste(x, collapse=','))) 
#  text keywordtag 
#1 hello x   x 
#2 foo and y  foo,y 
#3 nothing   
#4 x,y,foo x,y,foo 
+0

你知道为什么dplyr和stringr在处理这些类型的任务时不会崩溃R会更好吗? – lmcshane

+0

@ lmcshane我不知道。目前还不清楚崩溃问题的普遍程度(即您的环境中是否存在其他问题)。 – steveb