1 min read

Exercise 3: R numeric calculations

Find a function FUN that leads to the following output:

FUN(pi) - FUN(exp(1))
## [1] 1

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(floor(x))
  }

The R function floor returns the largest integer not greater than the input argument:

  pi
  ## [1] 3.141593
  FUN(pi)
  ## [1] 3
  exp(1)
  ## [1] 2.718282
  FUN(exp(1))
  ## [1] 2

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