2013-09-11 6 views
1

Мне нужно создать матрицу подобия, а код ниже - то, что у меня есть. Однако результаты не то, что мне нужно. Код возвращает матрицу с 16 строками, которая является результатом 8 уникальных терминов в матрице документов и двух уникальных терминов в workTitle.Вычислить матрицу подобия с помощью пакета tm

Мне нужна матрица, которая имеет только 4 строки (по одному за заголовок) и каждую строку, чтобы представить сумму расстояния редактирования между каждым словом в workTitle и каждым из терминов в заголовках.

require(tm) 

workTitle <- c("biomechanical engineer") 
titles <- c("train machinist", "operations supervisor", "pharmacy tech", "mechanical engineer") 

# create Corpus and a document-term matrix from the titles 
titleCorpus <- Corpus(VectorSource(titles)) 
titleDtm <- DocumentTermMatrix(titleCorpus) 

# print out the document-term matrix 
inspect(titleDtm) 

# calculate edit distance between every word from the test_var and the column names in the document-term matrix 
d <- apply(titleDtm, 1, function(x) { 
    terms <- unlist(strsplit(as.character(workTitle), " ")) 
    adist(colnames(titleDtm), terms) 
}) 

Это выход из кода выше:

 Docs 
     1 2 3 4 
    [1,] 11 11 11 11 
    [2,] 8 8 8 8 
    [3,] 3 3 3 3 
    [4,] 9 9 9 9 
    [5,] 11 11 11 11 
    [6,] 11 11 11 11 
    [7,] 10 10 10 10 
    [8,] 11 11 11 11 
    [9,] 0 0 0 0 
    [10,] 7 7 7 7 
    [11,] 8 8 8 8 
    [12,] 9 9 9 9 
    [13,] 8 8 8 8 
    [14,] 8 8 8 8 
    [15,] 7 7 7 7 
    [16,] 6 6 6 6 

ответ

1

Если я правильно понял, как о чем-то вроде:

terms <- as.character(Dictionary(titleDtm)) 
dat <- data.frame(adist(titles, terms), row.names = titles) 
colnames(dat) <- terms 
dat 

что приводит к

     engineer machinist mechanical operations pharmacy supervisor tech train 
train machinist    12   6   11   12  11   14 12 10 
operations supervisor  16  17   18   11  18   11 19 17 
pharmacy tech    12  10   11   11  5   13 9 11 
mechanical engineer   11  13   9   16  16   16 16 16 

А потом для сумм

data.frame(sum = rowSums(dat)) 

Который имеет следующий вывод

     sum 
train machinist  88 
operations supervisor 127 
pharmacy tech   82 
mechanical engineer 113 
Смежные вопросы