Little useless-useful R function
[This article was first published on R – TomazTsql, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Nothing spectacular, but yet interesting little useless R function for playing with strings and chars.
Converting Sentence case text to mixture of all and small caps resulting in sentence in mixed case.
For example:
"This is useless R Function that seems to exists."
to:
"This is UsEleSS r FuNcTion THaT SeEms To ExIsTS."
And many other mixture of cases. So by calling this function, the results will give you the mixed cases string.
MixedCases <- function(stavek){
nov_stavek = ""
cifra = 0
crka = ""
is.upper <- "[A-Z]"
is.lower <- "[a-z]"
for (crka in strsplit(stavek, "")[[1]]){
if (nchar(nov_stavek)<2){
random_stevilka = sample(0:1, 1, replace=TRUE)
if (random_stevilka == 0){
nov_stavek = paste(nov_stavek,toupper(crka), sep = "")
}
else {
nov_stavek = paste(nov_stavek,tolower(crka), sep = "")
}
}
else{
if(( grepl(pattern = is.upper, x=(strsplit(nov_stavek,"")[[1]][(cifra-2)])) &
grepl(pattern = is.upper, x=(strsplit(nov_stavek,"")[[1]][(cifra-1)])) |
grepl(pattern = is.lower, x=(strsplit(nov_stavek,"")[[1]][(cifra-2)])) &
grepl(pattern = is.lower, x=(strsplit(nov_stavek,"")[[1]][(cifra-1)])) ) == TRUE){
if ( grepl(pattern = is.upper, x=(strsplit(nov_stavek,"")[[1]][(cifra-1)])) ) {
nov_stavek = paste(nov_stavek, tolower(crka), sep = "")
}
else {
nov_stavek = paste(nov_stavek, toupper(crka), sep = "")
}
}
else {
random_stevilka = sample(0:1, 1, replace=TRUE)
if (random_stevilka == 0){
nov_stavek = paste(nov_stavek, toupper(crka), sep = "")
}
else {
nov_stavek = paste(nov_stavek, tolower(crka), sep = "")
}
}
}
#cifra = cifra + 1
}
return(nov_stavek)
}
Talk about useless functions 
Code is also available at Github. Feel free to improve it with even more wackiness
Happy Rrrring 
To leave a comment for the author, please follow the link and comment on their blog: R – TomazTsql.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.