Search code examples
rreplaceuppercaselowercasecapitalization

How to capitalize all but some letters in R


I have a dataframe in R with a column of strings, e.g. v1 <- c('JaStADmmnIsynDK', 'laUksnDTusainS')

My goal is to capitalize all letters in each string except 's', 't' and 'y'.

So the result should end up being: 'JAStADMMNIsyNDK' and 'LAUKsNDTUsAINS'.

Thus not changing any of the said letters: 's', 't' and 'y'.

As of now I do it by simply having 25x

levels(df$strings) <- sub('n', 'N', levels(df$strings))

But that seems to be overkill! How can I do this easily in R?


Solution

  • Try

    v2 <- gsub("[sty]", "", paste(letters, collapse="")) 
    chartr(v2, toupper(v2), v1)
    #[1] "JAStADMMNIsyNDK" "LAUKsNDTUsAINS" 
    

    data

    v1 <- c("JaStADmmnIsynDK", "laUksnDTusainS")