2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

docMatrixからメタ情報を削除する関数

Last updated at Posted at 2019-12-19

1. 趣旨

Rでテキストデータの解析(形態素解析)をやるときのおはなし。
RMeCabというパッケージを利用して、文書行列を作成する関数docMatrix()を実行すると、出力結果にメタ情報が入力される仕様になってます。このメタ情報、入っている状態だと分析できないのですが、「必要ないなら自分で消してくれ」という警告文が流れてきます。

> docMatrix("folder", minFreq = 2) %>% print
file = folder/2018.txt
file = folder/2019.txt
Term Document Matrix includes 2 information rows! 
whose names are [[LESS-THAN-2]] and [[TOTAL-TOKENS]]
if you remove these rows, run
result[ rownames(result) !=  "[[LESS-THAN-2]]" , ]
result[ rownames(result) !=  "[[TOTAL-TOKENS]]" , ]
                                docs
terms                            2018.txt 2019.txt
  .                                  3           0
  [[LESS-THAN-2]]                  170         200
  [[TOTAL-TOKENS]]                 830        1016
  11                                 2           0
 

だったら、初めからメタ情報を削除した状態で出力してくれる関数作っちゃえば楽じゃね?
ということで、超簡単な関数を作りました。いわゆるラッパー関数(Wrapper)ってやつです。

2. 関数を定義

docMatrixx()という関数を定義してみます。
本家docMatrix()より1つだけ「x」が多いです。

docMatrixx <- function(folder_name, minFreq = 1){
  lessthan <- paste("[[LESS-THAN-",minFreq,"]]") %>% gsub(" ","",.)
  resultMatrix <- docMatrix(folder_name, minFreq = minFreq)
  resultMatrix <- resultMatrix[rownames(resultMatrix) != lessthan, ]
  resultMatrix <- resultMatrix[rownames(resultMatrix) != "[[TOTAL-TOKENS]]", ]
}

おまけで、たまーに使うminFreq引数も使えるようにしました。

3. 実行してみた。

# 必要なパッケージは予め読み込んでおいてください
library(RMeCab)
library(dplyr)

# 第一引数はディレクトリ名、第二引数は単語の最低頻度の指定です
# 第一引数はディレクトリ名、第二引数は単語の最低頻度の指定です
> docMatrixx("folder",2) %>% print()
file = folder/2018.txt
file = folder/2019.txt
Term Document Matrix includes 2 information rows! 
whose names are [[LESS-THAN-2]] and [[TOTAL-TOKENS]]
if you remove these rows, run
result[ rownames(result) !=  "[[LESS-THAN-2]]" , ]
result[ rownames(result) !=  "[[TOTAL-TOKENS]]" , ]
                          docs
terms                      2018.txt 2019.txt
  .                                  3           0
  11                                 2           0

メタ情報の[[LESS-THAN-2]][[TOTAL-TOKENS]]も、行列からちゃんと消えました。

4. おわりに

メタ情報のない状態で行列を出力できるので、そのまま分析にかけることができるようになりました。
本家のdocMatrix()にはもっと沢山の引数が設定されているので、必要であれば関数の定義をいじくって拡張すれば、他の引数にも対応できるはずです。

おしまい。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?