[R] case conversion and/or string comparison

Randall Skelton rhskelto at atm.ox.ac.uk
Fri Nov 16 12:37:55 CET 2001

This is no doubt trivial but after searching the help files and the web, I 
cannot seem to find it.

1) How do I convert 'hgt' into 'HGT' in R?
2) How should I have used the help facilities to find this?

At the end of the day, all I want to do is case insensitive string 
matching... i.e. 'if ("HGT" == 'hgt') print('this should be true')'

I tried using some of the regular expression tools but I had some trouble 
interpreting the results:

 > grep("HGT", "hgt", ignore.case = T)     
 [1] 1
 > grep("HGT", "tem", ignore.case = T)

This appears to be what I want. However, putting an 'if' around this 
fails for the false case.

 > if ( grep("HGT", "tem", ignore.case = T) ) print('hi');
 Error in if (grep("HGT", "tem", ignore.case = T)) print("hi") : 
         argument of if(*) is not interpretable as logical

I suppose that R cannot interpret 'if (numeric(0))'.  I would think the 
following would work?

 > grep("HGT", "hgt", ignore.case = T) == 1
 [1] TRUE
 > grep("HGT", "tem", ignore.case = T) == 1

Note that the bottom is not 'FALSE'?  Why?

 > if (grep("HGT", "tem", ignore.case = T) == 1) print('hi');
 Error in if (grep("HGT", "tem", ignore.case = T) == 1) print("hi") : 
         missing value where logical needed

I suppose that R cannot interpret 'if (logical(0))' either?

So my question is:  How to I return a logical 'TRUE/FALSE' when 
comparing 2 strings?  Clearly, I am missing something.

Thanks in advance,

r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list