2017-11-01 6 views
1

以下は、私がテキストデータからバイグラムを作成する私のコードです。私が得ている出力は、モデルの変数としてこれらを使用できるように、フィールド名にアンダースコアが必要であることを除いては問題ありません。ここでRライブラリ(tm)でどうすればNGRAMSの出力に下線を付けます

text<- c("Since I love to travel, this is what I rely on every time.", 
     "I got the rewards card for the no international transaction fee", 
     "I got the rewards card mainly for the flight perks", 
     "Very good card, easy application process, and no international 
transaction fee", 
     "The customer service is outstanding!", 
     "My wife got the rewards card for the gift cards and international 
transaction fee.She loves it") 
df<- data.frame(text) 


library(tm) 
corpus<- Corpus(DataframeSource(df)) 
corpus<- tm_map(corpus, content_transformer(tolower)) 
corpus<- tm_map(corpus, removePunctuation) 
corpus<- tm_map(corpus, removeWords, stopwords("english")) 
corpus<- tm_map(corpus, stripWhitespace) 


BigramTokenizer<- 
    function(x) 
    unlist(lapply(ngrams(words(x),2),paste,collapse=" "),use.names=FALSE) 

dtm<- DocumentTermMatrix(corpus, control= list(tokenize= BigramTokenizer)) 

sparse<- removeSparseTerms(dtm,.80) 
dtm2<- as.matrix(sparse) 
dtm2 

出力は次のようになります。

Terms 
Docs got rewards international transaction rewards card transaction fee 
    1   0       0   0    0 
    2   1       1   1    1 
    3   1       0   1    0 
    4   0       1   0    1 
    5   0       0   0    0 
    6   1       1   1    0 

どのように私はgot_rewardsの代わりに、のようなフィールド名がこれは本当にtm固有のものではない報酬

+1

変更 『' '崩壊へ=』 _「''崩壊=」? – lukeA

+0

それは..ありがとう! – djacobs1216

答えて

1

を持って作るのですか私は思います。とにかく、あなたはあなたのコード内でcollapse="_"を設定するなどのように事実の後に列名を変更することができます。

colnames(dtm2) <- gsub(" ", "_", colnames(dtm2), fixed = TRUE) 
dtm2 
    Terms 
Docs got_rewards international_transaction rewards_card transaction_fee 
    1   0       0   0    0 
    2   1       1   1    1 
    3   1       0   1    0 
    4   0       1   0    1 
    5   0       0   0    0 
    6   1       1   1    0 
+0

作品..ありがとう! – djacobs1216

関連する問題