2017-09-13 133 views
1

因此,我已經有了TDM,但它在Excel上。所以我將它保存爲CSV。現在我想做一些分析,但是我不能將它作爲使用tm包的TDM加載。我的CSV看起來是這樣的:將CSV格式的術語文檔矩陣導入到R

  item01 item02 item03  item04 


red   0   1   1   0 
circle  1   0   0   1 
fame  1   0   0   0 
yellow  0   0   1   1 
square  1   0   1   0 

所以我一直無法加載該文件作爲TDM,到目前爲止,我已經試過最好是這樣的:

myDTM <- as.DocumentTermMatrix(df, weighting = weightBin) 

但它加載1對所有細胞

<<DocumentTermMatrix (documents: 2529, terms: 1952)>> 
Non-/sparse entries: 4936608/0 
Sparsity   : 0% 
Maximal term length: 27 
Weighting   : binary (bin) 
Sample    : 

      Terms 
Docs   item01 item02 item03 item04 
     Red  1  1  1  1     
     Circle  1  1  1  1   
     fame  1  1  1  1 

我第一次嘗試轉換爲語料庫和其他的東西,但如果我嘗試使用像檢查(TDM)的任何函數返回一個錯誤,這樣的或類似的。

Error in `[.simple_triplet_matrix`(x, docs, terms) : 

我真的不相信沒有辦法以正確的格式導入它,任何建議嗎?提前致謝。

回答

0

先嚐試將CS​​V轉換爲稀疏矩陣。我的CSV與您的CSV不同,因爲我自己輸入了它,但它是一樣的想法。

> library(tm) 
> library(Matrix) 
> myDF <- read.csv("my.csv",row.names=1,colClasses=c('character',rep('integer',4))) 
> mySM <- Matrix(as.matrix(myDF),sparse=TRUE) 
> myDTM <- as.DocumentTermMatrix(mySM,weighting = weightBin) 
> inspect(myDTM) 

<<DocumentTermMatrix (documents: 5, terms: 4)>> 
Non-/sparse entries: 7/13 
Sparsity   : 65% 
Maximal term length: 6 
Weighting   : binary (bin) 
Sample    : 
     Terms 
Docs  item01 item02 item03 item04 
    circle  1  1  0  0 
    fame  1  0  0  0 
    red   0  0  0  0 
    square  1  0  1  0 
    yellow  0  0  1  1 
> 
+0

Awsome,稀疏矩陣解決了它!謝謝! –