2

我有一个字符词矩阵(3 x 3)和一个字典(n x 1)。我想找到与字典匹配的字符,将替换为字典中存在的字符位置,并且将删除所有不匹配的单词(NA 或 NULL)。我试过 simple pmatch,但它不起作用。我正在寻找这样的结果,

1    5    2
1    4    NA
3    NA   2

但是以这种方式得到结果,[1] 1 NA 3 5 4 NA 2 NA NA

我尝试了下面的代码,

a <- matrix(c("456_rr", "432_uu", "522_kk", "456_rr", "432_tt", "522", "456_ss", "432", "522_kk"), nrow = 3, ncol = 3, byrow = TRUE) # WordTable

b <- matrix(c("456_rr","522_kk","456_ss", "432_tt", "432_uu"), nrow = 5, ncol = 1) # Dictionary

c <- pmatch(a, b)

print(c)
4

1 回答 1

2

'b' 中的nrow不正确。它应该是5

b <- matrix(c("456_rr","522_kk","456_ss", "432_tt", 
     "432_uu"), nrow = 5, ncol = 1) 
v1 <- pmatch(a,b)
m1 
#[1]  1 NA  3  5  4 NA  2 NA NA

dim(m1) <- dim(a)
m1
#     [,1] [,2] [,3]
#[1,]    1    5    2
#[2,]   NA    4   NA
#[3,]    3   NA   NA

如果我们需要获取重复的索引,使用duplicates.ok=TRUE默认为 FALSE

`dim<-`(pmatch(a, b, duplicates.ok=TRUE), dim(a))
#     [,1] [,2] [,3]
#[1,]    1    5    2
#[2,]    1    4    2
#[3,]    3   NA    2
于 2016-03-31T06:58:40.893 回答