Custom Functions

The main goal of class was to introduce you to the function() function which allows us to create new functions.

The code we produced in class can be downloaded and reviewed here: Code-Day10.R

Consider two examples:

# A simple function to find the maximum value of a numeric 
# vector (without NAs)

my_max <- function(input) {

	output <- sort(input, decreasing = TRUE)[1]
	return(output)

}

x <- 10:-10

x

my_max(input = x)

… and …

# A function to compute the standard deviation of an arbitrary 
# numeric input vector that gives user the option to choose between 
# the sample and population variants (the default returns the
# standard variation of a sample)

my_sd <- function(input, population = FALSE) {

	n <- length(input)
	x_bar <- mean(input)

	if (population == FALSE) {

		output <- sqrt(sum((input - x_bar)^2)/(n-1))
		return(output)

	} else {

	 	output <- sqrt(sum((input - x_bar)^2)/n)
	 	return(output)

	}

}

# Try it out and compare to canned sd() function

x <- rnorm(n = 10, mean = 0, sd = 1)

x

sd(x)

my_sd(input = x)

my_sd(input = x, population = TRUE)