rtouppertolower

capitalize last letter of a single word


In R trying to write a function that takes the word MarsuPial and results in marsupiaL.

current code

mycap <- function(mystr = "") {
  mystr <- tolower(mystr)
  a <- substr(mystr, 1, 1)
  b <- substr(mystr, 2, nchar(mystr))
  paste(tolower(a), b, sep = "")
}

Solution

  • You can use substr<- to capitalise the last character.

    mycap <- function(mystr = "") {
      mystr <- tolower(mystr)
      n <- nchar(mystr)
      substr(mystr, n, n) <- toupper(substr(mystr, n, n))
      return(mystr)
    }
    
    mycap('MarsuPial')
    #[1] "marsupiaL"
    mycap('dummy')
    #[1] "dummY"