Skip to content

Building functions

Lucy M Chang edited this page Apr 5, 2018 · 22 revisions

Building a function

So far, we've been using functions that are built into either R or the packages we've loaded. However, you can write your own functions to make code way easier to run. Remember that functions take arguments and return values.

There is a function called function() that lets you do this. You give the function a name by assigning it to a variable.

The basic form of a function is:

myfunction <- function(arg1, arg2, ... ){
  object <- actions to perform #saved to an object
  return(object)
}

Inside the function, you must define the arguments (just like in the functions you've already encountered).

Let's make a really simple function to print in the console whatever name you give it as an argument plus a statement about name ownership.

printName <- function(name = "Joe Shmoe"){
  print(name)
  print("That's my name.")
}

So now printName() runs just like any other function already built in. Notice we had set a default value for the argument called "name".

printName()

printName("Mary")

By default, the value the function returns is whatever object is called up last, but you can define a specific output using return().

All the things created inside of a function does not get saved (it all happens internally; temporary variables).

square.it <- function(x) { #x is the argument
    square <- x * x #square is the object
    return(square) #return the object
}

# What happens when you try to recall the variable square?
square

Dummy data

Use simple data to test your code. Also, try to break the function. That is, use extreme cases to make sure it still works properly.

# Try out your custom function!
square.it(5)
square.it(c(1, 4, 2))
square.it("hi")

matrix1 <- cbind(c(3, 10), c(4, 5))
square.it(matrix1)

Checking functions

We've seen print() before: it will return an error if a condition isn't met. Likewise, stop() will exit out of the function can return an error message.

Example:

my.second.fun <- function(matrix, vector) {
    if (dim(matrix)[2] != length(vector)) {
        stop("Can't multiply matrix%*%vector because the dimensions are wrong")
    }
    product <- matrix %*% vector
    return(product)
}

Exercise

Turn the following loop into a function that can take in any matrix, not just occ.

for(i in 1:length(occ)){
  print(sum(occ[i, ])) # row
}

Best practices

  1. Keep it short! Remember you can use them to call other functions! If it gets long, split it up! This helps with readability. Cool fact: updating a single function will update in all other functions that call it.
  2. COMMENT!! Annotate what the inputs are for the function, what the function does, and its output.
  3. Check for errors along the way using print() and stop().
  4. Use dummy data to test your function.