Skip to Content
R in a Nutshell
book

R in a Nutshell

by Joseph Adler
January 2010
Beginner
634 pages
19h 50m
English
O'Reilly Media, Inc.
Content preview from R in a Nutshell

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] 11

If 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.
Start your free trial

You might also like

R in a Nutshell, 2nd Edition

R in a Nutshell, 2nd Edition

Joseph Adler
The Big R-Book

The Big R-Book

Philippe J. S. De Brouwer
R Packages

R Packages

Hadley Wickham

Publisher Resources

ISBN: 9781449377502Supplemental ContentErrata Page