re_scale <- function(x, ...,
method = c("mean","max", "std", "max_min_n",
"median", "max_min", "mean_max")){
m = mean(x, ...)
s = sd(x, ...)
max = max(x, ...)
min = min(x, ...)
md = median(x, ...)
if (method == "mean"){
norm = x/m
}else if( method == "max"){
norm = m/max
}else if( method == "std"){
norm = (x-m)/s
}else if(method == "median"){
norm = x/md
}else if(method == "max_min_n"){
norm = (x-min)/(max - min)
}else if(method == "mean_max"){
norm = (x-m)/max
}else if(method == "max_min"){
norm = (x-m)/(max-min)
}
return(norm)
}
This parameter is typically used for pass parameters on to functions called within a function. function(x,...)
For example:
rescale <- function(x,...){
m = mean(x, ...)
sd = sd(x, ...)
}
x <- c(NA, 1:3)
rescale(x)
## Now, with the use of three dot argument
rescale(x, na.rm = T)
The ...
parameter allows a function to take any named parameter at all. If you write a function without it, it will only take the specified parameters, but if you add this parameter, it will accept any named parameter at all:
Expressions used in a function call are not evaluated before they are passed to the function. Most common languages have so-called pass by-value semantics, which means that all expressions given to parameters of a function are evaluated before the function is called. In R, the semantic is call-by-promise, also known as lazy evaluation.
Expressions in R are vectorized. When you write an expression, it is implicitly working on vectors of values, not single values. Even simple expressions that only involve numbers really are vector operations. They are just vectors of length 1.
## Not vectorized function
compare <- function(x,y){
if (x<y){
-1
}else if (y<x) {
1
}else{
0
}
}
## But thecompare function can be vetorized
compare <- Vectorize(compare)
## This functions solves the problem with control structures
compare <- function(x,y){
ifelse(x < y, -1, ifelse(y < x,1,0))
}
If the function is already vectorized and we use Vectorize()
function, we break the function.
## [1] 0.4
## [1] 10
## [1] 7
## [1] -3
## [1] 32
## [1] FALSE
## [1] "FALSE"