我需要通過比較文檔條款來構建相似矩陣。例如,如果Document1和Document2有兩個相同的術語,那麼我需要在我的相似度矩陣 (m [1,2])處寫一個2。我的相似性矩陣現在看起來像這樣:比較文檔中的文檔條款矩陣R中的文檔
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 0 NA NA NA NA NA NA NA NA
[2,] 0 0 NA NA NA NA NA NA NA
[3,] 0 0 0 NA NA NA NA NA NA
[4,] 0 0 0 0 NA NA NA NA NA
[5,] 0 0 0 0 0 NA NA NA NA
[6,] 0 0 0 0 0 0 NA NA NA
[7,] 0 0 0 0 0 0 0 NA NA
[8,] 0 0 0 0 0 0 0 0 NA
這些文檔和術語在文檔術語表中。現在我必須通過比較所有文檔及其術語,在相似性矩陣中表示NA來填充相似性矩陣。對於文檔對中的每個詞條匹配,我必須計數+1並在矩陣的正確位置插入結束值。
我的問題是,似乎我不能訪問文檔術語矩陣內的單個文檔及其術語。有沒有其他的方式來執行此操作,或者我錯過了什麼?這裏的代碼:
install.packages("tm")
install.packages("openNLP")
install.packages("openNLPmodels.en")
Sys.setenv(NOAWT=TRUE)
library(tm)
library(openNLP)
library(openNLPmodels.en)
sample = c(
"count eagle alien",
"dis bound eagle",
"bound count eagle dis",
"count eagle dis alien",
"bound eagle",
"count dis alien",
"bound count alien",
"bound count",
"count eagle dis"
)
print(sample)
corpus <- Corpus(VectorSource(sample))
inspect(corpus)
corpus <- tm_map(corpus, removeNumbers)
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, tolower)
corpus <- tm_map(corpus, removeWords, stopwords("english"))
corpus <- tm_map(corpus, stemDocument,language="english")
corpus <- tm_map(corpus, stripWhitespace)
corpus <- tm_map(corpus, tmTagPOS)
inspect(corpus)
dtm <- DocumentTermMatrix(corpus)
inspect(dtm)
# need to create similarity matrix here
#dist(dtm, method = "manhattan", diag = FALSE, upper = TRUE)
rowCount <- nrow(dtm)
similMatrix = matrix(nrow = rowCount - 1, ncol = rowCount)
show(similMatrix)
similMatrix[ row(similMatrix) >= col(similMatrix) ] <- 0
for(i in 1:(rowCount - 1)){ # rows
for (j in i+1:rowCount){ # cols
# need to compare document i and j here and write
# the value into similarity matrix
}
}
show(similMatrix)
這是很多包。你需要安裝它們來重現這個嗎? –
例如,如果您只是安裝了任何包定義'DocumentTermMatrix'的包,然後對結果做了'dput'來創建表示,是否足以重現? –
我認爲tm openNLP和openNLPmodels.en軟件包應該能夠完成這項工作,但不能100%確定這一點。所有這些軟件包都已由我的專業人員推薦執行此任務。 –