2 min read

Exercise 2: R vector operations

Find a function FUN that leads to the following output:

x <- sample(1:10)
FUN(x) - FUN(-x)
##  [1] 11 11 11 11 11 11 11 11 11 11

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 1: click to reveal

We can write the function as follows:

  FUN <- function(x) {
    return(sort(x))
  }

Based on this definition of FUN we get:

  FUN(x)
  ##  [1]  1  2  3  4  5  6  7  8  9 10
  FUN(-x)
  ##  [1] -10  -9  -8  -7  -6  -5  -4  -3  -2  -1

which fulfills the puzzle condition:

  FUN(x) - FUN(-x)
  ##  [1] 11 11 11 11 11 11 11 11 11 11
Answer 2: click to reveal

Another possible definition of FUN that builds on Puzzle 1 is:

  FUN <- function(x) {
    return(rep(max(x), times = length(x)))
  }

Based on this definition of FUN we get:

  FUN(x)
  ##  [1] 10 10 10 10 10 10 10 10 10 10
  FUN(-x)
  ##  [1] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1

which fulfills the puzzle condition:

  FUN(x) - FUN(-x)
  ##  [1] 11 11 11 11 11 11 11 11 11 11

As we have seen in exercise 1 the max can also be replaced with min and the result still holds:

  FUN <- function(x) {
    return(rep(min(x), times = length(x)))
  }
  FUN(x) - FUN(-x)
  ##  [1] 11 11 11 11 11 11 11 11 11 11

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