```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` The purpose of the base `apply` family of functions is to SIMPLIFY loops. ## loop approach ```{r} numSimulations <- 10000 ptm <- proc.time() results <- NULL for(iS in 1:numSimulations){ temp <- rnorm(100, 0, 1) results <- rbind(results, c(simNumber = iS, mean = mean(temp), min = min(temp), max = max(temp))) } (loopTime <- proc.time() - ptm) ``` ## apply approach - "apply" function ```{r} ptm <- proc.time() simulation <- function(ID){ temp <- rnorm(100, 0, 1) c(simNumber = ID, mean = mean(temp), min = min(temp), max = max(temp)) } results <- sapply(1:numSimulations, simulation) results <- t(results) (applyTime <- proc.time() - ptm) ``` But this is misleading; the bottleneck in the loop is that the array is being continuously copied and memory reallocated. If instead we allocate the memory initially, then the times become quite close. ```{r} ptm <- proc.time() results <- matrix(0, nrow = numSimulations, ncol = 4) for(iS in 1:numSimulations){ temp <- rnorm(100, 0, 1) results[iS,] <- c(simNumber = iS, mean = mean(temp), min = min(temp), max = max(temp)) } (loopTime2 <- proc.time() - ptm) ``` ### lapply and sapply `lapply` takes a vector or list (incl. data.frame) and returns list. `sapply` does the same but returns a simplified structure. ```{r} myList <- list(a = c(1,2,3,4,5), b = c(6,7,8,9,10), c = c(11,12,13,14,15)) fun_item1 <- function(data1, data2){ data1 } fun_type1 <- function(data1) { list(typeof(data1), data1) } lapply(myList, mean) sapply(myList, mean) myVector <- 0:10 lapply(myVector, `^`, 2) sapply(myVector, `^`, 2) myDF <- data.frame(names = c("ann","bob","corinne"), salary = c(15000, 25000, 150000), age = c(50, 40, 60)) lapply(myDF, mean) sapply(myDF, mean) ``` ### vapply `vapply` works on vectors, returns an array, requires FUN.VALUE ```{r} myStats <- function(data){ c(mean=mean(data), min=min(data), max=max(data)) } vapply(myList, myStats, FUN.VALUE = c(Avg = 0, minValue = 0, maxValue = 0)) ``` ### apply `apply` works on the margin of an array ```{r} myArray <- matrix(1:12, ncol=3) apply(myArray, 1, sum) apply(myArray, 2, sum) ``` ### tapply `tapply` uses factors instead of margins ```{r} myVector <- 1:12 myFactors <- rep(c("a","b"), c(5,7)) tapply(myVector, myFactors, min) ``` ### mapply `mapply` works where functions require more than one argument ```{r} mapply(`^`, 1:4, 2:5) ```

This site uses Just the Docs, a documentation theme for Jekyll.