简体   繁体   中英

R: Searching for a certain, delimited string

I'm looking for a way in R to search for a certain, delimited string. In my example I need to receive TRUE if a cell contains "HDT2" and not "HDT21" or "HDT24" and so on, because this string contains HDT2 as well.

So right now I am using

grepl("HDT2",data.label[d,2])

in a for-loop to check each row of the second column of data.label for "HDT2". The problem is that this also returns TRUE if there is more than just "HDT2". As for example it returns also true if there is "HDT21" or "HDT24", but this is not what i want.

Is there a way to only check for a certain, delimited string? Thanks!

EDIT: The strings I have to check are longer than just "HDT2". The string is for example "HDT2 (Arm 1: reference)".

You can use the following regular expression in grepl() . This will return true for an exact match of "HDT2" , with nothing coming before or after it.

grepl("^HDT2$",data.label[d,2])

Usage:

> grepl("^HDT2$", "HDT2")
[1] TRUE
> grepl("^HDT2$", "AHDT2")
[1] FALSE
> grepl("^HDT2$", "HDT2 (Arm 1: reference)")
[1] FALSE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM