Is there a other version to make the first letter of each string capital and also with FALSE for flac perl?
name<-"hallo"
gsub("(^[[:alpha:]])", "\\U\\1", name, perl=TRUE)
Is there a other version to make the first letter of each string capital and also with FALSE for flac perl?
name<-"hallo"
gsub("(^[[:alpha:]])", "\\U\\1", name, perl=TRUE)
You can try something like:
name<-"hallo"
paste(toupper(substr(name, 1, 1)), substr(name, 2, nchar(name)), sep="")
Or another way is to have a function like:
firstup <- function(x) {
substr(x, 1, 1) <- toupper(substr(x, 1, 1))
x
}
Examples:
firstup("abcd")
## [1] Abcd
firstup(c("hello", "world"))
## [1] "Hello" "World"
As pointed out in the comment, it is now possible to do:
stringr::str_to_title("iwejofwe asdFf FFFF")
stringr
uses stringi
under the hood which takes care of complex internationalization, unicode, etc., you can do:
stri_trans_totitle("kaCk, DSJAIDO, Sasdd.", opts_brkiter = stri_opts_brkiter(type = "sentence"))
There is a C or C++ library underneath stringi
.
In stringr
, there's str_to_sentence()
which does something similar. Not quite an answer to this question, but it solves the problem I had.
str_to_sentence(c("not today judas", "i love cats", "other Caps converteD to lower though"))
#> [1] "Not today judas" "I love cats" "Other caps converted to lower though"
for the lazy typer:
paste0(toupper(substr(name, 1, 1)), substr(name, 2, nchar(name)))
will do too.
I like the "tidyverse" way using stringr with a oneliner
library(stringr)
input <- c("this", "is", "a", "test")
str_replace(input, "^\\w{1}", toupper)
Resulting in:
[1] "This" "Is" "A" "Test"
Often we want only the first letter upper case, rest of the string lower case. In such scenario, we need to convert the whole string to lower case first.
Inspired by @alko989 answer, the function will be:
firstup <- function(x) {
x <- tolower(x)
substr(x, 1, 1) <- toupper(substr(x, 1, 1))
x
}
Examples:
firstup("ABCD")
## [1] Abcd
Another option is to use str_to_title
in stringr
package
dog <- "The quick brown dog"
str_to_title(dog)
## [1] "The Quick Brown Dog"
I was also looking for the answer on this, but the replies did not consider the case of strings starting with numbers or symbols. Also, the question was: "make the first letter of each string capital", not every word.
v = c("123.1 test test", "test", "test test", ". test")
stringr::str_replace(v, "([[:alpha:]])", toupper)
## [1] "123.1 Test test" "Test" "Test test" ". Test"