[R] replace a whole word with sub()

Patrick Connolly p_connolly at slingshot.co.nz
Sat Nov 14 03:35:36 CET 2009


On Fri, 13-Nov-2009 at 03:13PM +0000, Giulio Di Giovanni wrote:

|> 
|>  
|> 
|> Dear all, 
|> 
|>  
|> 
|> I cannot figure out how to solve a small problem (well, not for me), surely somebody can help me in few seconds.
|> 
|>  
|> 
|> I have a series of strings in a vector X of the type  "xxx", "yyy", "zzz", "IgA", "IgG", "kkk", "IgM", "aaa".
|> 
|> I want to substitute every ENTIRE string beginning with "Ig" with "0".
|> 
|> So, I'd like to have "xxx", "yyy", "zzz", "0", "0", "kkk", "0", "aaa".
|> 
|>  
|> 
|> I can easily identify these strings with grep("^Ig", X), but if I use this criterion in the sub() function (sub("^Ig", "0", X) I obviously get "0A", "0G" etc.
|> 
|>  
|> 
|> I didn't expect to do it in this way and I tried with metacharacters and regexps in order to grep and substitute the whole word (\b \>, $). I don't post here my tryings,  because they were obviously wrong.
|> 
|> Please can you help me?

I think this is what you need:

> X <- c("xxx", "yyy", "zzz", "IgA", "IgG", "kkk", "IgM", "aaa")
> X[grep("^Ig", X)] <- "0"
> X
[1] "xxx" "yyy" "zzz" "0"   "0"   "kkk" "0"   "aaa"
> 

HTH

-- 
~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.   
   ___    Patrick Connolly   
 {~._.~}                   Great minds discuss ideas    
 _( Y )_  	         Average minds discuss events 
(:_~*~_:)                  Small minds discuss people  
 (_)-(_)  	                      ..... Eleanor Roosevelt
	  
~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.




More information about the R-help mailing list