---
title: "A (too) short introduction to R"
output: html_notebook
---

In this first lab we will (if necessary) briefly see how one can use *R*.

## 0. Getting R (and a GUI)

First to use *R*, you need to install it! You can download it from [here](www.r-project.org). Since the original GUI for R is a bit limited, you may want to install more advanced GUI. One popular option is [RStudio](https://rstudio.com). Once you have installed everything appropriately we can start using *R*!

## 1. Basic instructions

I just list here some simple computations.


```{r}
x <- 1
y <- 3
x + y
x - y
x * y
x / y
x^y
## and many other stuffs: log, exp, sin, cos, gamma, ...
```


## 2. Vector, matrices, array, list

```{r}
x <- c(1, 5, -3, 7, 8, -15)## vector of reals
x
y <- c("toto", "tutu", "tata")## vector of character strings
y

A <- matrix(x, 3)##a matrix with 3 rows (hence 2 columns) which is "filled columnwise" with x
A
B <- matrix(x, 3, byrow = TRUE)## filled rowwise
B
C <- matrix(y, 3, 4)## recycle the vector y to fill in the matrix
C

## Tensors are also available from the array function
D <- array(1:60, dim = c(3, 4, 5))## A 3d tensor
E <- array(1:60, dim = c(5, 2, 3, 2))## A 4d tensor
D

l <- list(component1 = x, component2 = C)## list the most "powerfull type" can mix different object class within a list
l

D <- cbind(x, y)## column binding to create a 2 column matrix (of which class???)
D
D2 <- rbind(x, y)## row binding
D2
```

## 3. Linear algebra

```{r}
x <- 1:3##integers from 1 to 3 (included)
y <- seq(2.1, 15, length = 3)##evenly space points between 2.1 ane 15 (total length 3)

x + y
x * y ## componentwise multiplication
x %*% y ## inner product

A <- diag(5, 3)## 3 x 3 diagonal matrix with 5 on the diagonal
B <- matrix(1:9, 3)
t(B) ## Matrix transpose
A %*%  ## matrix multiplication
A * A ## componentwise multiplication (Hadamard product)
solve(A)## matrix inverse
eigen(A)## eigen decomposition
svd(A)## singular value decomposition
```

## 4. Random number generation

```{r}
rnorm(5, 0, 4)##5 independent draws from a gaussian distribution with mean 0 and *standard deviation* 4.
runif(5, -4, 3)## 5 independent draws from a U(-4, 3) distribution
```

## 5. Basic plots

```{r}
## Generate a random walk
randomwalk <- cumsum(rnorm(1000))
plot(randomwalk)
plot(randomwalk, type = "l")
plot(randomwalk, type = "o")

x <- seq(0, pi, length = 5)
y <- sin(x)
plot(x, y, xlab = "x", ylab = "sin(x)")

plot(sin, from = 0, to = 2 * pi, col = "orange", lwd = 2)##lwd for Line WiDth

x <- rnorm(100)
hist(x, freq = FALSE)##freq = FALSE so that area = 1
plot(dnorm, from = -4, to = 4, col = "green", lwd = 2, lty = 2, add = TRUE)## add = TRUE to add the plot to the current graphic

x <- rnorm(100)
y <- rnorm(100, 1)
boxplot(cbind(x, y))##boxplots
```

## 6. Importing / Exporting data

Well read the documentation of the *read.table*, *write.table* and *save* function. 

## 7. For, if, else, loops

```{r}
for (i in 1:3)
  print(i)

astring <- "what"

if (astring == "who"){
  outstring <- "what is"
  a <- 1
} else if (astring == "which"){
  outstring <- "what?"
  a <- 2
} else {
  outstring <- "is what?"
  a <- 3
}

print(outstring)
```

## 8. Creating function

```{r}
myfunction <- function(arg1, arg2, optional.argument = "take log"){
  output <- arg1 + arg2
  
  if (optional.argument == "take log")
    output <- log(output)
  
  return(output)
}

myfunction(2, 3)
myfunction(2, 3, "do not take log")
```

Watch out an *R* function can only return a single object so if you want to ouput several quantities you will have to store them within a list, i.e., as below
```{r}
myfunction2 <- function(arg1, arg2, optional.argument = "take log"){
  output <- arg1 + arg2
  
  if (optional.argument == "take log")
    output <- log(output)
  
  return(list(output = output, message = optional.argument))
}

myfunction2(2, 3)
```

## 9. Numerical optimization

```{r}
rosenbrock <- function(x) {   ## Rosenbrock Banana function
    x1 <- x[1]
    x2 <- x[2]
    100 * (x2 - x1 * x1)^2 + (1 - x1)^2
}

n.grid <- 100
x <- seq(-2, 2, length = n.grid)
y <- seq(-3, 3, length = n.grid)
grid <- expand.grid(x, y)
z <- apply(grid, 1, rosenbrock)##compute the function on the grid
z <- matrix(z, n.grid)

## plot of it (just take care of the persp line of code not the previous ones)
jet.colors <- colorRampPalette( c("blue", "green") )
nbcol <- 250
color <- jet.colors(nbcol)
# Compute the z-value at the facet centres
zfacet <- z[-1, -1] + z[-1, -n.grid] + z[-n.grid, -1] + z[-n.grid, -n.grid]
# Recode facet z-values into color indices
facetcol <- cut(zfacet, nbcol)
persp(x, y, z, col = color[facetcol], phi = 40, theta = -30, border = NA)

## minimize the banana function
init <- c(0, 0)## minimum is at (1, 1)
optim(init, rosenbrock)
optim(init, rosenbrock, method = "BFGS")## changing optimizer
nlm(rosenbrock, init)## another (the one I often used) optimizer
```



