首页 > 解决方案 > 是否有与 R 中的 which 函数等效的 pmatch ?

问题描述

我正在使用以下代码在 R 中的以下矩阵中获取某些匹配项的索引:

      [,1]  [,2] 
 [1,] "t2"  "t2" 
 [2,] "t5"  "t5" 
 [3,] "t7"  "t7" 
 [4,] "t10" "t10"
 [5,] "t9"  "t9" 
 [6,] "t4"  "t4" 
 [7,] "t8"  "t8" 
 [8,] "t6"  "t6" 
 [9,] "t3"  "t3" 
[10,] "t1"  "t1"
searchstring<-c("t1","t2")
searchresult<-which(association[,1] %in% searchstring)
#The result is "10,1"

我需要能够找到部分匹配项。例如,如果我输入“t1”作为搜索字符串,我需要输出为“4,10”。这只是这里的示例数据,但在我的真实数据中,矩阵中的所有字符串都是唯一的,但我只会搜索字符串的一部分,所以我只需要搜索那部分并返回任何的行索引匹配字符串,就像匹配完整字符串一样。在 R 中是否有执行此操作的功能?我试图让 pmatch 工作,但一直没能。

标签: rmatrix

解决方案


也许你可以试试grep

> lapply(paste0("^", searchstring), grep, x = association[, 1])
[[1]]
[1]  4 10

[[2]]
[1] 1

startsWith+unstack

> unstack(as.data.frame(which(sapply(searchstring, startsWith, x = association[, 1]), arr.ind = TRUE)))
$`1`
[1]  4 10

$`2`
[1] 1

推荐阅读