---
title: "Vectorization"
subtitle: "RaukR 2023 • Advanced R for Bioinformatics"
author: "Marcin Kierczak"
description: "Speed up R code using vectorized functions."
image: "assets/featured.webp"
format: html
---

```{r}
#| echo: false
## LIBRARIES AND VARIABLES
# load the packages you need for this document
```

::: {.callout-note}
In programming languages loop structures, either with or without conditions, are used to repeat commands over multiple entities. For and while loops as well as if-else statements are also often used in R, but perhaps not as often as in many other programming languages. The reason for this is that in R, there is an alternative called *vectorization* which usually is more efficient.
:::

Vectorization implies that we can multiply all values in a vector in R by two by calling:

```{r}
vec.a <- c(1, 2, 3, 4)
vec.a * 2
```

In many other and languages as well as in R, you can also create this with a loop instead

```{r}
for (i in vec.a) {
  vec.a[i] <- vec.a[i] * 2
}

vec.a
```

As you saw in the lecture, this is far less efficient and not by any means easier to type and we hence tend to avoid loops when possible.

## Task 1: A large matrix

### Looping over a matrix

- Create a 100000 by 10 matrix with the numbers 1:1000000
- Write a `for`-loop that calculates the sum for each row of the matrix. 
- Verify that your row counts are consistent with what you obtain with the `apply()` function 
- Verify that your row counts are consistent with what you obtain with the `apply()` function `rowSums()` function

```{r}
#| code-fold: true
#| results: markup

X <- matrix(1:1000000, nrow = 100000, ncol = 10)
for.sum <- vector()
# Note that this loop is much faster if you outside the loop create an empty vector of the right size.
# rwmeans <- vector('integer', 100000)
for (i in 1:nrow(X)) {
  for.sum[i] <- sum(X[i, ])
}
head(for.sum)

app.sum <- apply(X, MARGIN = 1, sum)
head(app.sum)

rowSums.sum <- rowSums(X)
head(rowSums.sum)

identical(for.sum, app.sum)
identical(for.sum, rowSums.sum)
identical(for.sum, as.integer(rowSums.sum))
```

## Task 2: Fibonacci sequence

During the lecture an approach to calculate factorials was implemented using recursion (function calling itself). Here we should use recursion to generate a sequence of Fibonacci numbers. A Fibonacci number is part of a series of number with the following properties:

- the first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1 (depending on the chosen starting point) 
- each subsequent number is the sum of the previous two. Hence:

`0, 1, 1, 2, 3, 5, 8, 13, 21, ...`

or

`1, 1, 2, 3, 5, 8, 13, 21, ...`

### N-th Fibonacci number

Write a function that generates Fibonacci number using a recursive approach.

```{r}
#| code-fold: true
#| results: markup

fib_rec <- function(n) {
  if (n == 0 || n == 1) {
    return(n)
  } else {
    return(fib_rec(n - 1) + fib_rec(n - 2))
  }
}
```

### Generate Fibonacci sequence

Generate Fibonacci numbers from 0 to 10 using `*apply*` approach.

```{r}
#| code-fold: true
#| results: markup

sapply(0:10, FUN = fib_rec)
```

### Vectorized Fibonacci generator

Vectorize your Fibonacci number generating function.

```{r}
#| code-fold: true
#| results: markup

vec_fib_rec <- Vectorize(fib_rec)
vec_fib_rec(0:10)
```

## Session

<details>
  <summary>Click here</summary>

```{r}
#| label: session

sessionInfo()
```

</details>
