user2318751
user2318751

Reputation: 1

how can I use perl-like regular expressions in R to match exact string held within a vector?

I have a data frame containing a number of similar IDs and associated information:

col1 = c("id_string", "1id_string", "id_string1")    
col2 = c("x", "y", "z")    
col3 = c("d", "e", "f")    
data = data.frame(col1, col2, col3)

I have a vector (output from a loop) containing a string that I wish to use for matching:

id = "id_string"

I have used grep to match the string held within the vector with all rows in data$col1 containing the string

grep(id, data$col1)

However, I wish to extract only the row numbers from data$col1 with the exact string held within id (no characters before / after). How can I achieve this?

Upvotes: 0

Views: 152

Answers (1)

CHP
CHP

Reputation: 17189

If you must use grep try

data
##         col1 col2 col3
## 1  id_string    x    d
## 2 1id_string    y    e
## 3 id_string1    z    f

grep(paste0("^", id, "$"), data$col1)
## [1] 1

Or as @Arun suggested

data[data$col1 == id, ]

Upvotes: 3

Related Questions