Functions in R

A function is a block of organized statements to perform a required task. Functions are created using function() and are stored as R objects. They are R objects of class "function". Functions in R are "first class objects" and can be passed as arguments to other functions and can be nested, so we can have functions inside functions.


fcn <- function(){
## do something here
    }

Let's go over some super simple examples


# Write a function that tests if a vector x is longer than a vector y.
test <- function(x,y){
    ifelse(length(x) > length(y),'TRUE', 'FALSE')
    }

# Let x and y be two arbitrary vectors
x <- c(2,3,5,9,10)
y <- c(3,2,1,2.3,5.9,16)
test(x,y)
 

# Write a function that approximates this Euler's number e

f <- function(n){
x <- rep(0,n)
for(i in 0:n){
    x[i+1] <- 1/factorial(i)
    }
    return(sum(x))
    }
f(100)
 

# Write a function to solve the log maximum likelihood function of a normal distribution
# Find the mean (mu), and standard deviation (sigma). We supply -f since we want to maximize
# We use the  optim()  function to find to do the optimization.

f <- function(parameters,x){
    n = nrow(x)
    pi = 3.14
    mu = parameters[1]
    sigma = parameters[2]
    -((-n/2)*log(2*pi*sigma^2) - (1/(2*sigma^2))*sum((x-mu)^2))
    }

    # Set the initial values of mu and sigma. I will set them: mu = 1, sigma = 1.
    set.seed(12345)
    xx <- matrix(rnorm(100, 2, 5), ncol = 1)
    optim(c(mu = 2,sigma = 2), fn=f, x = xx)$par