R中的ngram表示和距离矩阵

哈迪吉

假设我们有以下数据:

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

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

#  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 
phi

您也可以使用该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

用以下方法重新创建1克 stringdist

# 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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章