- Function in R
- is a R Object of class "function"
- It has "named arguments" with default values, i.e. mean function in R calculates the arithmetic mean, it has na.rm arguments with default value "FALSE".
> x <- c(1,2,NA,5)
> mean(x) # can't calculate mean because of the NA value
[1] NA
> mean(x,na.rm = TRUE) # turn on remove NA value argument
[1] 2.666667
> mean(na.rm = TRUE, x) # the same even change the position of arguments
[1] 2.666667
Define a sum function to return sum of two arguments
> sumfun <- function(x,y){
+ return(x+y)
+ }
> sumfun(1,4)
[1] 5
Lazy Evaluation: evaluated only while needed
> f <- function(x,y){
+ x*2 # no evaluation for y, the same as return(x*2)
+ }
> f(4) # return result without error
[1] 8
No comments:
Post a Comment