Functional Programming

Homework

Homework 1 is assigned and can be found here: http://m497.inqs.info/hw.html

Quarto Documentation

quarto use template inqs909/qs_hw

Quarto Resources

Nested for Loops

  • Nested for Loops

  • while Loops

  • More Examples

  • Vectorized Code

  • Built-in Functions

  • User-built functions

  • apply()

  • lapply()

  • sapply()

Nested for Loops

Nested for loops are for loops within another for loop. You can stack these loops as much as needed. Just make sure the index is different for each loop. The general format for a loop goes as follow:

for (i in vector_1){
  for (ii in vector_2){
    perform task
  }
}

Example

Without using the sd() function, compute the standard deviation for each column of the matrix:

x <- matrix(rnorm(1000), nrow = 10)

\[ s^2 = \frac{1}{n-1}\sum^n_{i=1}(x_i-\bar x)^2 \]

Example

while Loops

  • Nested for Loops

  • while Loops

  • More Examples

  • Vectorized Code

  • Built-in Functions

  • User-built functions

  • apply()

  • lapply()

  • sapply()

while Loops

A while loop is a combination of a for loop and a break statement. The loop will continue indefinitely until a condition becomes false.

# Initial Condition
condition <- starting TRUE condition

while (condition){
  perform task
  condition <- update condition
}

Example

Simulate from a \(N(0,1)\) distribution until you have 50 positive numbers.

Code
n <- 0
pos_num <- c()

while (n < 51){
  x <- rnorm(1)
  if (x > 0) {
    pos_num <- c(pos_num, x)
    n <- n + 1
  }
}

pos_num

Example

Find the value of \(x\) where the function \(y=1/x\) relative converges (\(\frac{|y_{old}-y_{new}|}{y_{old}}\)) at a level of \(10^-6\) as \(x\rightarrow \infty\).

Code
diff <- 10
x <- 2
y_old <- 1
while (diff > 1e-6){
  y_new <- 1 / x
  diff <- abs(y_old - y_new) / y_old
  x <- x + 1
  y_old <- y_new
}

Example

Simulate from a \(Binom(1,.2)\) distribution until the sum of the random variables generated is 50.

Code
sum_bin <- 0
x <- c()
while (sum_bin <51) {
  x <- c(x, rbinom(1, 1, 0.2))
  sum_bin <- sum(x)
}
sum_bin
length(x)

Example

More Examples

  • Nested for Loops

  • while Loops

  • More Examples

  • Vectorized Code

  • Built-in Functions

  • User-built functions

  • apply()

  • lapply()

  • sapply()

Example

Using the code below:

x <- rnorm(5000)

Create a new vector containing all the positive values of x. The new vector should be less than 5000.

Answer:

Code
nn <- length(x)
pos <- c()
for (i in 1:nn){
  if (x[i] > 0) {
    pos <- c(pos, x[i])
  }
}
pos

Example

\[ f(x,y) = x^2 + y^2 + \ln(x+y) \]

Find all the values of \(f(x,y)\) for every combination of \(x \in \{1, 8, 13, 25, 42, 67, 95\}\) and \(y \in \{6, 12, 18, 52, 61, 79, 83\}\)

Store values in a \(7\times 7\) matrix.

Answer:

Code
x <- c(1, 8, 13, 25, 42, 67, 95)
y <- c(6, 12, 18, 52, 61, 79, 83)
res <- matrix(nrow = 7, ncol = 7)
colnames(res) <- as.character(x)
rownames(res) <- as.character(y)

for (i in 1:7){
  for (ii in 1:7){
    res[ii,i] <- x[i]^2 + y[ii]^2 + log(x[i] + y[ii])
  }
}
print(res)

Vectorized Code

  • Nested for Loops

  • while Loops

  • More Examples

  • Vectorized Code

  • Built-in Functions

  • User-built functions

  • apply()

  • lapply()

  • sapply()

Vectorized Code

Vectorized code is programming where functions or processes are applied to vectors instead of individual values.

Indicating a loop is not necessary to apply a function to each individual element in a vector.

Vectorized Code

Mathematical Operations are conducted element-wise to 2 or more vectors

Element 1 in vector x is applied to element 1 in vector y

Example

Example

Built-in Functions

  • Nested for Loops

  • while Loops

  • More Examples

  • Vectorized Code

  • Built-in Functions

  • User-built functions

  • apply()

  • lapply()

  • sapply()

Built-in Functions

