capitalize last letter of a single word

251 Views Asked by At

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 = "")
}
3

There are 3 best solutions below

1
On BEST ANSWER

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"
0
On
mycap <- function(mystr = "") {
  # a: the string without the last character
  a <- substr(mystr, 1, nchar(mystr)-1)

  # b: only the last character 
  b <- substr(mystr, nchar(mystr), nchar(mystr))

  # lower(a) and upper(b)
  paste(tolower(a), toupper(b), sep = "")
}

For your example:

mycap("MarsuPial")
[1] "marsupiaL
0
On

Another option avoiding string subsetting/splitting is to convert the string to an integer vector to reverse the order so that we can use stringr::str_to_title.

library(stringr)
library(dplyr)
mycap <- function(mystr = "") {
    mystr %>% utf8ToInt %>% rev %>% intToUtf8 %>% str_to_title %>% utf8ToInt %>% rev %>% intToUtf8
}

mycap("MarsuPial")
#[1] "marsupiaL"
mycap("dummy")
#[1] "dummY"

Or another fast option is to use stringi::stri_reverse and stringi::stri_trans_totitle

library(stringi)
mycap <- function(mystr = "") stri_reverse(stri_trans_totitle(stri_reverse(mystr)))