0
0
R Programmingprogramming~5 mins

Function arguments in R Programming

Choose your learning style9 modes available
Introduction

Function arguments let you send information into a function so it can use that information to do its job.

When you want to reuse a function with different values.
When you want to make your code cleaner by avoiding repeated code.
When you want to customize what a function does each time you call it.
When you want to pass data like numbers or text into a function for processing.
Syntax
R Programming
function_name <- function(arg1, arg2, ...) {
  # code using arg1, arg2
}

Arguments are placed inside the parentheses after the function name.

You can have as many arguments as you need, separated by commas.

Examples
This function takes one argument name and prints a greeting.
R Programming
greet <- function(name) {
  print(paste("Hello," , name))
}
This function takes two numbers and returns their sum.
R Programming
add <- function(x, y) {
  return(x + y)
}
This function has a default argument times which repeats the text. If you don't give times, it repeats twice.
R Programming
repeat_text <- function(text, times = 2) {
  for(i in 1:times) {
    print(text)
  }
}
Sample Program

This program defines a function multiply that takes two numbers and returns their product. Then it calls the function with 4 and 5 and prints the result.

R Programming
multiply <- function(a, b) {
  result <- a * b
  return(result)
}

answer <- multiply(4, 5)
print(paste("4 times 5 is", answer))
OutputSuccess
Important Notes

You can give default values to arguments so they are optional when calling the function.

Arguments can be named when calling the function to make code clearer, like multiply(a = 4, b = 5).

Order matters if you don't name arguments; they match by position.

Summary

Function arguments let you send information into functions.

You can have many arguments, with or without default values.

Use arguments to make your functions flexible and reusable.