2017-02-23 12 views
3

"splitstackshape"の "cSplit_e"を使用して、1つの列の複数の値をバイナリ値の列に分割することができます。私はtf-idfを計算するためにテキストの問題を扱っていますが、列の下ですべての一意の値を持つことは必ずしも必要ではありません。例えば、複数の値を考慮したcSplit_e関数の変更

docname ftype      doc_text 
    1  mw    hello, hi, how, are, you, hello 
    2  gw      hi,yo,man 
    3  mw      woha,yo, yoman 

DPUT(DF)上記例えば

structure(list(docname = 1:3, ftype = c("mw", "gw", "mw"), doc_text = structure(1:3, .Label = c("hello, hi, how, are, you, hello", 
"hi,yo,man", "woha,yo, yoman"), class = "factor")), .Names = c("docname", 
"ftype", "doc_text"), class = "data.frame", row.names = c(NA, 
-3L)) 

我々はDOC-1を考慮すればとき」、次いでcSplit_eが "1" の値を有する5つの別々の列にdoc_text変換します「こんにちは」が2回現れた。反復値を考慮に入れてこの関数を変更する方法はありますか?本質的には

、ここで私が達成しようとしているものです:データフレームを考える

あなたは、どのように、DOCNAME FTYPE doc_text 1 MWこんにちは、こんにちは、こんにちは 2 GWよ、やあ、男 3 me woha、yo、yoman

"、"で区切られた列の値に基づいてdoc_textを複数の列に変換し、それぞれの頻度を取得したいとします。だから、結果は、誰かがこの使用「splitstackshape」または別の方法でを達成する方法を知っているならば、私は感謝します

docname ftype are hello hi how man woha yo yoman you 
    1 mw 1  2 1 1 0 0 0  0 1 
    2 gw 0  0 1 0 1 0 1  0 0 
    3 mw 0  0 0 0 0 1 1  1 0 

でなければなりません。最終的な目的はtf-idfを計算することです。

ありがとうございました。

答えて

3

私たちは、 'doc_text'

library(qdapTools) 
cbind(df[1], mtabulate(strsplit(as.character(df$doc_text), ",\\s*"))) 
# docname are hello hi how man woha yo yoman you 
#1  1 1  2 1 1 0 0 0  0 1 
#2  2 0  0 1 0 1 0 1  0 0 
#3  3 0  0 0 0 0 1 1  1 0 

それとも別のオプションであるtidyverse

library(tidyverse) 
separate_rows(df, doc_text) %>% #split to long format 
      group_by(docname, doc_text) %>% #group by variables 
      tally() %>% #get the frequency 
      spread(doc_text, n, fill=0) #reshape to wide 

それとも@Frankが

を示唆したようで分割後 mtabulateでこれを行うことができます少し text-miningで10
+2

おかげで@akrunとフランク。 – syebill

2

docs <- gsub('[[:punct:]]+', ' ', as.character(df$doc_text)) 
library(tm) 
corpus <- Corpus(VectorSource(docs)) 

# compute Term Frequencies 
as.matrix(DocumentTermMatrix(corpus, control = list(wordLengths=c(2,Inf)))) 
#  Terms 
#Docs are hello hi how man woha yo yoman you 
# 1 1  2 1 1 0 0 0  0 1 
# 2 0  0 1 0 1 0 1  0 0 
# 3 0  0 0 0 0 1 1  1 0 

# compute Tf-Idf scores 
as.matrix(DocumentTermMatrix(corpus, control = list(wordLengths=c(2,Inf), weighting=weightTfIdf))) 
#   Terms 
#Docs  are  hello   hi  how  man  woha  yo  yoman`  you 
# 1 0.2641604 0.5283208 0.09749375 0.2641604 0.0000000 0.0000000 0.0000000 0.0000000 0.2641604 
# 2 0.0000000 0.0000000 0.19498750 0.0000000 0.5283208 0.0000000 0.1949875 0.0000000 0.0000000 
# 3 0.0000000 0.0000000 0.00000000 0.0000000 0.0000000 0.5283208 0.1949875 0.5283208 0.0000000 
+0

最初の行で判断すると、これは "hello world"のようなマルチワード値を別々の値として扱います。もしそうなら、その注意点に言及したいかもしれません。 – Frank

+2

@Frankはい、それは「単語の袋」表現なので、「n> 1」、例えばフレーズの「nグラム」は考慮しない。 @Sandipan @ –

+0

私はあなたが "、"を取り除くために句読点を取り除いたのを見ることができますが、テキストに単語の一部を構成する意味のある句読点があればどうなりますか?私は最初のステップを省略し、残りの部分に従うべきですか?また、あなたは "wordLengths = c(2、Inf)"に光を当てることができます。ドキュメントの最小と最大の単語長を指定するために使用されていますか? – syebill

関連する問題