R Functions

Functions are a blocks of code that perform a specific task.
They help in modularizing the code, making it more readable, maintainable, and reusable.
function_name <- function(arg1, arg2, ...) {
# Function body
# Code to perform the task
  1. function_name - Declare a function name.
  2. arg1, arg2, ... - Input parameters (arguments) either 0 or more that the function expects.
  3. return(result) - The output that the functions expects.


# Define a function
add_numbers <- function(a, b) {
  result <- a + b

# Use the function
sum_result <- add_numbers(3, 5)
print(sum_result)  # Output: 8

You can place even more arguments and can use the function any number of times

Returning Multiple Values

You can return multiple values in one function.


# Function returning multiple values
calculate_stats <- function(data) {
  mean_value <- mean(data)
  median_value <- median(data)
  return(list(mean = mean_value, median = median_value))

# Use the function
data <- c(1, 2, 3, 4, 5)
stats <- calculate_stats(data)

Here we used multiple values with its respective variable in a list form and return the values.
We use dollar ($) sign after the function name to get the value of a variable we want.

Anonymous Functions (Lambda Functions)

you can declare a statement in one line without return value


# Anonymous function (lambda function)
square <- function(x) x^2
# is equivalent to
square_lambda <- function(x) { return(x^2) }

# Use the anonymous function
result1 <- square(4)
result2 <- square_lambda(4)

Nested Functions

You can declare a function within other function


# Outer function
outer_function <- function(a, b) {
  # Nested function
  inner_function <- function(x, y) {
    result <- x + y
  # Using the nested function
  nested_result <- inner_function(a, b)
  # Returning the result

# Using the outer function
final_result <- outer_function(3, 5)
print(final_result)  # Output: 8

Quick Recap - Topics Covered

R Functions
Nested Functions

Practice With Examples in Compilers

The Concepts and codes you leart practice in Compilers till you are confident of doing on your own. A Various methods of examples, concepts, codes availble in our websites. Don't know where to start Down some code examples are given for this page topic use the code and compiler.

Example js

Example 1 Example 2 Example 3 Example 4 Example 5