
Your Success, Our Mission!
6000+ Careers Transformed.
A function is a block of code that performs a specific task. R provides a wide range of built-in functions to perform common operations easily.
Common Built-in Functions
Function | Purpose |
| mean() | Calculate average |
| sum() | Add values |
| length() | Count elements |
| min() / max() | Find smallest / largest value |
| summary() | Statistical summary |
| str() | Structure of data |
Example
| numbers <- c(10, 20, 30, 40) mean(numbers) sum(numbers) length(numbers) |
Built-in functions save time and reduce the need to write repetitive code.
Why Create Your Own Functions?
User-defined functions help:
Syntax of a Function
| function_name <- function(arguments) { # function body return(output) } |
Example
| add_numbers <- function(a, b) { result <- a + b return(result) } add_numbers(5, 10) |
Functions with Default Values
| greet <- function(name = "User") { paste("Hello", name) } |
What are Conditional Statements?
Conditional statements allow R to execute code based on conditions.
if Statement
| score <- 75 if (score >= 50) { print("Pass") } |
if...else Statement
| if (score >= 50) { print("Pass") } else { print("Fail") } |
if...else if...else
| if (score >= 90) { print("Excellent") } else if (score >= 60) { print("Good") } else { print("Needs Improvement") } |
Vectorized Condition: ifelse()
| marks <- c(40, 60, 80) ifelse(marks >= 50, "Pass", "Fail") |
Why Use Loops?
Loops are used to repeat a block of code multiple times.
R provides three main loop structures:
for Loop
| for (i in 1:5) { print(i) } |
Used when the number of iterations is known.
while Loop
| i <- 1 while (i <= 5) { print(i) i <- i + 1 } |
Used when repetition depends on a condition.
repeat Loop
| i <- 1 repeat { print(i) i <- i + 1 if (i > 5) { break } } |
Loop Control Statements
break → exits the loop
next → skips current iteration
| for (i in 1:5) { if (i == 3) next print(i) } |
Top Tutorials
CNN in Deep Learning 2026
A beginner-friendly guide to CNNs: understand deep learning essentials, create Python-based models, and explore advanced applications.
Breaking The Limits: Scaling Databases with MySQL Partitioning
Learn MySQL partitioning with examples. Improve query performance, scalability, and data management using RANGE, LIST, HASH, KEY, and composite techniques.
ML in Action: Hands-On Guide to Deploying and Serving Models
Learn model deployment and serving—from concepts to real-world architectures, tools, APIs, containers, and cloud workflows for production-ready ML.
All Courses (6)
Master's Degree (2)
Fellowship (2)
Certifications (2)