R Programming language - R Function

www.igif‮moc.aedit‬

In R programming language, a function is a block of code that performs a specific task and can be reused multiple times in a program. Functions allow you to break down complex tasks into smaller, more manageable pieces of code, making your code more modular, easier to read and maintain.

Here is the basic syntax of a function in R:

function_name <- function(arg1, arg2, ...) {
  # Function code
  return(output)
}

In this syntax, function_name is the name of the function, arg1, arg2, and so on are the arguments of the function (which can be empty), and output is the value returned by the function.

Here is an example of a simple function in R that calculates the sum of two numbers:

sum_numbers <- function(a, b) {
  sum <- a + b
  return(sum)
}

In this example, sum_numbers is the name of the function, a and b are the input arguments, and sum is the output of the function. The function takes two numbers a and b, adds them together, and returns their sum.

You can call the function by passing two numbers as arguments, like this:

result <- sum_numbers(2, 3)
print(result)

In this example, result will be assigned the value 5, and the print() function will print the value of result to the console.

Functions can also have default arguments, variable-length arguments, and can return multiple values. There are many built-in functions in R, and you can also create your own custom functions to perform specific tasks in your program.