Returning invisibly
When the main purpose of a function is to generate output, like drawing a plot or printing something in the console, you may not want a return value to be printed as well. In that case, the value should be invisibly returned.
The base R plot function returns NULL
, since its main purpose is to draw a plot. This isn't helpful if you want to use it in piped code: instead it should invisibly return the plot data to be piped on to the next step.
Recall that plot()
has a formula interface: instead of giving it vectors for x
and y
, you can specify a formula describing which columns of a data frame go on the x
and y
axes, and a data
argument for the data frame. Note that just like lm()
, the arguments are the wrong way round because the detail argument, formula
, comes before the data
argument.
plot(y ~ x, data = data)
This exercise is part of the course
Introduction to Writing Functions in R
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Using cars, draw a scatter plot of dist vs. speed
plt_dist_vs_speed <- ___(___ ~ ___, data = ___)
# Oh no! The plot object is NULL
plt_dist_vs_speed