[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.
            
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:
curve(FUN, from = -2, to = 2, n = 1000) grid()
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 revealWe can write the function as follows:
  FUN <- function(x) {
    return(abs(x) %% 1)
  }
This function returns the fractional part of the absolute value of its input. For example:
FUN(12.345) ## [1] 0.345 FUN(-0.1234) ## [1] 0.1234
FUN can be defined equivalently as:
  FUN <- function(x) {
    return(abs(x) - floor(abs(x)))
  }
To check that this function is indeed a solution to the puzzle we can redraw the plot:
curve(FUN, from = -2, to = 2, n = 1000) grid()
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.
