2016-04-20 4 views
0

für einen Datenrahmen mit dieser Form:Wie transferiere ich den Textbeutel in eine große Doc-Word-Matrix in R?

docId   bow 
1    [(3,1),(4,3),(6,1)...] 
2    [(1,1),(2,5),(3,1),(6,3)...] 
... 

Ich wünsche d * w eine große doc-Wort-Matrix mit einer Größe zu erzeugen (d bezeichnen die Anzahl von Dokumenten und w bezeichnet die Anzahl der Worte):

0 0 1 3 0 1 .... 
1 5 1 0 0 3..... 
.... 

Es gab eine Python-Lösung in SO. Ich frage mich, wie man es in R macht? Vielen Dank!

Antwort

0

wir extrahieren alle (idx, count) erste dann Format in das erforderliche Matrixformat wie folgt:

options(stringsAsFactors=FALSE) 
library(stringi) 
library(plyr) 

df <- data.frame(docId=1:2, bow=c("[(3,1),(4,3),(6,1),(10,8)","[(1,1),(2,5),(3,1),(6,3)")) 
tuples <- stri_extract_all_words(df$bow) 

ans <- rbind.fill.matrix(lapply(tuples, function(x) { 
    idx <- stri_split_fixed(x, ",", simplify=TRUE) 
    idx <- `dim<-`(as.numeric(idx),dim(idx)) 
    res <- matrix(0, ncol=max(idx[,1])) 
    res[1,idx[,1]] <- idx[,2] 
    res 
})) 
ans[is.na(ans)] <- 0 
ans 
Verwandte Themen