## ---- chunkA1 ----
3+5; 3-5; 3*5; 3/5
# More complex including brackets
(5+3-1)/(5*10)
# is different to 
5+3-1/5*10
# power of a variable
4*4*4
4^300
# root of a variable
sqrt(16)
16^(1/2)
16^0.5
# exponential and logarithms
exp(3)
log(exp(3))
exp(1)
# Log to the basis of 2
log2(8)
2^log2(8)
# raise the number of digits shown
options(digits=8)
exp(1)
# Rounding
20/3
round(20/3,2)
floor(20/3)
ceiling(20/3)

## ---- chunkA2 ----
n <- 10
n
n <- 11
n
12 -> n
n
n <- n^2
n 

## ---- chunkA3 ----
# check if m==10
m <- 11
m==10 # is equal to
m==11
m!=11 # is not equal to
m>10  # is larger than
m<10  # is smaller than
m<=11 # is smaller or equal than
m>=12 # is larger or equal than

## ---- chunkA4 ----
ls()  # list variables
rm(m) # remove m
ls()  # list variables again (m is missing)

## ---- chunkA5 ----
name <- "test"
is.numeric(n)
is.numeric(name)
is.character(n)
is.character(name)

## ---- chunkA6 ----
class(n)
class(name)
mode(n)
mode(name)
typeof(n)
typeof(name)
# Lets change formats:
n1 <- n
is.character(n1)
n1 <- as.character(n)
is.character(n1)
as.numeric(name) # New thing: NA

## ---- chunkA7 ----
# last but not least we need boolean (logical) variables
n2 <- TRUE
is.numeric(n2)
class(n2)
is.logical(n2)
as.logical(2) # all values except 0 will be converted to TRUE
as.logical(0)

## ---- chunkA8 ----
is.logical(n==10)
n3 <- n==10 # we can assign the logical output to a new variable
is.logical(n3)

## ---- chunkA9 ----
x <- c(1,3,5,6,7)
class(x)
is.vector(x)
is.numeric(x)

## ---- chunkA10 ----
x1 <- seq(from=1,to=5,by=1)
x2 <- 1:5

## ---- chunkA11 ----
1:10-1
1:(10-1)
1:10^2-2 *3

## ---- chunkA12 ----
rand1 <- rnorm(n = 100) # 100 standard normally distributed random numbers
set.seed(134) # fix the starting value of the random number generator (then it will always)
rand1a <- rnorm(n = 100)

## ---- chunkA13 ----
#install.packages("moments") # only once, no need to reinstall every time
library(moments)
mean(rand1a)
sd(rand1a)
skewness(rand1a)
moments::kurtosis(rand1a)
summary(rand1a)

## ---- chunkA14 ----
x <- c(2,4,5,8,10,12)
length(x)
dim(x)
x^2/2-1
x %*% x # R automatically multiplies row and column vector
is.vector(x)
y <- as.matrix(x)
is.matrix(y); is.matrix(x)
dim(y); dim(x)
t(y) %*% y
y %*% t(y)
mat <- matrix(data = x,nrow = 2,ncol = 3, byrow = TRUE)
dim(mat); ncol(mat); nrow(mat)
mat2 <- matrix(c(1,2,3,4),2,2) # set a new (quadratic) matrix
mat2i <- solve(mat2)
mat2 %*% mat2i
mat2i %*% mat2

## ---- chunkA15 ----
diag(3)
diag(c(1,2,3,4))
mat4 <- matrix(0,3,3)
mat5 <- matrix(1,3,3)
cbind(mat4,mat5)
rbind(mat4,mat5)

## ---- chunkA16 ----
########################################################
### 8) The INDEXING System
# We can access the single values of a vector/matrix
x[2] # one-dim
mat[,2,drop=FALSE] # two-dim column
mat[2,] # two-dim row
i <- c(1,3)
mat[,i]
mat[1,2:3] # two-dim select second and third column, first row
mat[-1,] # two-dim suppress first row
mat[,-2] # two-dim suppress second column

## ---- chunkA17 ----
mat>=5 # which elements are large or equal to 5?
mat[mat>=5] # What are these elements?
which(mat>=5, arr.ind = TRUE) # another way with more explicit information

## ---- chunkA18 ----
colnames(mat) <- c("a","b","c")
rownames(mat) <- c("A","B")
mat[1,c(2,3)]
mat["A",c("b","c")]

