我有一个这样的列表:
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
如何获取字符串中的索引(完全匹配)list?
我可以不使用grep
。有没有办法获取列表中某个字符串(完全匹配)的索引?谢谢!
使用lapply:
which(lapply(map_tmp, function(x) grep("^HIJ$", x))!=0)
lapply 函数为您提供列表中每个元素的列表(如果没有匹配则为 0)。这which!=0
函数为您提供列表中字符串出现的元素。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)