Home > database >  Convert the lowercase string to uppercase string based in underline order
Convert the lowercase string to uppercase string based in underline order

Time:02-16

I have a vector my.names with strings:

my.names<-c("Mahal_Nossasenhoraaparecida1_419","Innovatech_Bonito_117","Novo_Oeste_Morrodoindaia_570n")
#[1] "Mahal_Nossasenhoraaparecida1_419" "Innovatech_Bonito_117"           
#[3] "Novo_Oeste_Morrodoindaia_570n"

I'd like to convert using something like toupper in:

my.names.trans1
#[1] "Mahal_NOSSASENHORAAPARECIDA1_419" "Innovatech_BONITO_117"           
#[3] "Novo_Oeste_MORRODOINDAIA_570N"

But, I have one problem. I don't have position stability in the string and my reference is just only that I need to apply the uppercase before the last underline (_) and if have any letter at the end of the string too.

Please, any help with it?

CodePudding user response:

We can use sub here with the Perl extension turned on, to convert the last two terms to uppercase.

my.names <- c("Mahal_Nossasenhoraaparecida1_419",
              "Innovatech_Bonito_117",
              "Novo_Oeste_Morrodoindaia_570n")
my.names <- sub("([^_] _[^_] $)", "\\U\\1", my.names, perl=TRUE)
my.names

[1] "Mahal_NOSSASENHORAAPARECIDA1_419" "Innovatech_BONITO_117"
[3] "Novo_Oeste_MORRODOINDAIA_570N"
  • Related