Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, switch uppercase to lowercase and vice-versa in a string

Tags:

r

I am familiar with the functions toupper() and tolower(), however that doesn't exactly give what I want here. Here is an example of the string I have and the string I want:

this = "This is the string THAT I have!"
that = "tHIS IS THE STRING that i HAVE!"

simple enough to describe with an example, harder to implement (i think).

Thanks!

like image 722
Canovice Avatar asked Mar 10 '23 16:03

Canovice


2 Answers

I'm sort of curious if there is a better way than:

chartr(x = this,
       old = paste0(c(letters,LETTERS),collapse = ""),
       new = paste0(c(LETTERS,letters),collapse = ""))

Helpful observation by @Joris in the comments that ?chartr notes that you can use character ranges, avoiding the paste:

chartr("a-zA-Z", "A-Za-z",this)
like image 165
joran Avatar answered Mar 12 '23 12:03

joran


Here's a way that works with characters that aren't between a and z / A and Z :

text <- "aBàÉ"

up <- gregexpr("\\p{Lu}", text, perl=TRUE)
lo <- gregexpr("\\p{Ll}", text, perl=TRUE)
regmatches(text,up)[[1]] <- tolower(regmatches(text,up)[[1]])
regmatches(text,lo)[[1]] <- toupper(regmatches(text,lo)[[1]])
text
#> [1] "AbÀé"
like image 38
Moody_Mudskipper Avatar answered Mar 12 '23 14:03

Moody_Mudskipper