Home > OS >  Comparing Two Strings And Changing Case of Differing Characters
Comparing Two Strings And Changing Case of Differing Characters

Time:06-24

I'm trying to compare a "master" string to a list of strings using R. Based on this comparison, I'd like all characters in the string which differ from the master string changed to lowercase.

For example: the master string is "AGG". The list of strings being compared to is ["ATT", "AGT"]. I want to return ["Att","AGt"]. Order also matters. So ["GGA"] should return ["gGa"].

Any help would be greatly appreciated!

CodePudding user response:

You could turn all characters into lowercase first, and turn those characters in the master string back to uppercase.

master <- "AGG"
x <- c("ATT", "AGT", "GGA")

chartr(tolower(master), master, tolower(x))
# [1] "Att" "AGt" "GGA"

Update: If you want to compare x and master character-by-character, try this:

sapply(strsplit(x, ""), \(char) {
  paste(ifelse(char == strsplit(master, "")[[1]], char, tolower(char)), collapse = "")
})

# [1] "Att" "AGt" "gGa"
  • Related