Function is also an object, like in JavaScript
Example:
add2 <- function(x, y){
x + y
}
steps of improve function
x <- 1:20
above10 <- function(x){
use <- x > 10
x[use]
}
r <- above10(x)
print(r)
aboveN <- function(x, n){
use <- x > n
x[use]
}
r <- aboveN(x, 10)
print(r)
aboveN <- function(x, n=10){
use <- x > n
x[use]
}
r <- aboveN(x)
print(r)
Environment
Constructer Function
make.power <- function(n) {
pow <- function(x) {
x^n
}
pow
}
square <- make.power(n=2)
cube <- make.power(3)
square(3) # 9
cube(3) # 27
check environment
ls(environment(square))
# [1] "n" "pow"
get('n', environment(square))
# [1] 2