El Dude
El Dude

Reputation: 5618

replace substring in R

I have a list of strings, for which I must change a certain substring from caps to lowcaps. How can I implement this efficiently in R?

Here's a sublist:

>head(ID)

"1007_PM_S_AT"
"1053_PM_AT"  
"117_PM_AT"   
"121_PM_AT"    
"1255_PM_G_AT" 
"1294_PM_AT" 

I need to change everything after PM to lowercase.

Upvotes: 1

Views: 1016

Answers (1)

Stedy
Stedy

Reputation: 7469

One option, would be to wrap tolower() in a sub() call

R> test <- c("1007_PM_S_AT", "1053_PM_AT", "117_PM_AT", "121_PM_AT", "1255_PM_G_AT", "1294_PM_AT")
R> sub("pm", "PM", tolower(test))
[1] "1007_PM_s_at" "1053_PM_at"   "117_PM_at"    "121_PM_at"    "1255_PM_g_at" "1294_PM_at"  

Another alternative (probably not as good here) that can be useful is to use the replacement function regmatches<-.

matches <- gregexpr('(?<=PM)(.+)', test, perl=TRUE)              # match the string after PM
regmatches(test, matches) <- tolower(regmatches(test, matches))  # replace with lower case

Upvotes: 6

Related Questions