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.

Syntax
function_name <- function(arg1, arg2, ...) {
# Function body
# Code to perform the task
return(result)
}

  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.
Example
# Define a function
add_numbers <- function(a, b) {
  result <- a + b
  return(result)
}

# 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.

Example
# 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)
print(stats$mean)
print(stats$median)

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

Example
# 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

Example
# Outer function
outer_function <- function(a, b) {
  
  # Nested function
  inner_function <- function(x, y) {
    result <- x + y
    return(result)
  }
  
  # Using the nested function
  nested_result <- inner_function(a, b)
  
  # Returning the result
  return(nested_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 1
Example 1 Example 2 Example 3 Example 4 Example 5


Quiz


FEEDBACK