[R] case conversion and/or string comparison
Ben Bolker
ben at zoo.ufl.edu
Fri Nov 16 13:20:51 CET 2001
Here are some hacks:
test <- "BIG"
letters[match(strsplit(test,"")[[1]],LETTERS)]
test2 <- "BIGsmall"
v <- strsplit(test2,"")[[1]]
ucase <- v %in% LETTERS
v[ucase] <- letters[match(v[ucase],LETTERS)]
paste(v,collapse="")
I'm not sure how you would have found this in the help system ...
On Fri, 16 Nov 2001, Randall Skelton wrote:
> 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)
> numeric(0)
>
> 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
> logical(0)
>
> 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,
> Randall
>
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
> 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
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
>
--
318 Carr Hall bolker at zoo.ufl.edu
Zoology Department, University of Florida http://www.zoo.ufl.edu/bolker
Box 118525 (ph) 352-392-5697
Gainesville, FL 32611-8525 (fax) 352-392-3704
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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