2015-03-17 5 views
1

У меня есть следующий код:Документ Термин матрица R

rm(list=ls(all=TRUE)) #clear data 
setwd("~/UCSB/14 Win 15/Issy/text.fwt") #set working directory 
files <- list.files(); head(files) #load & check working directory 

fw1 <- scan(what="c", sep="\n",file="fw_chp01.fwt") 

library(tm) 
corpus2<-Corpus(VectorSource(c(fw1))) 
skipWords<-(function(x) removeWords(x, stopwords("english"))) 

#remove punc, numbers, stopwords, etc 
funcs<-list(content_transformer(tolower), removePunctuation, removeNumbers, stripWhitespace, skipWords) 
corpus2.proc<-tm_map(corpus2, FUN = tm_reduce, tmFuns = funcs) 

corpus2a.dtm <- DocumentTermMatrix(corpus2.proc, control = list(wordLengths = c(1,110))) #create document term matrix 

Я пытаюсь использовать некоторые из операций подробно в справочном руководстве по тм (http://cran.r-project.org/web/packages/tm/tm.pdf) с небольшим успехом. Например, когда я пытаюсь использовать findFreqTerms, я получаю следующее сообщение об ошибке:

Error: inherits(x, c("DocumentTermMatrix", "TermDocumentMatrix")) is not TRUE 
Can

никому ключ мне в том, почему это не работает, и что я могу сделать, чтобы исправить это?

отредактированные для @lawyeR:

головки (fw1) производят первые шесть строк текста (Эпизод 1 из Finnegans Wake Джеймс Джойс):

[1] "003.01 riverrun, past Eve and Adam's, from swerve of shore to bend"  
[2] "003.02 of bay, brings us by a commodius vicus of recirculation back to"  
[3] "003.03 Howth Castle and Environs."           
[4] "003.04 Sir Tristram, violer d'amores, fr'over the short sea, had passen-" 
[5] "003.05 core rearrived from North Armorica on this side the scraggy"   
[6] "003.06 isthmus of Europe Minor to wielderfight his penisolate war: nor" 

осматривает (corpus2) выводит каждую строку текст в следующем формате (это последняя строка текста):

[[960]] 
<<PlainTextDocument (metadata: 7)>> 
029.36 borough. #this part differs by line of course 

инспектировать (corpus2a.dtm) возвращает таблицу всех типов (есть 4163 в общей сложности (в тексте в т он следующий формат:

Docs youths yoxen yu yurap yutah zee zephiroth zine zingzang zmorde zoom 
    1  0  0 0  0  0 0   0 0  0  0 0 
    2  0  0 0  0  0 0   0 0  0  0 0 
+0

Можете ли вы включить в свой вопрос, что возвращается с головы (fw1)? Кроме того, включите то, что возвращается из инспекции (corpus2). Наконец, для диагностики выясняется, что производит проверка (corpus2a.dtm)? – lawyeR

+0

@lawyeR Я включил эти результаты в редактирование вопроса. Спасибо за вашу помощь! – hooliaquoolia

ответ

0

Вот упрощенная форма, которую вы предоставили и сделали, и tm делает свою работу. Возможно, что одна или несколько шагов очистки вызвали проблему.

> library(tm) 
> fw1 <- c("riverrun, past Eve and Adam's, from swerve of shore to bend  
+         of bay, brings us by a commodius vicus of recirculation back to 
+         Howth Castle and Environs.  
+         Sir Tristram, violer d'amores, fr'over the short sea, had passen- 
+         core rearrived from North Armorica on this side the scraggy  
+         isthmus of Europe Minor to wielderfight his penisolate war: nor") 
> 
> corpus<-Corpus(VectorSource(c(fw1))) 
> inspect(corpus) 
<<VCorpus (documents: 1, metadata (corpus/indexed): 0/0)>> 

[[1]] 
<<PlainTextDocument (metadata: 7)>> 
riverrun, past Eve and Adam's, from swerve of shore to bend  
           of bay, brings us by a commodius vicus of recirculation back to 
           Howth Castle and Environs.  
           Sir Tristram, violer d'amores, fr'over the short sea, had passen- 
           core rearrived from North Armorica on this side the scraggy  
           isthmus of Europe Minor to wielderfight his penisolate war: nor 

> dtm <- DocumentTermMatrix(corpus) 
> findFreqTerms(dtm) 
[1] "adam's,"  "and"   "armorica"  "back"   "bay,"   "bend"   
[7] "brings"  "castle"  "commodius"  "core"   "d'amores,"  "environs."  
[13] "europe"  "eve"   "fr'over"  "from"   "had"   "his"   
[19] "howth"   "isthmus"  "minor"   "nor"   "north"   "passen-"  
[25] "past"   "penisolate" "rearrived"  "recirculation" "riverrun,"  "scraggy"  
[31] "sea,"   "shore"   "short"   "side"   "sir"   "swerve"  
[37] "the"   "this"   "tristram,"  "vicus"   "violer"  "war:"   
[43] "wielderfight" 

В другой точке, я считаю полезным в начале загрузки несколько других дополнительных пакетов tm.

library(SnowballC); library(RWeka); library(rJava); library(RWekajars) 

За то, что его стоимость, по сравнению с вашими несколько сложных этапов очистки, обычно я тащусь вдоль, как это (заменить комментарии $ комментарий с текстом вектор):

comments$comment <- tolower(comments$comment) 
comments$comment <- removeNumbers(comments$comment) 
comments$comment <- stripWhitespace(comments$comment) 
comments$comment <- str_replace_all(comments$comment, " ", " ") 
# replace all double spaces internally with single space 
# better to remove punctuation with str_ because the tm function doesn't insert a space 
library(stringr) 
comments$comment <- str_replace_all(comments$comment, pattern = "[[:punct:]]", " ") 
comments$comment <- removeWords(comments$comment, stopwords(kind = "english")) 
+0

Этот код работает, но по какой-то причине, когда я запускаю его, я получаю: Ошибка в eval (expr, envir, enc): не удалось найти функцию «str_replace_all» – hooliaquoolia

+0

Вы загрузили пакет stringr? – lawyeR

0

С другой билет, это должно help tm 0.6.0 имеет ошибку, и ее можно решить с помощью этого утверждения.

corpus_clean <- tm_map(corp_stemmed, PlainTextDocument) 

Надеюсь, это поможет.

Смежные вопросы