Find a function FUN
that leads to the following output:
x <- 1:10
FUN(x) - FUN(-x)
## [1] 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(max(x))
}
Based on this definition of FUN
we get:
FUN(x)
## [1] 10
FUN(-x)
## [1] -1
We finally confirm that this function solves the puzzle:
FUN(x) - FUN(-x)
## [1] 11
Answer 2: click to reveal
Another solution to this puzzle is:
FUN <- function(x) {
return(min(x))
}
Based on this definition of FUN
we get:
FUN(x)
## [1] 1
FUN(-x)
## [1] -10
We confirm that this function solves the puzzle:
FUN(x) - FUN(-x)
## [1] 11
For a full collection of R programming tutorials and exercises visit my website at codeRtime.org and the codeRtime YouTube channel.