Introduction to User Defined Functions in R
One can create user defined functions in R Language easily. User-defined functions allow to write/create custom blocks of code to be reused throughout the analysis. The article presents some useful examples of how to write user defined functions in R Language. R language helps to create much more efficient and possibly elegant coding.
Table of Contents
Assigning Function to a Variable
Example 1: Create a simple function and assign the function to a variable name as we do with any other objects.
f <- function(x, y = 0){ z <- x + y z } x = rnorm(10) f(x + y)
Regression Coefficients
Example 2: Given $n\times 1$Â vector of $y$ and matrix of $X$ the $\hat{\beta}=E[X|y] = (X’X)^{-1}X’y$, where $(X’X)^{-1}$Â is generalized invers of $X’X$.
Beta <- function(x, y){ X <- qr(x) qr.coef(X, y) } attach(mtcars) xmat = cbind(1, hp, wt) yvar = mpg regcoef <- Beta(xmat, yvar)
The qr()
function computes the QR decomposition of a matrix. The QR decomposition if used to solve the equation $Ax=b$ for a given matrix $A$, and vector $b$. It is very useful in computing regression coefficients and in applying Newton Raphson’s algorithm.
Removing all Objects from globalenv
Example 3: Create a function capable of removing all objects from the globalenv.
clear <- function(env = globalenv() ){ obj = ls(envir = env) rm(list = obj, envir = env) }
The clear()
function removes all objects from a specified environment and seems to work correctly. However, the clear()
function detects also itself and as a result, it cannot be reused without redefining the function again.
The clear()
function can be improved to keep the function clear()
when all other objects are deleted.
clear <- function(env = globalenv()){ objects <- objects(env) objects <- objects[objects != "clear"] rm(list = objects, envir = env) invisible(NULL) }
Computing Measure of Central Tendency
Example 4: Create a function that can compute some basic Measure of Central Tendency.
center = function(x, type){ switch(type, mean = mean(x), median = median(x), trimmed = mean(x, trim = 0.1)) } attach(airquality) center(Temp, "mean") # for calcualtion of mean center(Temp, "median") # for calculation of median center(Temp, "trimmed") # for calculation of trimmed mean
Note that the user-defined functions in R can incorporate conditional statements, loops, and other functionalities to perform more advanced tasks. They can also have default parameter values for added flexibility.