1

私はRが初めてで、これに苦労しています。列「テキスト」に単語(「foo」、「x」、「y」)のセットが存在するかどうかを確認する新しい列を作成し、その値を新しい列に書き込みます。

次のようなデータ フレームがあります。

 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

これは、あなたが行ったこと、およびコメントで提案されたことのバリエーションです。これはdplyrとを使用しstringrます。もっと効率的な方法があるかもしれませんが、これは 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
于 2016-01-23T07:42:28.147 に答える