1

我是 R 新手,一直在努力解决这个问题。我想创建一个新列,检查“text”列中是否存在一组单词(“foo”、“x”、“y”),然后将该值写入新列。

我有一个看起来像这样的数据框: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 崩溃?

4

1 回答 1

2

This is a variation on what you have done, and what was suggested in the comments. This uses dplyr and stringr. There may be a more efficient way but this may not crash your R session.

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
于 2016-01-23T07:42:28.147 回答