1 min read

Exercise 7: R string processing

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.

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"

For a full collection of R programming tutorials and exercises visit my website at codeRtime.org and the codeRtime YouTube channel.