我有一个字符矩阵(3乘3)和一个字典(n乘1)。我想找到与字典匹配的字符,将被字典中存在的字符位置替换,并且将删除所有不匹配的字(NA或NULL)。我尝试过简单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)
答案 0 :(得分: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