String Matching a dictionary with R

I have a table of words ( wt ) like this (3 by 3)

ungrateful    mango       uncertain
hobby       prejudicial   meat
persecution   bird        honest

and dictionary ( dict )

persecution
overpowering
prejudicial
offense
ungrateful
uncertain
musical
murderous
detest
youth

I want to search all words in wt using dict , and if any word matches the dictionary, this will give the position of the dictionary word in the table of words, and words that do not match will be automatically deleted.

    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)
        }          
}

But it gives an error when I expect a way out like this

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

I am new to R and not very good at syntax. please, help.

+4
source share
2 answers

match . ( , .) , wt.

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

@epi10, charmatch

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

pmatch

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

.

+2

Source: https://habr.com/ru/post/1629231/


All Articles