R中的ngram表示和距离矩阵

ngram representation and distance matrix in R

假设我们有这个数据:

a <- c("ham","bamm","comb")

对于 1-gram,这是上面列表的矩阵表示。

#  h a m b c o
#  1 1 1 0 0 0
#  0 1 2 1 0 0 
#  0 0 1 1 1 1

我知道 table(strsplit(a,split = "")[i]) for i in 1:length(a) 会给出它们每个的分开计数。但我不知道如何使用 rbind 将它们作为一个整体,因为长度和列名不同。

之后,我想使用欧几里德距离或曼哈顿距离来找到它们各自的相似度矩阵:

#     ham  bamm comb  
# ham  0    3    5
# bamm 3    0    4
# comb 5    4    0 

你可以这样做:

s <- stack(setNames(strsplit(a,split=""),a))
m <- t(table(s))

> m
      values
ind    a b c h m o
  ham  1 0 0 1 1 0
  bamm 1 1 0 0 2 0
  comb 0 1 1 0 1 1

然后使用 dist :

> as.matrix(dist(m,method='manhattan'))
     ham bamm comb
ham    0    3    5
bamm   3    0    4
comb   5    4    0

您也可以使用 stringdist 包。

library(stringdist)
a <- c("ham","bamm","comb")

# stringdistmatrix with qgram calculations
stringdistmatrix(a, a, method = 'qgram')

     [,1] [,2] [,3]
[1,]    0    3    5
[2,]    3    0    4
[3,]    5    4    0

stringdist

重新创建 1-gram
# creates the total count of the 1-gram
qgrams(a, q = 1L)
   h m o a b c
V1 1 4 1 2 2 1

# create a named vector if you want a nice table
names(a) <- a
qgrams(a, .list = a, q = 1L)

#V1 is the total line
     h m o a b c
V1   1 4 1 2 2 1
ham  1 1 0 1 0 0
bamm 0 2 0 1 1 0
comb 0 1 1 0 1 1