0
0
R-programmingHow-ToBeginner · 3 min read

How to Create Function in R: Simple Guide with Examples

In R, you create a function using the function() keyword followed by curly braces containing the code. Define parameters inside the parentheses and return values explicitly or implicitly by the last expression.
📐

Syntax

To create a function in R, use the function() keyword with parameters inside parentheses and the function body inside curly braces. The last evaluated expression is returned automatically.

  • function_name: The name you assign to your function.
  • parameters: Inputs your function accepts, separated by commas.
  • function body: Code inside curly braces that runs when the function is called.
r
function_name <- function(parameter1, parameter2) {
  # code to execute
  result <- parameter1 + parameter2
  return(result)  # optional, last line is returned by default
}
💻

Example

This example shows a function named add_numbers that takes two numbers and returns their sum.

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

result <- add_numbers(5, 3)
print(result)
Output
[1] 8
⚠️

Common Pitfalls

Common mistakes include forgetting to use function(), missing commas between parameters, or not returning a value explicitly when needed. Also, avoid naming conflicts with existing functions.

r
wrong_function <- function(a b) {
  a + b
}

# Correct version:
correct_function <- function(a, b) {
  a + b
}
📊

Quick Reference

PartDescriptionExample
function_nameName of the functionadd_numbers
parametersInputs separated by commasa, b
function bodyCode inside curly braces{ sum <- a + b; return(sum) }
returnValue returned by functionreturn(sum) or last expression

Key Takeaways

Use the function() keyword with parameters and curly braces to create a function in R.
The last expression in the function body is returned automatically if return() is not used.
Separate parameters with commas and avoid syntax errors like missing commas.
Name functions clearly and avoid overwriting existing R functions.
Test your function by calling it with arguments and printing the result.