Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grep a word exactly

Tags:

regex

r

I'd like to grep for "nitrogen" in the following character vector and want to get back only the entry which is containing "nitrogen" and nothing of the rest (e.g. nitrogen fixation):

varnames=c("nitrogen", "dissolved organic nitrogen", "nitrogen fixation", "total dissolved nitrogen", "total nitrogen")

I tried something like this:

grepl(pattern= "![[:space:]]nitrogen![[:space:]]", varnames)

But this doesn't work.

like image 670
sabsirro Avatar asked Apr 06 '12 09:04

sabsirro


2 Answers

Although Dason's answer is easier, you could do an exact match using grep via:

varnames=c("nitrogen", "dissolved organic nitrogen", "nitrogen fixation", "total dissolved nitrogen", "total nitrogen")

grep("^nitrogen$",varnames,value=TRUE)
[1] "nitrogen"

grep("^nitrogen$",varnames)
[1] 1
like image 61
thelatemail Avatar answered Sep 28 '22 19:09

thelatemail


To get the indices that are exactly equal to "nitrogen" you could use

which(varnames == "nitrogen")

Depending on what you want to do you might not even need the 'which' as varnames == "nitrogen" gives a logical vector of TRUE/FALSE. If you just want to do something like replace all of the occurances of "nitrogen" with "oxygen" this should suffice

varnames[varnames == "nitrogen"] <- "oxygen"
like image 20
Dason Avatar answered Sep 28 '22 19:09

Dason