2017-03-19 7 views
1

私はあらかじめ定義された単語/フレーズを持つデータフレームを持っています。同義語を検出してデータフレームに保存します

例:多数の行と一つの列を有し、すべての行のテキストがある DF $項

stock 
revenue 
continuous improvement 

別のデータフレーム(DF2)。私はそれを作るための任意の簡単な方法があります行ごとに用語を検出し、この

row_number, stock, continuous improvement, revenue 
1,1,0,1 
2,1,0,0 
3,0,1,0 

のような出力なものとして持っていたいと思いDFからの用語を用いて、実施例 DF2の$文

I used to study at university and in my free time observe the stock prices. Additionally the revenue of every stock 
Stock market is my first interest 
I always try to continuous improvement 

?次のように

答えて

2

あなたがこれを行うことができます:

# Create some fake data 
words <- c("stock", "revenue", "continuous improvement") 
phrases <- c("blah blah stock and revenue", "yada yada revenue yada", 
      "continuous improvement is an unrealistic goal", 
      "phrase with no match") 

# Apply the 'grepl' function along the list of words, and convert the result to numeric 
df <- data.frame(lapply(words, function(word) {as.numeric(grepl(word, phrases))})) 
# Name the columns the words that were searched 
names(df) <- words 
df 
    stock revenue continuous improvement 
1  1  1      0 
2  0  1      0 
3  0  0      1 
4  0  0      0 

私はここに行番号を持つ別の変数を作成していないが、あなたは常に追加することができ、あなたが​​とそれを必要に応じています。

+0

非常に良い答え。ありがとうございました。あなたのコードの単語のためのちょうど一般的な質問私はdf(1列と61000行)とフレーズのために私は700000周りのすべての行の合計単語と1列と2000行を別のdf2を持っている。このような 'df3 < - data.frame(lapply(df $ words、function(word){as.numeric(grepl(word、df2 $ phrase)}))')データフレームを使うのは正しい方法ですか?私はこのコマンドを使用し、それが実行され、結果を待つが、私は説明したテキストの量で結果を取ることはないと思う。あなたは実行時間のために何を信じますか – Keri

+0

これが必要でしょうか?もっと楽観的なやり方を見つけるべきか? – Keri

+0

こんにちはKeri、ええ構文が正しいように見えますが、それはしばらく時間がかかるかもしれません。また、結果として得られるdata.frameは、2000行×61000列になります。最初のdfの単語が重複していて、それを削除できますか?それは物事をより速くするでしょう。また、各検索が独立しているので、コードを並列化してより高速に実行することもできます(パッケージを並列にチェックアウトする)。 – gfgm

関連する問題