Find a string in another string in R

你。 提交于 2020-01-04 06:35:39

问题


I want to find a string within another string in R. The strings are as follows. I want to be able to match string a to string b as and the out put should be a == b which returns TRUE

a <- "6250;7250;6251"
b <- "7250"
a == b                 #FALSE

回答1:


If b were to equal 725 instead of 7250, would you still want the result to be TRUE?

If so then the grepl answer already given will work (and you could speed it up a bit by setting fixed=TRUE since there are no patterns to be matched.

If you only want TRUE when there is an exact match to something between ; then you will either need to embed b into a regular expression (sprintf may be of help), or simpler, use strsplit to split a into just the parts to be matched, then use %in% to see if b is a match to any of those values.




回答2:


You can use regmatches and gregexpr, but your question is somewhat vague at the moment, so I'm not positive that this is what you're looking for:

> regmatches(a, gregexpr(b, a))
[[1]]
[1] "7250"

> regmatches(a, gregexpr(b, a), invert=TRUE)
[[1]]
[1] "6250;" ";6251"

Based on your updated question, you're probably looking for grepl.

> grepl(b, a)
[1] TRUE
> grepl(999, a)
[1] FALSE

^^ We're essentially saying "look for 'b' in 'a'".



来源:https://stackoverflow.com/questions/18791354/find-a-string-in-another-string-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!