grep R中列表内向量中的精确匹配 [英] grep exact match in vector inside a list in R
本文介绍了grep R中列表内向量中的精确匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的列表:
map_tmp <- list("ABC",
c("EGF", "HIJ"),
c("KML", "ABC-IOP"),
"SIN",
"KMLLL")
> grep("ABC", map_tmp)
[1] 1 3
> grep("^ABC$", map_tmp)
[1] 1 # by using regex, I get the index of "ABC" in the list
> grep("^KML$", map_tmp)
[1] 5 # I wanted 3, but I got 5. Claiming the end of a string by "$" didn't help in this case.
> grep("^HIJ$", map_tmp)
integer(0) # the regex do not return to me the index of a string inside the vector
如何在列表中获取字符串的索引(完全匹配)?我可以不用 grep
.有什么方法可以获取列表中某个字符串的索引(完全匹配)?谢谢!
How can I get the index of a string (exact match) in the list?
I'm ok not to use grep
. Is there any way to get the index of a certain string (exact match) in the list? Thanks!
推荐答案
使用mapply或带有 str_detect
的Map来查找位置,我只对一个字符串" KML ",您可以将其用于其他所有程序.我希望这会有所帮助.
Use either mapply or Map with str_detect
to find the position, I have run only for one string "KML" , you can run it for all others. I hope this is helpful.
首先,我们甚至列出列表,以便我们可以轻松处理它
First of all we make the lists even so that we can process it easily
library(stringr)
map_tmp_1 <- lapply(map_tmp, `length<-`, max(lengths(map_tmp)))
### Making the list even
val <- t(mapply(str_detect,map_tmp_1,"^KML$"))
> which(val[,1] == T)
[1] 3
> which(val[,2] == T)
integer(0)
对于" ABC "字符串:
val <- t(mapply(str_detect,map_tmp_1,"ABC"))
> which(val[,1] == T)
[1] 1
> which(val[,2] == T)
[1] 3
>
这篇关于grep R中列表内向量中的精确匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文