You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Abish Pius edited this page Feb 28, 2020
·
1 revision
Functions
The R function called function() tells R you are about to define a new function.
Functions are objects, so must be assigned a variable name with the arrow operator.
The general way to define functions is: (1) decide the function name, which will be an object, (2) type function() with your function's arguments in parentheses, (3) write all the operations inside brackets.
Variables defined inside a function are not saved in the workspace.
Code: Functions Example
# example of defining a function to compute the average of a vector xavg<-function(x){
s<- sum(x)
n<- length(x)
s/n
}
# we see that the above function and the pre-built R mean() function are identicalx<-1:100
identical(mean(x), avg(x))
# variables inside a function are not defined in the workspaces<-3
avg(1:10)
s# the general form of a functionmy_function<-function(VARIABLE_NAME){
performoperationsonVARIABLE_NAMEandcalculateVALUEVALUE
}
# functions can have multiple arguments as well as default valuesavg<-function(x, arithmetic=TRUE){
n<- length(x)
ifelse(arithmetic, sum(x)/n, prod(x)^(1/n))
}