1

I'm building a shiny app and in my app the user gives as input a string such as the following:

cats,dogs,birds,cows

So, several words separated by commas, with no spaces. The thing is I want to capitalize each of those words and I can only do it by making R see the string as a group of strings, so the result of the capitalization should be:

Cats,Dogs,Birds,Cows

I really don't know how to do this, and the problem is that my string isn't even a vector because it is coded as such:

unlist(strsplit(input, ",")))

I'm sorry if this was confusing and thank in advance for any answer

tadeufontes
  • 443
  • 1
  • 3
  • 12
  • There are several ways to do this. You may want to check a previous question: https://stackoverflow.com/questions/6364783/capitalize-the-first-letter-of-both-words-in-a-two-word-string – Zhiqiang Wang Oct 20 '19 at 23:36

1 Answers1

2

One possibility could be:

x <- c("cats,dogs,birds,cows", "cats,dogs,birds")
sapply(strsplit(x, ",", fixed = TRUE), 
       function(x) paste0(tools::toTitleCase(x), collapse = ","))

[1] "Cats,Dogs,Birds,Cows" "Cats,Dogs,Birds" 

And there is also a handy library called snakecase:

to_upper_camel_case(x, sep_out = ",")

[1] "Cats,Dogs,Birds,Cows" "Cats,Dogs,Birds" 
tmfmnk
  • 38,881
  • 4
  • 47
  • 67