【问题标题】:String Matching with word dictionary with R使用 R 与单词字典进行字符串匹配
【发布时间】:2026-02-19 12:15:02
【问题描述】:

我有一个像这样(3×3)的单词表(wt

ungrateful    mango       uncertain
hobby       prejudicial   meat
persecution   bird        honest

还有一本词典(dict

persecution
overpowering
prejudicial
offense
ungrateful
uncertain
musical
murderous
detest
youth

我想用 dict 搜索 wt 中的所有单词,如果有任何单词与字典匹配,这将给出字典单词在单词表中的位置,不匹配的单词将被自动删除。

    wt <- matrix(c("ungrateful","mango", "uncertain","hobby", "prejudicial", "meat","persecution","bird","honest"), nrow = 3, ncol = 3, byrow = TRUE)
    dict<- matrix(c(
"persecution",
"overpowering",
"prejudicial",
"offense",
"ungrateful",
"uncertain",
"musical",
"murderous",
"detest",
"youth"), nrow = 10, ncol = 1, byrow = FALSE)

for (i in 1:nrow(df)){
        for (i in 1:col(df)){
                x[i,j ] <- charmatch(df[i,j],dict_word)
        }          
}

但是当我期待这样的输出时,这会给出错误

     [,1] [,2] [,3]
 [1,]  5         6
 [2,]      3
 [3,]  1

我是 R 的新手,对语法不太了解。请帮忙。

【问题讨论】:

    标签: r string pattern-matching string-matching


    【解决方案1】:

    match 函数在第二个参数中返回第一个参数的匹配位置。 (如果有多个匹配,则只返回第一个匹配的位置。)然后我们将其转换为与wt 矩阵的位置对应的矩阵。

    matrix(match(wt, dict), nrow=nrow(wt))
    
         [,1] [,2] [,3]
    [1,]    5   NA    6
    [2,]   NA    3   NA
    [3,]    1   NA   NA
    

    【讨论】:

    • 天啊,就是这么简单!真的非常感谢。我尝试了很多东西。
    • @bipu 你可以点击答案左边的勾号“接受”它,说明它解决了你的问题。
    • @eipi10,我正在寻找一些关于如何从第二个数据集中获取匹配的某些特定等效列的数据的建议。我已将问题发布到 - *.com/questions/42749447/… 如果您能提出建议,那将是非常有帮助的
    【解决方案2】:

    和上面提到的@epi10一样,charmatch

    matrix(charmatch(wt,dict), nrow = nrow (wt))
    

    匹配

    matrix(pmatch(wt,dict), nrow = nrow (wt))
    

    也可以。

    【讨论】: