By CM
y = f(x) = x+3
name = function(argument) = do something!
(or in CS sense)
# Defining a function
y <- function(x){
return (x+3)
}
# Using it !
y(5)
>>> 8
# It is equivalent to do...
x <- 5
x+3
# Defining a function
y <- function(x, y, z){
return (x+y+z)
}
# Using it !
y(5, 5, 7)
>>> 17
# It is equivalent to do...
x <- 5
y <- 5
z <- 7
x+y+z
(multi-variables)
#3 Fibonacci sequence
fibonacci <- function(n){
if ((n == 1) | (n == 2)){
return (1)
} else {
return (fibonacci(n-2) + fibonacci(n-1))
}
}
fibonacci(10)
>>> 55
for(i in 1:10){
print(fibonacci(i))
}
>>> 1 1 2 3 5 8 13 21 34 55
(multi-variables)
# HELP!
help(max)
?seq
args(dbinom)
Packages are collections of R functions, data, and compiled code in a well-defined format.
install.packages("dplyr")
[syntax]
install.packages(package_name)
library(dplyr)
require(dplyr)
[syntax]
library(package_name)
or
require(package_name)
Use apply function family instead of loop
We will introduce the following three commonly used functions:
lapply
sapply
vapply
lapply(X, FUN, ...)
When you want to apply a function to each element of a list in turn and get a list back.
returns a list of the same length as X
each element of which is the result of applying FUN to the corresponding element of X.
sapply(X, FUN, ...)
When you want to apply a function to each element of a list in turn, but you want a vector back, rather than a list.
vapply(X, FUN, FUN.VALUE, ...)
similar to sapply
The FUN.VALUE argument expects a template for the return argument of this function FUN
FUN.VALUE: numeric / logical / ...
safer (and sometimes faster) to use