Review of functions

2026-01-15

Functions in R

  • We use functions all the time

  • What if there isn’t a built-in or package function?

  • Idea: avoid repetitive coding (errors, hard to maintain)

  • Instead:

  • Extract common operations
  • Wrap in a function
  • Reuse

Basic Structure of a function

  • Name

  • Input arguments

    • names
    • default value
  • Body

  • Output values

A first function

mymean <- function(x) {
  avg <- sum(x)/length(x) # body

  return(avg) # return value - alternatively we could just write `avg`
}

mymean(1:15)
mymean(c(1:15, NA))

we want to deal with missing values more gracefully

Defaults & Conditionals

Parameters can have default values. Those values are included in the function specification

mymean <- function(x, na.rm = F) {
  # If na.rm is T, delete the missing value from x
  if (na.rm) x <- na.omit(x)
  return(sum(x)/length(x))
}


mymean(1:15)
mymean(c(1:15, NA), na.rm=TRUE) 

Conditionals

if (condition) { # only one set of commands  
  statement      # is executed depending on 
} else {         # whether condition is true
  statement      # or false
}
  • Condition is a logical value (TRUE or FALSE), i.e. has to be of length 1

  • Use & and | to combine several conditions

  • ! negates a condition (!FALSE is TRUE)

Conditionals - if()

If statement block diagram

Conditionals - ifelse

If-else statement block diagram

Function Writing

  • Start simple, then extend

  • Test out each step

  • Don’t try too much at once

Your Turn

  • Write a function sd that computes the standard deviation of x “from scratch”. Include a parameter na.rm in it

  • \(L(\lambda; x) = -n\lambda + log(\lambda) \cdot\sum x_i\) is the log likelihood function of a Poisson variable x with parameter \(\lambda > 0\)

    • Write a function loglikpois with parameters lambda and x (a vector) that computes the log likelihood value for lambda given observations x.
    • Make sure to check that lambda is positive; return an error message (using stop()) if it is not.
    • Plot the likelihood values for lambda between 0 and 10 for x = c(1, 3, 2, 3, 0, 1, 0, 1, 3, 3)

Good Practice

  • Use tabs to structure blocks of statements

  • Build complex blocks of codes step by step

    • A function should complete one task
    • Chain multiple functions together with a meta-function for more complex tasks
  • # write comments!

Anonymous functions

  • also called lambda expressions

  • have the form

    • function (x) do something in one line or
    •   function (x) {
          do 
          something
          in 
          multiple
          lines
        }
  • created on-the-fly, not re-used anywhere else, not assigned a name

Questions?