## ---- chunkA19 ----
x <- c(1,2,4,-1,2,8)  # example vector 1
x1 <- c(1,2,4,-1,2,8,NA,Inf) # example vector 2 (more complex)
sqrt(x) # square root of x
x^3 # x to the power of ...
sum(x1,na.rm=TRUE) # sum of the elements of x
prod(x) # product of the elements of x
max(x) # maximum of the elements of x
min(x) # minimum of the elements of x
which.max(x) # returns the index of the greatest element of x
which.min(x) # returns the index of the smallest element of x
# statistical function - use rand1 and rand2 created before
range # returns the minimum and maximum of the elements of x
mean # mean of the elements of x
median # median of the elements of x
var # variance of the elements of x
sd # standard deviation of the elements of x
cor # correlation between x and y
cov # covariance between x and y
cov2cor # scale a covariance matrix into the corresponding correlation matrix
# more complex functions
round(x, n) # rounds the elements of x to n decimals
rev(x) # reverses the elements of x
sort(x, decreasing = TRUE) # sorts the elements of x in increasing order
rank(x) # ranks of the elements of x
log(x) # computes natural logarithms of x
cumsum(x) # a vector which ith element is the sum from x[1] to x[i]
cumprod(x) # id. for the product
cummin(x) # id. for the minimum
cummax(x) # id. for the maximum
unique(x) # duplicate elements are suppressed

## ---- chunkA20 ----
df <- data.frame(col1=c(2,3,4), col2=sin(c(2,3,4)), col3=c("a","b", "c"))
li <- list(x=c(2,3,4), y=sin(c(2,3,4)), z=c("a","b", "c","d","e"), fun=mean)
# to grab elements from a list or dataframe use $ or [[]]
df$col1; li$x # get variables
df[,"col3"]; li[["x"]] # get specific elements that can also be numbered
df[,3]; li[[1]]

## ---- chunkA21 ----
?"function" # "function" is such a high-level object that it 
# is interpreted before the "help"-command

# 1. Let's create a function that squares an entry x and name it square
square <- function(x){x^2}
square(x = 5)
square(x = c(1,2,3))

# 2. Let us define a function that returns a list of several 
# different results (statistics of a random vector v)
stats <- function(v){
  v.m <- mean(v) # create a variable that is only valid in the function
  v.sd <- sd(v)
  v.var <- var(v)
  v.output <- list(Mean=v.m, StandardDeviation=v.sd, Variance=v.var)
  return(v.output)
}
set.seed(123)
v <- rnorm(100000,mean=1,sd=5)
stats(v)
stats(v)$Mean

# 3. A function can have standard arguments.
### This time we also create a random vector within the function and use 
# its length as an input
stats2 <- function(n,m=0,s=1){
  v <- rnorm(n,mean=m,sd=s)
  v.m <- mean(v) # create a variable that is only valid in the function
  v.sd <- sd(v)
  v.var <- var(v)
  v.output <- list(Mean=v.m, StandardDeviation=v.sd, Variance=v.var)
  return(v.output)
}
stats2(n = 1000000)
stats2(n = 1000,m=1)
stats2(n = 1000,m=1,s=10)
stats2(m=1) # what happens if an mandatory argument is left out?

## ---- chunkA22 ----
?plot
?colors
y1 <- rnorm(n = 50,mean = 0,sd = 1)
plot(y1)
# set title, and x- and y-labels
plot(y1,main="normal RV",xlab="Point No.",ylab="Sample")
# now make a line between elements, and color everything blue
plot(y1,main="normal RV",xlab="Point No.",ylab="Sample",col="CornflowerBlue",type='l')
# if you want to save plots or open them in separate windows you can use x11, pdf, png, ...
?Devices
# x11 (opens separate window)
plot(y1,main="normal RV",xlab="Point No.",ylab="Sample",col="blue",type='l')
# pdf
pdf(file = "plot1.pdf",width = 6,height = 6)
  plot(y1,main="normal RV",xlab="Point No.",ylab="Sample",col="blue",type='l',
       lty=2)
  legend("topleft",col=c("blue"), lty=2, legend=c("normal Sample"))
dev.off()
# more extensive example
#X11(6,6)
par(mfrow=c(2,1),cex=0.9,mar=c(3,3,1,3)+0.1)
plot(y1,main="normal RV",xlab="Point No.",ylab="Sample",col="blue",
     type='l',lty=2,ylim=c(-2.5,2.5),lwd=2)
legend("topleft",col=c("blue"), lty=2, legend=c("normal Sample"))
barplot(y1,col="blue") # making a barplot
# plotting a histogram
par(mfrow=c(1,1),cex=0.9,mar=c(5,5,1,1)+0.1)
hist(y1) # there is a nicer version available once we get to time series analysis
# create a second sample
y2 <- rnorm(50)
# scatterplot
plot(y1,y2,xlab="y1",ylab="y2",main="Scatterplot Example")
# boxplot
boxplot(y1,y2)

## ---- chunkA23 ----
x <- sample(-15:15,10) # sample does draw randomly draw 10 numbers from the 
# input vector -15:15
# 1. We square every element of vector x in a loop
y <- NULL # 1.a) set an empty variable (NULL means it is truly nothing and has 
# no pre-specified dimension/length)
is.null(y)
# 1.b) Use an easy for-loop:
for (i in 1:length(x)){
  y[i] <- x[i]^2
}
# 2. Now we use an if-condition to only replace negative values
y <- NULL
for (i in 1:length(x)){
  y[i] <- x[i]
  if(x[i]<0) {y[i] <- x[i]^2}
}

