2

I have a string

text <- "This String IS a tESt. TRYING TO fINd a waY to do ThiS."

and I would like to use gsub in R to replace all characters in every word that is not the first letter to lowercase. Is this possible?

desired_output <- "This String Is a test. Trying To find a way to do This."
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Ankhnesmerira
  • 1,386
  • 15
  • 29

2 Answers2

2

There is a pretty way to do this. We can make a single call to gsub in Perl mode, taking advantage of the ability to lowercase a capture group.

text <- "This String IS a tESt. TRYING TO fINd a waY to do ThiS."
gsub("(?<=\\b.)(.*?)\\b", "\\L\\1", text, perl=TRUE)

[1] "This String Is a test. Trying To find a way to do This."

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • How very pretty, thank you!! I guess i'll take this opportunity to ask if you would happen to know an online resource with comprehensive list of regex syntax in R. – Ankhnesmerira May 18 '18 at 03:39
  • 1
    Any good regex resource will help you with R regex. Actually, Stack Overflow is a very good resource for this. – Tim Biegeleisen May 18 '18 at 03:44
0

There should be some pretty way to do this however, one way is by splitting each word and lowering all the characters of the word except the first one and then paste the string back.

paste0(sapply(strsplit(text, " ")[[1]], function(x) 
 paste0(substr(x, 1, 1),tolower(substr(x, 2, nchar(x))))), collapse = " ")

#[1] "This String Is a test. Trying To find a way to do This."

Detailed step by step explanation :

strsplit(text, " ")[[1]]

#[1] "This"   "String" "IS"     "a"      "tESt."  "TRYING" "TO"     "fINd"  
# [9] "a"      "waY"    "to"     "do"     "ThiS." 

sapply(strsplit(text, " ")[[1]], function(x) 
         paste0(substr(x, 1, 1),tolower(substr(x, 2, nchar(x)))))

#   This   String       IS        a    tESt.   TRYING       TO     fINd 
#  "This" "String"     "Is"      "a"  "test." "Trying"     "To"   "find" 
#       a      waY       to       do    ThiS. 
#     "a"    "way"     "to"     "do"  "This." 


paste0(sapply(strsplit(text, " ")[[1]], function(x) 
  paste0(substr(x, 1, 1),tolower(substr(x, 2, nchar(x))))), collapse = " ")

#[1] "This String Is a test. Trying To find a way to do This."
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213