# Functions.r -- basic tutorial on functional programming in R # CSE 446 # Author: Daryl Hansen # Say we have a function that does something. For simplicity, it adds two numbers # (in reality we'd use the + operator if that's all we wanted) plus <- function(a, b) { return(a+b) } plus(5,3) # We can change the arguments by wrapping it in another function, like so: add.seven <- function(a) { return(plus(a,7)) } multiply.and.add <- function(a, b, n) { return(plus(n*a, n*b)) } add.seven(13) multiply.and.add(7, 8, 2) # We can also pass in functions as arguments to other functions fun.max <- function(v, w, fun) { first <- max(v) second <- max(w) return(fun(first, second)) } x <- c(1,3,5,7) y <- c(-1, 0, 1, 2) fun.max(x, y, plus) # Once again reducing the number of arguments add.max.y <- function(v) { return(fun.max(v, y, plus)) } add.max.y(x) # Notice how the behavior of max.and.half.y changes when we change y # (despite y not being one of its arguments) y <- c(1,2,4) add.max.y(x) # We can then use this to manipulate rows of a matrix: X <- matrix(c(0,0,0,1,0,1,0,2,5), 3, 3) # 'apply' takes a matrix, a dimension, and a function # if dim=1, it applies the function to each row of the matrix # if dim=2, it applies it to each column apply(X, 1, add.max.y) apply(X, 2, add.max.y) # 'apply' is much faster than using a loop: bigX = matrix(1:500000, 50000, 10) # Compare the runtime of this line (~1 second on my machine) mean(apply(bigX, 1, add.max.y)) # with this equivalent loop: (~7 seconds on my machine) z = c() for (i in 1:50000) { z[i] = add.max.y(bigX[i,]) } mean(z)