July 20, 2021

Functions in R

User-Defined Functions in R

Functions are objects, in R
func_name <- function (argument) {
   statement
}

power_R <- function(x, y) {
   # function to print x raised to the power y
   result <- x^y
   print(paste(x,"raised to the power", y, "is", result))
}

power_R <- function(x, y = 2) {
   # function to print x raised to the power y
   result <- x^y
   print(paste(x,"raised to the power", y, "is", result))
}

return(expression)

If there are no explicit returns from a function, the value of the last evaluated expression is returned

check <- function(x) {
   if (x > 0) {
       result <- "Positive"
   } else if (x < 0) {
       result <- "Negative"
   } else {
       result <- "Zero"
   }
   return(result)
}

multi_return <- function() {
   my_list <- list("color" = "red", "size" = 20, "shape" = "round")
   return(my_list)
}

To make assignments to global variables, superassignment operator, <<-, is used

outer_func <- function(){
   inner_func <- function(){
       a <<- 30
       print(a)
   }
   inner_func()
   print(a)
}

recursive.factorial <- function(x) {
   if (x == 0)    return (1)
   else           return (x * recursive.factorial(x-1))
}

print.student <- function(obj) {
 cat(obj$name, "\n")
 cat(obj$age, "years old\n")
 cat("GPA:", obj$GPA, "\n")
}

formals(func_name)
body(func_name)
environment(func_name)

fn <- function(x) {x+x+x}; fn(6)
(function(x) {x+1}) (2) # function definition/call in single line
my.standard<-function(x){(x-mean(x))/sd(x)}

There are three kinds of functions in R.
Most of the functions that you come across are called closures.
A few important functions, like length() are known as builtin functions, which use a special evaluation mechanism to make them go faster.
Language constructs, like if and while are also functions! They are known as special functions.

args(predict)
args(train.default)

Related Articles: R Date Time operations


No comments:

Post a Comment