Functions are stored as R objects with the class function
Functions can be:
function( arglist ) expr
return(value)
#of
f <- function(arglist) {
## Body
}
where:
Ex: arg1, arg2 = 1, arg3 = 'Nico', arg4 = NULL, …
Arguments can be matched positionally or by name.
Arguments mappings works as follow:
All the below function calls are equivalent:
mean(x=data,na.rm=FALSE)
mean(na.rm=FALSE,x=data)
mean(data,na.rm=FALSE)
mean(na.rm=FALSE,data)
To get the arguments of a function you can use the args function:
args(data.frame)
function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,
stringsAsFactors = default.stringsAsFactors())
NULL
Arguments to functions are evaluated lazily (ie only when needed).
f = function(x, y) {
return(x*2)
}
f(2)
[1] 4
f = function(x, y) {
print(x)
print(y)
}
f(2)
[1] 2
Error in print(y) : argument "y" is missing, with no default
Notice that the error occurs only when the y argument is needed (ie interpreted)
The … argument indicates a variable number of arguments.
This special argument is used :
myPlot = function(x, y, type = "l", ...) {
plot(x, y, type = type, ...)
}
Any arguments that appear after it must be named explicitly and cannot be partially matched.
The return value of a function is:
f = function(x, y) {
return(x*2)
}
is equivalent to:
f = function(x, y) {
x*2
}
is equivalent to:
f = function(x, y) {
return(x*2)
x*4 # This statement will be skipped
}
Typically, a function is defined in the global environment, so that the values of free variables are just found in the user’s workspace
In this case the environment in which a function is defined is the body of another function! ????
Just use the question mark ? to obtain the documentation on a function
?data.frame
Use the str function
Example:
str(vector)
function (mode = "logical", length = 0L)
where:
Just type the function:
Example with the function ddply from plyr
library(plyr)
> ddply
function (.data, .variables, .fun = NULL, ..., .progress = "none",
.inform = FALSE, .drop = TRUE, .parallel = FALSE, .paropts = NULL)
{
if (empty(.data))
return(.data)
.variables <- as.quoted(.variables)
pieces <- splitter_d(.data, .variables, drop = .drop)
ldply(.data = pieces, .fun = .fun, ..., .progress = .progress,
.inform = .inform, .parallel = .parallel, .paropts = .paropts)
}
<environment: namespace:plyr>
where:
To avoid the below message (function)
Error: could not find function "...."
load the package that contains the function
require(myPackage)
with R - Require or R - Library