0
0
R Programmingprogramming~5 mins

Function definition in R Programming

Choose your learning style9 modes available
Introduction

Functions help you group code to do a specific job. You can reuse them anytime without rewriting.

When you want to repeat a task many times with different inputs.
When you want to organize your code into small, clear parts.
When you want to test or fix one part of your code easily.
When you want to share your code with others in a simple way.
Syntax
R Programming
function_name <- function(arg1, arg2, ...) {
  # code to run
  return(value)  # optional
}

The function name is how you call it later.

Arguments (arg1, arg2, ...) are inputs you give to the function.

Examples
A simple function with no inputs that prints a greeting.
R Programming
say_hello <- function() {
  print("Hello!")
}
A function that adds two numbers and returns the result.
R Programming
add <- function(x, y) {
  return(x + y)
}
A function that returns the square of a number. The last line is the return value.
R Programming
square <- function(num) {
  num * num
}
Sample Program

This program defines a function to greet someone by name. It then calls the function with "Anna" and prints the greeting.

R Programming
greet <- function(name) {
  message <- paste("Hello," , name, "!")
  return(message)
}

result <- greet("Anna")
print(result)
OutputSuccess
Important Notes

If you do not use return(), R returns the last expression automatically.

Functions help keep your code clean and easy to understand.

Summary

Functions group code to do one job.

Define with function() and give a name.

Use arguments to send inputs and return() to send back results.