R Core Language Concepts
Estimated reading: 3 minutes 43 views

🧩 R Functions – Create and Use Reusable Code Blocks in R


🧲 Introduction – What Are Functions in R?

In R, a function is a reusable block of code designed to perform a specific task. Functions allow you to modularize your code, reduce repetition, and make programs easier to read, test, and debug.

R provides hundreds of built-in functions (like mean(), sum(), plot())—but you can also define your own using the function() keyword.

🎯 In this guide, you’ll learn:

  • How to define and call functions in R
  • Function parameters, return values, and default arguments
  • Scope of variables inside functions
  • Real-world examples and best practices

🛠️ Defining a Function in R

🔧 Syntax:

function_name <- function(arg1, arg2 = default) {
  # body
  return(result)
}

✅ Example:

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

greet("Alice")

🧾 Output:

[1] "Hello, Alice"

🧪 Built-in vs User-defined Functions

  • Built-in: Already available (e.g., sum(), mean(), nchar())
  • User-defined: You create them using function()
sum(c(1, 2, 3))         # Built-in
customAdd <- function(x, y) { x + y }   # User-defined
customAdd(5, 3)         # 8

🧾 Return Values in Functions

By default, R returns the last evaluated expression, but it’s good practice to use return() explicitly.

square <- function(n) {
  return(n^2)
}
square(4)   # 16

🧩 Function with Default Arguments

power <- function(base, exponent = 2) {
  return(base ^ exponent)
}
power(3)       # 9
power(3, 3)    # 27

🔁 Function with Conditional Logic

check_pass <- function(score) {
  if (score >= 60) {
    return("Pass")
  } else {
    return("Fail")
  }
}
check_pass(75)   # "Pass"

🔂 Passing Vectors to Functions

average <- function(values) {
  return(mean(values))
}
average(c(10, 20, 30))  # 20

🔒 Variable Scope Inside Functions

Variables declared inside a function are local.

outside <- 10

test <- function() {
  inside <- 5
  return(outside + inside)
}

test()       # 15
# print(inside)  # Error: object 'inside' not found

🔗 Anonymous Functions

You can create functions without naming them:

(function(x) x^2)(4)    # 16

Often used in apply() functions and inline logic.


🧠 Best Practices for Writing Functions

  • Use descriptive names (calculate_total(), not ct())
  • Keep functions short and focused on a single task
  • Use return() for clarity
  • Include default arguments when possible
  • Document what your function does with comments

📌 Summary – Recap & Next Steps

Functions help you organize, reuse, and scale your code effectively in R. They enable modular programming and are the backbone of clean, efficient R scripts.

🔍 Key Takeaways:

  • Define functions using function() keyword
  • Use parameters and return statements to customize behavior
  • Functions can have default values and conditional logic
  • Scope matters: variables inside functions are local
  • Use return() to clearly specify output

⚙️ Real-World Relevance:
Functions are essential in building data pipelines, statistical models, dashboards, and packages. They help you create repeatable analysis and automate workflows in R.


❓ FAQs – R Functions

❓ How do I return multiple values from an R function?
✅ Use a list():

multi_return <- function(a, b) {
  return(list(sum = a + b, product = a * b))
}
multi_return(2, 3)

❓ Can functions call other functions?
✅ Yes, functions can call other functions including themselves (recursion):

double <- function(x) { return(x * 2) }
apply_twice <- function(x) { return(double(double(x))) }
apply_twice(2)   # 8

❓ What is the use of anonymous functions in R?
✅ Useful in inline operations:

sapply(1:5, function(x) x^2)

❓ How can I view a function’s code in R?
✅ Simply type its name without parentheses:

mean

❓ Can I define functions inside other functions in R?
✅ Yes. This is known as nested functions and can help organize logic.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

R – Functions

Or Copy Link

CONTENTS
Scroll to Top