# 1 Advanced techniques in R

## 1.1 Functions

• R programming is essential applying and writing functions. Most of R consists of functions.
• An R function may require multiple inputs, we call them arguments. The arguments can either be input in the right order, or using argument names. In RStudio, pressing tab after function name gives help about arguments
• Using “?+function name” to learn how to use that funcion.
• We introduce how to write simple functions here. In the following example the function abs_val returns the absolute value of a number.
abs_val = function(x){
if(x >= 0){
return(x)
}
else{
return(-x)
}
}
abs_val(-5)
## [1] 5

A function for vector truncation

mytruncation<- function(v, lower, upper){
v[which(v<lower)]<- lower
v[which(v>upper)]<- upper
return(v)
}

You just defined a global function for truncation. Now let’s apply it to vector z2, where we truncate at lower=3 upper=7.

mytruncation(v = c(1:9), lower = 3, upper = 7)
## [1] 3 3 3 4 5 6 7 7 7

## 1.2 Loop

There are two ways to write a loop: while and for loop. Loop is very useful to do iterative and duplicated computing.

For example: calculate $$1+1/2+1/3+...+1/100$$.

### 1.2.1 Using while loop

i<- 1
x<- 1
while(i<100){
i<- i+1
x<- x+1/i
}
x
## [1] 5.187378

### 1.2.2 Using for loop

x<- 1
for(i in 2:100){
x<- x+1/i
}
x
## [1] 5.187378

Exercise:

1. Do you think $$1+1/2^2+1/3^2+...+1/n^2$$ converges or diverges as $$n\rightarrow \infty$$? Use R to verify your answer.
2. Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13,… What is the next number? What is the 50th number? Creat a vector of first 30 Fibonacci numbers.
3. Write a function that can either calculate the summation of the serie in Question 1 or generate and print Fibonacci sequence in Question 2.

go to top