Writing your own functions

Theoretical and Empirical Research Methodology · Implementation Lab 3

Prof. Dr. Claudius Gräbner-Radkowitsch

Europa-University Flensburg, Department of Pluralist Economics

2 October 2026

Writing our own functions

By your request: a short recap

The conceptual background: Gräbner-Radkowitsch (2026)

A function is an object that can be called

  • In R, everything that exists is an object — functions included
  • A function can be called: takes an input, applies a routine, and returns an output

2 → log() → 0.6931472

  • Calling it means: its name, then brackets with the arguments inside
log(2)       # prefix form: the name first, arguments in brackets

Mandatory and optional arguments

  • Mandatory arguments usually the input
  • Optional arguments: how the routine is executed
    • Always come with a default
sum(1, 2, 3, 4, NA)                 # NA
sum(1, 2, 3, 4, NA, na.rm = TRUE)   # 10
  • na.rm defaults to FALSE → a missing value leads to NA as output
  • help(sum): tells which arguments exist, and their defaults

Optional arguments are passed by their name — which is also what makes a function call readable

How to define a function

pythagoras <- function(cathetus_1, cathetus_2){
  hypo_squared <- cathetus_1**2 + cathetus_2**2
  hypotenuse <- sqrt(hypo_squared)
  return(hypotenuse)
}

pythagoras(2, 4)  # 4.472136
  • the name and <-
  • function(...) with the arguments
  • the braces: the function body
  • return(): the output
  • Objects created in the body live in the function’s own environment
    • hypo_squared does not exist outside

A feature, not a bug: it keeps your workspace clean

Let’s write two functions

We build them live, step by step — the written documentation is on the session page

① Fahrenheit → Celsius · ② a summary function for a vector

References

Gräbner-Radkowitsch, C. (2026) “Object Types in R I: Functions” C. Gräbner-Radkowitsch (ed.), Method and Inquiry, available at https://euf-methodology-hub.netlify.app/resources/r-object-types-i-functions.