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
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\).
i<- 1
x<- 1
while(i<100){
i<- i+1
x<- x+1/i
}
x
## [1] 5.187378
x<- 1
for(i in 2:100){
x<- x+1/i
}
x
## [1] 5.187378
Exercise:
- 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.
- 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.
- Write a function that can either calculate the summation of the serie in Question 1 or generate and print Fibonacci sequence in Question 2.