Site icon R-bloggers

Exercise 7: R string processing

[This article was first published on R programming tutorials and exercises for data science and mathematics, 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.

Find a function FUN that leads to the following output:

FUN("mile")
## [1] "e" "i" "l" "m"
FUN("lime")
## [1] "e" "i" "l" "m"
FUN("camel")
## [1] "a" "c" "e" "l" "m"
FUN(paste(sample(letters), collapse = ""))
##  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m"
## [14] "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z"

Hint: aim to keep the answer simple. The main logic of the function can often be summarized in a single line of R code.

< details> < summary> Answer: click to reveal

We can write the function as follows:

  FUN <- function(x) {
    return(sort(strsplit(x, split = "")[[1]]))
  }

This function splits the input string into single characters and then performs an alphabetical sort. For example:

  x <- "camel"
  strsplit(x, split = "")
  ## [[1]]
  ## [1] "c" "a" "m" "e" "l"
  sort(strsplit(x, split = "")[[1]])
  ## [1] "a" "c" "e" "l" "m"
To leave a comment for the author, please follow the link and comment on their blog: R programming tutorials and exercises for data science and mathematics.

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.