---
title: "Functions"
output: html_notebook
---
```{r}
myfunction <- function(arg1, arg2, ... ){
statements
return(object)
}
```
```{r}
# Define a simple function
myFirstFun<-function(n)
{
# Compute the square of integer `n`
result <- n*n
return(result) # optional
# n*n # this single line will work too
}
# Assign `10` to `k`
k <- 10
# Call `myFirstFun` with that value
m <- myFirstFun(k)
# Call `m`
m
```
#### Functions without return()
If there are no explicit returns from a function, the value of the last evaluated expression is returned automatically in R.
```{r}
check <- function(x) {
if (x > 0) {
result <- "Positive"
}
else if (x < 0) {
result <- "Negative"
}
else {
result <- "Zero"
}
result
}
check(5)
check(-5)
check(0)
```
We generally use explicit return() functions to return a value immediately from a function.
If it is not the last statement of the function, it will prematurely end the function bringing the control to the place from which it was called.
```{r}
check <- function(x) {
if (x>0) {
return("Positive")
}
else if (x<0) {
return("Negative")
}
else {
return("Zero")
}
}
check(5)
check(-5)
check(0)
```
Same as:
```{r}
check <- function(x) {
if (x>0) {
return("Positive")
}
if (x<0) {
return("Negative")
}
return("Zero")
}
check(5)
check(-5)
check(0)
```
#### Recursion
_Als Rekursion (lateinisch recurrere ‚zurücklaufen‘) bezeichnet man den abstrakten Vorgang, dass Regeln auf ein Produkt, das sie hervorgebracht haben, von neuem angewandt werden. Hierdurch entstehen potenziell unendliche Schleifen._ [Wikipedia](https://de.wikipedia.org/wiki/Rekursion)
```{r}
factorial <- function(n)
{
if (n==0)
return(1)
else
return(n * factorial(n - 1))
}
factorial(4)
```
Rekursive Funktionen können (!) deutlich langsamer sein als iterative Ansätze.
```{r}
fibonacci<-function(n)
{
if (n == 0)
return(1)
else if (n == 1)
return(1)
else
return(fibonacci(n-1)+fibonacci(n-2))
}
fibonacci_nonrec <- function(n)
{
prev1 <- 0
prev2 <- 1
result <- 0
for (i in 1:n)
{
result = prev1 + prev2
prev1 = prev2
prev2 = result
}
return(result)
}
n = 34
tic <- Sys.time()
fibonacci(n)
print(Sys.time() - tic)
tic <- Sys.time()
fibonacci_nonrec(n)
print(Sys.time() - tic)
```