Arguments
A function definition in R includes the names of arguments. Optionally, it may include default values. If you specify a default value for an argument, then the argument is considered optional:
> f <- function(x,y) {x+y}
> f(1,2)
[1] 3
> g <- function(x,y=10) {x+y}
> g(1)
[1] 11If you do not specify a default value for an argument, and you do not specify a value when calling the function, you will get an error if the function attempts to use the argument:[24]
> f(1) Error in f(1) : element 2 is empty; the part of the args list of '+' being evaluated was: (x, y)
In a function call, you may override the default value:
> g(1,2) [1] 3
In R, it is often convenient to specify a variable-length
argument list. You might want to pass extra arguments to another
function, or you may want to write a function that accepts a variable
number of arguments. To do this in R, you specify an ellipsis
(...) in the arguments to the
function.[25]
As an example, let’s create a function that prints the first
argument and then passes all the other arguments to the summary function. To
do this, we will create a function that takes one argument: x. The arguments specification also includes
an ellipsis to indicate that the function takes other arguments. We
can then call the summary function
with the ellipsis as its argument:
> v <- c(sqrt(1:100)) > f <- function(x,...) {print(x); summary(...)} > f("Here is the summary for v.", v, digits=2) [1] "Here is the summary for v." Min. 1st Qu. Median Mean 3rd Qu. ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access