Control Flow

Learning Objectives

  • Nested for Loops

Nested for Loops

  • Nested for Loops

  • More Examples

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 \]

More Examples

  • Nested for Loops

  • More Examples

Example

The median() function obtain the median value of a vector. Write code to obtain the median value for any vector.

x <- rnorm(500)
y <- rnorm(501)
median(x)
median(y)

Answer:

Code
wk <- x 
pos50 <- (length(wk) + 1) / 2
swk <- sort(wk)
if ((length(wk) %% 2) == 0) {
  val <- (swk[floor(pos50)] + swk[ceiling(pos50)]) / 2
} else {
  val <- swk[pos50]
}
print(val)
median(wk)

wk <- y 
pos50 <- (length(wk) + 1) / 2
swk <- sort(wk)
if ((length(wk) %% 2) == 0) {
  val <- (swk[floor(pos50)] + swk[ceiling(pos50)]) / 2
} else {
  val <- swk[pos50]
}
print(val)
median(wk)

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

Create a vector reporting the data type of each variable in ISLR2::BrainCancer

library(ISLR2)
BrainCancer

Answer:

Code
nn <- ncol(BrainCancer)
y <- c()
for (i in 1:nn){
  y <- c(y, class(BrainCancer[,i]))
}

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)

Example

For each column in mtcars, take the mean for the even columns, and median for the odd columns. Store the values in a list containing 2 vectors.

Answer:

Code
x <- c()
y <- c()
nn <- ncol(mtcars)
for (i in 1:nn){
  if (i %% 2 == 0){
    x <- c(x, mean(mtcars[,i]))
  } else {
    y <- c(y, median(mtcars[,i]))
  }
}

xy <- list(x,y)