r - 是否有与 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 工作,但一直没能。
解决方案
也许你可以试试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
推荐阅读
- function - wix-fetch vs wix-http-functions
- java - 替换字符串中的字符而不使用 if else
- apache - google.com 的 Apache 反向代理(仅用于测试)
- r - 在 R 中查找具有 NA 单元格的 .csv 文件的列平均值时出错
- c - 如何查看数字是否在数组中具有相同的数字?
- linux - 从 shell 向 CloudWatch 发送事件
- javascript - Javascript 如何从 ADODB 记录集中获取值
- r - 视网膜显示上的 RStudio 中的内联图大小和编织图大小不一致
- html - CSS HTML tfoot, tbody, thead 复杂样式
- json - 仅用字符串替换 .txt 文件中的 JSON 内容(WSO2 集成器)