R Functions

R Tutorial

📘 R Functions – Complete Guide (Beginner → Advanced)

In R Functions is a reusable block of code that performs a specific task. Functions make programs shorter, cleaner, reusable, and easier to debug.


1️⃣ What is a R Functions?

A function:

  • Takes input (arguments)

  • Performs operations

  • Returns an output

👉 It has many built-in functions, and users can also create custom functions.


2️⃣ Built-in Functions in R

Examples of commonly used functions:



3️⃣ Creating a User-Defined Function

Syntax


Example


 

Output

[1] 10

4️⃣ Function Without Arguments


 


5️⃣ Function with One Argument


 


6️⃣ Function with Multiple Arguments


 


7️⃣ Default Arguments


 


8️⃣ Returning Multiple Values (Using List)


 


9️⃣ Anonymous (Lambda) Functions

Functions without names, mostly used inside other functions.



🔟 Recursive Functions

A function calling itself.


 


1️⃣1️⃣ Conditional Logic Inside Functions


 


1️⃣2️⃣ Why Use Functions?

✔ Code reusability
✔ Easy maintenance
✔ Better readability
✔ Modular programming
✔ Important for exams & interviews


📌 Common Mistakes

❌ Forgetting return() (sometimes optional but risky)
❌ Wrong argument order
❌ Missing base case in recursion
❌ Overusing global variables


✅ Summary

  • Functions are created using function()

  • Can have arguments, default values, and return values

  • Support recursion, anonymous functions, and lists

  • Core concept for R programming mastery

You may also like...