There are several available functions in R to conduct specific statistical methods or tasks

Help Documentation

Section Description
Description Provides a brief introduction of the function
Usage Provides potential usage of the function
Arguments Arguments that the function can take
Details An in depth description of the function
Value Provides information of the output produced by the function
Notes Any need to know information about the function
Authors Developers of the function
References References to the model and function
See Also Provide information of supporting functions
Examples Examples of the function

Generic Functions

Several R objects have a known class attached to it. A specialized object designed to be read by generic functions, such as summary() and plot().

For example, the summary() is a generic for several types of functions: summary.aov(), summary.lm(), summary.glm(), and many more.

Commonly-used Function

Functions Description
aov() Fits an ANOVA Model
lm() Fits a linear model
glm() Fits a general linear model
t.test() Conducts a t-test

User-built functions

  • Nested for Loops

  • while Loops

  • More Examples

  • Vectorized Code

  • Built-in Functions

  • User-built functions

  • apply()

  • lapply()

  • sapply()

User-built functions

  • Functions created by the user for analysis

  • Needs to be ran once to the R environment

  • Will be lost when R session is closed

Anatomy

name_of_function <- function(data_1, data_2 = NULL, 
                             argument_1, argument_2 = TRUE, argument_3 = NULL,
                             ...){
  # Conduct Task
  # Conduct Task
  output_object <- Tasks
  return(output_object)
}
  • function: used to construct the function

  • data1: first data argument that needs to supplied

  • data2: second data argument that does not need to be supplied

  • argument1: first argument must be supplied to alter function

  • argument2: second argument to alter function, set to TRUE

  • argument3: third argument that does not need to be supplied

  • : additional arguments supplied to other functions

Example

Create a function for

\[ y = \ln(x^2) \]

Example

Create a function for

\[ f(x) = \left\{\begin{array}{cc} x^3 & x<0\\ x^2 + 5 & \mathrm{otherwise} \end{array} \right. \]

Example

Create a function for

\[ f(x,y) = \left\{\begin{array}{cc} x^3 e^y & x<0\ \\ x^2 + 5 + \ln(y) & \mathrm{otherwise} \end{array} \right. \]

Example

Create the function that allows your to compute the z-score of a specific value x using the sampling distribution from a set of data (y vector):

\[ z = \frac{x-\bar y}{\sqrt{s^2_{y}/n_y}} \]

Example

apply()

  • Nested for Loops

  • while Loops

  • More Examples

  • Vectorized Code

  • Built-in Functions

  • User-built functions

  • apply()

  • lapply()

  • sapply()

apply()

The apply function returns a vector, array, or list of values by applying a function to the margins of an array. You will need to specify the following arguments:

  • X: an array to be indexed and applied

  • MARGIN: specifyng which index(es) to subset by

  • FUN: function to be applied

  • : further arguments to be applied to FUN, must be labeled

apply(X, MARGIN, FUN, ...)

Example

Find the standard deviation of all the columns of the following matrix:

Example

Find the \(25th\), \(50th\), and \(75th\) quartiles for each row of the following matrix:

lapply()

  • Nested for Loops

  • while Loops

  • More Examples

  • Vectorized Code

  • Built-in Functions

  • User-built functions

  • apply()

  • lapply()

  • sapply()

lapply()

The lapply function applies a function to all the elements of a vector or matrix, and it will return a list. You will need to specify the following arguments:

  • X: object to be iterated

  • FUN: a function to be applied

  • : further arguments to be passed along to FUN

lapply(X, FUN, ...)

Example

Create a function that returns a labeled list for with the following values: mean, standard deviation, median, max, and min.

sapply()

  • Nested for Loops

  • while Loops

  • More Examples

  • Vectorized Code

  • Built-in Functions

  • User-built functions

  • apply()

  • lapply()

  • sapply()

sapply()

The sapply() function will apply a function to each element of a list or vector, and it will return a simplified object, vector, matrix, or array. The sapply() function uses 4 main arguments:

  • X: a vector or list to be iterated

  • FUN: a function to be applied

  • : arguments passed along to FUN, must be labeled

  • simplify: indicates how to simplify the function, defaults to n-dimensional array based on output

sapply(X, FUN, ..., simplify = TRUE)

Example

Using the vector below, compute the length of each string using sapply and str_length() from stringr

Example

Using the list generated below, compute the mean of each element of the list using sapply.

Example

Using the vector below, use the sapply() to find \(\log(x)\) for each value and return a matrix: