Simulation and Functions

Outline

  1. Simulation
  2. Loops
  3. Functions

Simulation

Why Simulate?

Simulation

Simulation

Simulation

Simulation

Simulation

x <- rnorm(10, 0, 1)
x
##  [1]  1.6400096  1.0361779 -1.1159705 -1.3423796  0.8128874  1.5461313
##  [7] -1.8693206 -0.6347188 -1.1626086 -0.5812986
x <- rnorm(10)
x
##  [1]  0.4819232 -0.2771778 -0.2084614  0.7621179 -1.1332870 -0.2302228
##  [7]  0.5480552 -0.3150096  0.2005406  0.1565243

Setting the random number seed

set.seed(1)
x <- rnorm(10, 0, 1)
x
##  [1] -0.6264538  0.1836433 -0.8356286  1.5952808  0.3295078 -0.8204684
##  [7]  0.4874291  0.7383247  0.5757814 -0.3053884
set.seed(1)
x <- rnorm(10, 0, 1)
x ## Same as before
##  [1] -0.6264538  0.1836433 -0.8356286  1.5952808  0.3295078 -0.8204684
##  [7]  0.4874291  0.7383247  0.5757814 -0.3053884

Simulation

set.seed(1)
y <- rnorm(10, 20, 2)
y 
##  [1] 18.74709 20.36729 18.32874 23.19056 20.65902 18.35906 20.97486 21.47665
##  [9] 21.15156 19.38922
summary(y)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   18.33   18.91   20.51   20.26   21.11   23.19

Simulation - Poisson Distribution

set.seed(1)
y <- rpois(10, 1)    ## Counts with a mean (lambda) of 1
y 
##  [1] 0 1 1 2 0 2 3 1 1 0
y <- rpois(10, 20)    ## Counts with a mean of 20
y 
##  [1] 16 18 19 30 23 16 17 18 18 21

Simulation - Binomial Distribution

set.seed(1)
y <- rbinom(10, 4, 0.5)    ## size=4 and p=0.5
y 
##  [1] 1 2 2 3 1 3 4 2 2 0
mean(y) # n*p
## [1] 2
x <- rbinom(n = 100, size = 5, prob = 0.5)
mean(x)
## [1] 2.49

Simulation - Exponential Distribution

data1 <- rexp(10, rate = 1)
mean(data1)
## [1] 1.669803
data2 <- rexp(100, rate = 1)
mean(data2)
## [1] 0.9870225
data3 <- rexp(1000, rate = 1)
mean(data3)
## [1] 1.026968
var(data3)
## [1] 1.014509

Example 1: flipping coins

What is the probability of flipping \(5\) coins and getting all heads?

Example 1: flipping coins

What is the probability of flipping \(5\) coins and getting all heads?

0.5^(5)
## [1] 0.03125

Example 1: flipping coins

What is the probability of flipping \(5\) coins and getting all heads?

coins <- rbinom(n = 10000, size = 5, prob = 0.5)
mean(coins == 5)
## [1] 0.0325
coins <- rbinom(n = 100000, size = 5, prob = 0.5)
mean(coins == 5)
## [1] 0.03164

Variance of the sample mean

For a set of random variables \(X_1,\ldots,X_n\), each independent with variance \(\sigma^2\), what is the variance of the sample mean?

\[\begin{align*} Var(\bar{X}) &= Var(\frac{1}{n}\sum_{i=1}^n X_i) \\ &= \frac{1}{n^2}\sum_{i=1}^n Var(X_i) \\ &= \frac{n\sigma^2}{n^2} \\ &= \frac{\sigma^2}{n} \end{align*}\]

Example: variance of the sample mean

For a set of random variables \(X_1,\ldots,X_n\), each independent with variance \(\sigma^2\), what is the variance of the sample mean?

We can individually generate data and calculate sample means. But this doesn’t give us information about the variance of these means.

data1 <- rexp(10, rate = 1)
mean(data1)
## [1] 1.489288
data2 <- rexp(100, rate = 1)
mean(data2)
## [1] 0.8978229
data3 <- rexp(1000, rate = 1)
mean(data3)
## [1] 1.028234

Simulating a Linear Model

set.seed(1)
x <- rnorm(100, 0, 1) ## Simulate predictor variable

e <- rnorm(100, 0, 2)  ## Simulate the error term  

y <- 0.5 + 2 * x + e    ## Compute the outcome via the model 
summary(y)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
## -5.4816 -1.1493  0.7582  0.6422  2.3404  6.1534

Simulating a Linear Model

set.seed(1)
y <- 0.5 + 2 * x + e    
plot (x, y) 

Simulating a Linear Model

model <- lm(y~x)
summary(model) 
## 
## Call:
## lm(formula = y ~ x)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -3.754 -1.228 -0.279  1.079  4.692 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   0.4246     0.1940   2.189    0.031 *  
## x             1.9979     0.2155   9.273 4.58e-15 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.926 on 98 degrees of freedom
## Multiple R-squared:  0.4674, Adjusted R-squared:  0.4619 
## F-statistic: 85.99 on 1 and 98 DF,  p-value: 4.583e-15

Simulating a Linear Model

par(mfrow = c(2, 2))
plot(model) 

Simulating Independent samples

set.seed(1)
scores <- rnorm(20, 10, 2)
groups <- rbinom(20, 1, 0.5)
groups 
##  [1] 1 1 1 1 1 1 0 0 1 1 0 1 0 0 0 0 0 1 1 0
boxplot(scores ~ groups)

Simulating Independent samples

shapiro.test(scores)
## 
##  Shapiro-Wilk normality test
## 
## data:  scores
## W = 0.95327, p-value = 0.4195

Simulating Independent samples

t.test(scores ~ groups, var.equal = TRUE)
## 
##  Two Sample t-test
## 
## data:  scores by groups
## t = -0.074459, df = 18, p-value = 0.9415
## alternative hypothesis: true difference in means between group 0 and group 1 is not equal to 0
## 95 percent confidence interval:
##  -1.834543  1.708957
## sample estimates:
## mean in group 0 mean in group 1 
##        10.34651        10.40930

Simulating Independent samples

t.test(scores ~ groups, var.equal = FALSE)
## 
##  Welch Two Sample t-test
## 
## data:  scores by groups
## t = -0.071915, df = 14.06, p-value = 0.9437
## alternative hypothesis: true difference in means between group 0 and group 1 is not equal to 0
## 95 percent confidence interval:
##  -1.934786  1.809200
## sample estimates:
## mean in group 0 mean in group 1 
##        10.34651        10.40930

Functions

Anatomy of a function

function_name <- function(param1, param2 = "default") {
  # Body of the function
  return(output)
}

Consider some examples

Example 1

## Square a number, add 2
square_plus_2 <- function(x) {
  y <- x^2 + 2
  return(y)
}

square_plus_2(4)
## [1] 18
square_plus_2(x = 4)
## [1] 18

Example 1 (Continuation)

## Square a number, add 2
square_plus_2 <- function(x) {
  y <- x^2 + 2
  return(y)
}

square_plus_2(4)
## [1] 18
square_plus_2(10)
## [1] 102
square_plus_2(1:5)
## [1]  3  6 11 18 27

Example 2 (Temperature Conversion)

fahr_to_kelvin <- function(fahr) {
  # function that converts temperature in degrees Fahrenheit to kelvin
  # input: fahr: numeric value representing temp in degrees farh
  # output: kelvin: numeric converted temp in kelvin
  kelvin <- ((fahr - 32) * (5 / 9)) + 273.15
  return(kelvin)
}

fahr_to_kelvin(32)
## [1] 273.15

Temperature Conversion

fahr_to_kelvin <- function(fahr) {
  # function that converts temperature in degrees Fahrenheit to kelvin
  # input: fahr: numeric value representing temp in degrees farh
  # output: kelvin: numeric converted temp in kelvin
  kelvin <- ((fahr - 32) * (5 / 9)) + 273.15
  return(kelvin)
}

fahr_to_kelvin(212)
## [1] 373.15
fahr_to_kelvin(540)
## [1] 555.3722

Example 3 (Return Multiple Values)

my_function <- function(x, y) {         
  w1 <- x + y
  w2 <- x * y
  return(list(w1, w2))
}
 # If we apply the function, we get the following list output:
my_function (x = 5, y = 3) 
## [[1]]
## [1] 8
## 
## [[2]]
## [1] 15

Example 4

x <- c(10, 20, 30, 40, 50)

mean(x)
## [1] 30
sd(x)
## [1] 15.81139

Example 4

my_function <- function(x) {  
  n <- length(x)
  mean <- sum (x) / n 
  sd  <- sqrt(sum((x - mean(x))^2) / (n - 1))
  return(list(mean, sd))
}
 # If we apply the function, we get the following list output:
x <- c(10, 20, 30, 40, 50)
my_function(x) 
## [[1]]
## [1] 30
## 
## [[2]]
## [1] 15.81139

User-defined Function

## Create a function to print squares of numbers in sequence.
new.function <- function(a) {
   for(i in 1:a) {
      b <- i^2
      print(b)
   }
}   
new.function(3)
## [1] 1
## [1] 4
## [1] 9

User-defined Function

## Create a function to print squares of numbers in sequence.
new.function <- function(a) {
   for(i in 1:a) {
      b <- i^2
      print(b)
   }
}   
new.function(6)
## [1] 1
## [1] 4
## [1] 9
## [1] 16
## [1] 25
## [1] 36

Calling a Function without an Argument

# Create a function without an argument.
new.function <- function() {
   for(i in 1:5) {
      print(i^2)
   }
}   

# Call the function without supplying an argument.
new.function()
## [1] 1
## [1] 4
## [1] 9
## [1] 16
## [1] 25

Example 5 (Calling a Function with Argument Values)

# Create a function with arguments.
new.function <- function(a, b, c) {
   result <- a * b + c
   print(result)
}

# Call the function by position of arguments.
new.function(5, 3, 11)
## [1] 26
# Call the function by names of the arguments.
new.function(a = 11, b = 5, c = 3)
## [1] 58

Creating The Quadratic Formula Function in R

quadraticRoots <- function(a, b, c) {

  print(paste0("You have chosen the quadratic equation ", a, "x^2 + ", b, "x + ", c, "."))

  discriminant <- (b^2) - (4*a*c)

  if(discriminant < 0) {
    return(paste0("This quadratic equation has no real numbered roots."))
  }
  else if(discriminant > 0) {
    x_int_plus <- (-b + sqrt(discriminant)) / (2*a)
    x_int_neg <- (-b - sqrt(discriminant)) / (2*a)

    return(paste0("The two x-intercepts for the quadratic equation are ",
                  format(round(x_int_plus, 5)), " and ",
                  format(round(x_int_neg, 5)), "."))
  }
  else #discriminant = 0  case
    x_int <- (-b) / (2*a)
    return(paste0("The quadratic equation has only one root. This root is ",
                  x_int))
}

quadraticRoots(1, 0, 5)
## [1] "You have chosen the quadratic equation 1x^2 + 0x + 5."
## [1] "This quadratic equation has no real numbered roots."

Creating The Quadratic Formula Function in R

quadraticRoots <- function(a, b, c) {

  print(paste0("You have chosen the quadratic equation ", a, "x^2 + ", b, "x + ", c, "."))

  discriminant <- (b^2) - (4*a*c)

  if(discriminant < 0) {
    return(paste0("This quadratic equation has no real numbered roots."))
  }
  else if(discriminant > 0) {
    x_int_plus <- (-b + sqrt(discriminant)) / (2*a)
    x_int_neg <- (-b - sqrt(discriminant)) / (2*a)

    return(paste0("The two x-intercepts for the quadratic equation are ",
                  format(round(x_int_plus, 5)), " and ",
                  format(round(x_int_neg, 5)), "."))
  }
  else #discriminant = 0  case
    x_int <- (-b) / (2*a)
    return(paste0("The quadratic equation has only one root. This root is ",
                  x_int))
}
quadraticRoots(1, 7, 5)
## [1] "You have chosen the quadratic equation 1x^2 + 7x + 5."
## [1] "The two x-intercepts for the quadratic equation are -0.80742 and -6.19258."

Creating The Quadratic Formula Function in R

quadraticRoots <- function(a, b, c) {

  print(paste0("You have chosen the quadratic equation ", a, "x^2 + ", b, "x + ", c, "."))

  discriminant <- (b^2) - (4*a*c)

  if(discriminant < 0) {
    return(paste0("This quadratic equation has no real numbered roots."))
  }
  else if(discriminant > 0) {
    x_int_plus <- (-b + sqrt(discriminant)) / (2*a)
    x_int_neg <- (-b - sqrt(discriminant)) / (2*a)

    return(paste0("The two x-intercepts for the quadratic equation are ",
                  format(round(x_int_plus, 5)), " and ",
                  format(round(x_int_neg, 5)), "."))
  }
  else #discriminant = 0  case
    x_int <- (-b) / (2*a)
    return(paste0("The quadratic equation has only one root. This root is ",
                  x_int))
}
quadraticRoots(2, 4, 2)
## [1] "You have chosen the quadratic equation 2x^2 + 4x + 2."
## [1] "The quadratic equation has only one root. This root is -1"

Creating The Quadratic Formula Function in R

quadraticRoots <- function(a, b, c = 1) {

  print(paste0("You have chosen the quadratic equation ", a, "x^2 + ", b, "x + ", c, "."))

  discriminant <- (b^2) - (4*a*c)

  if(discriminant < 0) {
    return(paste0("This quadratic equation has no real numbered roots."))
  }
  else if(discriminant > 0) {
    x_int_plus <- (-b + sqrt(discriminant)) / (2*a)
    x_int_neg <- (-b - sqrt(discriminant)) / (2*a)

    return(paste0("The two x-intercepts for the quadratic equation are ",
                  format(round(x_int_plus, 5)), " and ",
                  format(round(x_int_neg, 5)), "."))
  }
  else #discriminant = 0  case
    x_int <- (-b) / (2*a)
    return(paste0("The quadratic equation has only one root. This root is ",
                  x_int))
}
quadraticRoots(2, 4, 2)
## [1] "You have chosen the quadratic equation 2x^2 + 4x + 2."
## [1] "The quadratic equation has only one root. This root is -1"

Creating The Quadratic Formula Function in R

quadraticRoots <- function(a, b, c = 1) {

  print(paste0("You have chosen the quadratic equation ", a, "x^2 + ", b, "x + ", c, "."))

  discriminant <- (b^2) - (4*a*c)

  if(discriminant < 0) {
    return(paste0("This quadratic equation has no real numbered roots."))
  }
  else if(discriminant > 0) {
    x_int_plus <- (-b + sqrt(discriminant)) / (2*a)
    x_int_neg <- (-b - sqrt(discriminant)) / (2*a)

    return(paste0("The two x-intercepts for the quadratic equation are ",
                  format(round(x_int_plus, 5)), " and ",
                  format(round(x_int_neg, 5)), "."))
  }
  else #discriminant = 0  case
    x_int <- (-b) / (2*a)
    return(paste0("The quadratic equation has only one root. This root is ",
                  x_int))
}
quadraticRoots(2, 4)
## [1] "You have chosen the quadratic equation 2x^2 + 4x + 1."
## [1] "The two x-intercepts for the quadratic equation are -0.29289 and -1.70711."

Resampling

Motivation

A parametric approach (Independent t-test)

Are these assumptions satisfied?

A permutation test

A permutation test Procedure

An example with actual data

# experiment comparing growing conditions' effect of growth
data(PlantGrowth)
head(PlantGrowth)
##   weight group
## 1   4.17  ctrl
## 2   5.58  ctrl
## 3   5.18  ctrl
## 4   6.11  ctrl
## 5   4.50  ctrl
## 6   4.61  ctrl
table(PlantGrowth$group)
## 
## ctrl trt1 trt2 
##   10   10   10

An example with actual data

ggplot(data = PlantGrowth,
       aes(x = group, y = weight)) +
  geom_boxplot() + theme_bw()

Is there a significant mean difference in weight between Treatment 2 and Control?

T-test

t.test(x = PlantGrowth$weight[PlantGrowth$group == "ctrl"],
       y = PlantGrowth$weight[PlantGrowth$group == "trt2"])
## 
##  Welch Two Sample t-test
## 
## data:  PlantGrowth$weight[PlantGrowth$group == "ctrl"] and PlantGrowth$weight[PlantGrowth$group == "trt2"]
## t = -2.134, df = 16.786, p-value = 0.0479
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
##  -0.98287213 -0.00512787
## sample estimates:
## mean of x mean of y 
##     5.032     5.526

A permutation test

# remove treatment 1
PlantGrowth <- PlantGrowth %>%
  filter(group != "trt1")
obs_diff <- mean(PlantGrowth$weight[PlantGrowth$group == "trt2"]) -
    mean(PlantGrowth$weight[PlantGrowth$group == "ctrl"])
obs_diff
## [1] 0.494

A permutation test

# store permuted differences
permuted_diff <- numeric()
for (i in 1:10000) {
  # for each iteration, scramble group variable
  permuted_data <- PlantGrowth %>%
    mutate(group = sample(group))
  # compute difference
  diff = mean(permuted_data$weight[permuted_data$group == "trt2"]) -
    mean(permuted_data$weight[permuted_data$group == "ctrl"])
  # store difference
  permuted_diff[i] <- diff
}
head(permuted_diff)
## [1] -0.306 -0.296  0.226  0.374 -0.116 -0.552

How do we compute a p-value?

# calculate p-value
mean(abs(permuted_diff) > abs(obs_diff))
## [1] 0.0484

A permutation test for correlation

A permutation test for correlation

set.seed(1111111)
sim_data <- data.frame(x = rnorm(11),
                       y = c(rnorm(11)))
ggplot(sim_data, aes(x = x, y = y)) + 
  geom_point()

A permutation test for correlation

obs_cor <- cor(sim_data$x, sim_data$y)
obs_cor
## [1] -0.108006

A permutation test for correlation

obs_cor <- cor.test(sim_data$x, sim_data$y)
obs_cor
## 
##  Pearson's product-moment correlation
## 
## data:  sim_data$x and sim_data$y
## t = -0.32592, df = 9, p-value = 0.7519
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  -0.6648080  0.5259451
## sample estimates:
##       cor 
## -0.108006

A permutation test for correlation

# store correlations
permuted_cor <- numeric()
for (i in 1:10000) {
  permuted_data <- 
    data.frame(x = sim_data$x,
               y = sample(sim_data$y))
  permuted_cor[i] <- cor(permuted_data$x,
                         permuted_data$y)
}
permuted_cor_df <- data.frame(cor = permuted_cor)
head(permuted_cor_df)
##          cor
## 1 -0.3789125
## 2 -0.6887097
## 3 -0.1764174
## 4  0.2357416
## 5  0.1888525
## 6  0.2586279

How do we compute a p-value?

# calculate p-value
mean(abs(permuted_cor) > abs(cor(sim_data$x, sim_data$y)))
## [1] 0.7433

Another permutation test for correlation

set.seed(302)
sim_data <- data.frame(x = rnorm(30, mean = 0, sd = 1))
sim_data$y <- sim_data$x + rnorm(30, mean = 0, sd = 2)
ggplot(sim_data, aes(x = x, y = y)) + 
  geom_point()

Another permutation test for correlation

obs_cor <- cor(sim_data$x, sim_data$y)
obs_cor
## [1] 0.5432401

Another permutation test for correlation

obs_cor <- cor.test(sim_data$x, sim_data$y)
obs_cor
## 
##  Pearson's product-moment correlation
## 
## data:  sim_data$x and sim_data$y
## t = 3.4238, df = 28, p-value = 0.001921
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  0.2274944 0.7556241
## sample estimates:
##       cor 
## 0.5432401

Another permutation test for correlation

permuted_cor <- numeric()
for (i in 1:10000) {
  permuted_data <- 
    data.frame(x = sim_data$x,
               y = sample(sim_data$y))
  permuted_cor[i] <- cor(permuted_data$x,
                         permuted_data$y)
}
permuted_cor_df <- data.frame(cor = permuted_cor)
head(permuted_cor_df)
##           cor
## 1 -0.17228945
## 2 -0.22716410
## 3  0.21496325
## 4  0.28050753
## 5  0.06209496
## 6 -0.44889433

How do we compute a p-value?

# calculate p-value
mean(abs(permuted_cor) > abs(cor(sim_data$x, sim_data$y)))
## [1] 0.0017

Loops

For Loops

For Loops

for (i in 1:5) {
  print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5

For Loops

for (i in 1:5) {
  print(i^2)
}
## [1] 1
## [1] 4
## [1] 9
## [1] 16
## [1] 25

For Loops

for (i in 1:5) {
  print(c(i, i^2) )
}
## [1] 1 1
## [1] 2 4
## [1] 3 9
## [1]  4 16
## [1]  5 25

For Loops

for (i in 1:8) {
  print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8

For Loops

for (i in c(1, 2, 3, 4, 5, 6, 7, 8)) {
  print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8

For Loops

for (i in c(1, 2, 3, 4, 5, 6, 7, 8)) {
  print(i^2)
}
## [1] 1
## [1] 4
## [1] 9
## [1] 16
## [1] 25
## [1] 36
## [1] 49
## [1] 64

For Loops

pas <- numeric(8)
for (i in 1:8) {
 pas[i]<-i^2
}
pas
## [1]  1  4  9 16 25 36 49 64
mean(pas)
## [1] 25.5
sd(pas)
## [1] 22.58318

For Loops

x <- c(1, 8, 22, 40)
for (i in 1:4) {
 pas[i]<-(x[i])^2
}
pas
## [1]    1   64  484 1600   25   36   49   64
mean(pas)
## [1] 290.375
sd(pas)
## [1] 551.9097

For Loops Examples

x <- 0
for(i in 1:5){
  x <- c(x,i)
}
x
## [1] 0 1 2 3 4 5

For Loops Examples

x <- 0
for(i in 1:5){
  x <- c(x,i)
  print(x)
}
## [1] 0 1
## [1] 0 1 2
## [1] 0 1 2 3
## [1] 0 1 2 3 4
## [1] 0 1 2 3 4 5

For Loops Examples

x <- 1
for(i in 1:5){
  x <- c(x,i)
  print(x)
}
## [1] 1 1
## [1] 1 1 2
## [1] 1 1 2 3
## [1] 1 1 2 3 4
## [1] 1 1 2 3 4 5
x <- 12
for(i in 1:5){
  x <- c(x,i)
  print(x)
}
## [1] 12  1
## [1] 12  1  2
## [1] 12  1  2  3
## [1] 12  1  2  3  4
## [1] 12  1  2  3  4  5

For Loops

for (i in c("zero", "one", "two", "three", "four", "five")) {
  print(i)
}
## [1] "zero"
## [1] "one"
## [1] "two"
## [1] "three"
## [1] "four"
## [1] "five"

For loops: a pair of examples

phrase <- "Good Night,"
for(word in c("and", "Good", "Luck")) {
  phrase <- paste(phrase, word)
  print(phrase)
}
## [1] "Good Night, and"
## [1] "Good Night, and Good"
## [1] "Good Night, and Good Luck"

Example

index.set <- list(name="Michael", weight=185, is.male=TRUE) # a list
for(i in index.set) {
  print(c(i, typeof(i)))
}
## [1] "Michael"   "character"
## [1] "185"    "double"
## [1] "TRUE"    "logical"

Nested Loops Examples

for (i in 1:3) {
  for (j in 1:2) {
    print(i + j)
  }
}
## [1] 2
## [1] 3
## [1] 3
## [1] 4
## [1] 4
## [1] 5

Nested Loops Examples

for (i in 1:3) {
  for (j in 1:2) {
    print(i * j)
  }
}
## [1] 1
## [1] 2
## [1] 2
## [1] 4
## [1] 3
## [1] 6

Nested Loops Examples

for (i in 1:3) {
  for (j in 1:2) {
    print(i * j^2)
  }
}
## [1] 1
## [1] 4
## [1] 2
## [1] 8
## [1] 3
## [1] 12

Nested Loops Examples

y <- 2
for(i in 1:5){
  y <- y*i
  print(y)
}
## [1] 2
## [1] 4
## [1] 12
## [1] 48
## [1] 240
y <- 2
for(i in 1:5){
  y <- y*i
}
y
## [1] 240

Nested Loops Examples

y <- 2
for(i in 1:20){
  y <- y*i
  print(y)
}
## [1] 2
## [1] 4
## [1] 12
## [1] 48
## [1] 240
## [1] 1440
## [1] 10080
## [1] 80640
## [1] 725760
## [1] 7257600
## [1] 79833600
## [1] 958003200
## [1] 12454041600
## [1] 174356582400
## [1] 2.615349e+12
## [1] 4.184558e+13
## [1] 7.113749e+14
## [1] 1.280475e+16
## [1] 2.432902e+17
## [1] 4.865804e+18
y <- 2
for(i in 1:20){
  y <- y*i
}
y
## [1] 4.865804e+18

Filling in a Vector

x <- rep(NA, 5)
x
## [1] NA NA NA NA NA
# Inefficient
x <- rep(NA, 5)
for (i in 1:5) {
  x[i] <- i * 2
}
x
## [1]  2  4  6  8 10
# Much better
x <- seq(2, 10, by = 2)
x
## [1]  2  4  6  8 10

Filling in a Matrix

A <- c(1,1,1)
for(j in 1:10){
A <- cbind(j,j^2, 5*j)
}
A
##       j       
## [1,] 10 100 50
A <- c(1,1,1)
for(j in 1:10){
A <- rbind(j,j^2, 5*j)
}
A
##   [,1]
## j   10
##    100
##     50

Filling in a Matrix

A <- c(1,1,1)
for(j in 1:10){
A = cbind(A, c(j,j^2, 5*j))
}
A
##      A                              
## [1,] 1 1  2  3  4  5  6  7  8  9  10
## [2,] 1 1  4  9 16 25 36 49 64 81 100
## [3,] 1 5 10 15 20 25 30 35 40 45  50
A <- c(1,1,1)
for(j in 1:10){
A = rbind(A, c(j,j^2, 5*j))
}
A
##   [,1] [,2] [,3]
## A    1    1    1
##      1    1    5
##      2    4   10
##      3    9   15
##      4   16   20
##      5   25   25
##      6   36   30
##      7   49   35
##      8   64   40
##      9   81   45
##     10  100   50

Filling in a Matrix

x <- matrix(NA, nrow = 4, ncol = 3)
for (i in 1:4) {
  for (j in 1:3) {
    x[i, j] <- i * j
  }
}
x
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    2    4    6
## [3,]    3    6    9
## [4,]    4    8   12

Filling in a Matrix

x <- matrix(rep(1:3, 4), nrow = 4, ncol = 3, byrow = TRUE)
x
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    1    2    3
## [3,]    1    2    3
## [4,]    1    2    3
x * 1:4
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    2    4    6
## [3,]    3    6    9
## [4,]    4    8   12

while loops

day <- 1
num.days <- 365
while(day <= num.days) {
  day <- day + 1
}

while Loop Example

x <- 10
while(x<30){
x <- x+5
print(x)
}
## [1] 15
## [1] 20
## [1] 25
## [1] 30
x
## [1] 30

while Loop Example

x <- 5
while(x<20){
x <- x+4
print(x)
}
## [1] 9
## [1] 13
## [1] 17
## [1] 21
x
## [1] 21

while Loop Example

x <- 5
y <- x
while(x<20){
x <- x+4
y <- c(y,x)
print(y)
}
## [1] 5 9
## [1]  5  9 13
## [1]  5  9 13 17
## [1]  5  9 13 17 21
x
## [1] 21
y
## [1]  5  9 13 17 21

while Loop Example

set.seed(3)
x <- -1
while (x < 0) {
  x <- rnorm(1)
  print(x)
}
## [1] -0.9619334
## [1] -0.2925257
## [1] 0.2587882
x
## [1] 0.2587882

while Loop Example

set.seed(3)
x <- -1
while (x < -0.5) {
  x <- rnorm(1)
  print(x)
}
## [1] -0.9619334
## [1] -0.2925257
x
## [1] -0.2925257