Defining a function

In general, functions are objects, so we assign them to variable names with <-. The function function tells R you are about to define a function. The general form of a function definition looks like this:

my_function <- function(VARIABLE_NAME){
  perform operations on VARIABLE_NAME and calculate VALUE
  VALUE
}

The functions you define can have multiple arguments as well as default values. For example, we can define a function that computes either the arithmetic or geometric average depending on a user defined variable like this:

avg <- function(x, arithmetic = TRUE){
  n <- length(x)
  ifelse(arithmetic, sum(x)/n, prod(x)^(1/n))
}

Instruction

# Create an avg function. avg <- function(x, arithmetic = TRUE){ n <- length(x) ifelse(arithmetic, sum(x)/n, prod(x)^(1/n)) } # Use an avg function to find the average value in 1:5. avg(1:5)

Previous: 2-4 | any(), all()

Next: 2-6 | For-Loop

Back to Main