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