evoalgs-r-practise/intro/functions.R

65 lines
1.6 KiB
R

# Basic Function Definition
# -------------------------
# A simple function that adds two numbers
add_numbers <- function(x, y) {
sum <- x + y
return(sum)
}
# Using the function
result <- add_numbers(5, 3)
print(paste("Sum:", result))
# Function with Default Parameters
# --------------------------------
# A function with default values for parameters
multiply_numbers <- function(x, y = 2) {
product <- x * y
return(product)
}
# Using the function with default parameter
default_product <- multiply_numbers(4)
print(paste("Default Product:", default_product))
# Using the function by specifying both parameters
specified_product <- multiply_numbers(4, 3)
print(paste("Specified Product:", specified_product))
# Returning Multiple Values
# -------------------------
# A function that returns multiple values using a list
operate_numbers <- function(a, b) {
sum <- a + b
diff <- a - b
prod <- a * b
return(list(sum = sum, difference = diff, product = prod))
}
# Using the function
results <- operate_numbers(10, 5)
print("Operations Result:")
print(results)
# Variable Scope
# --------------
# A function to demonstrate variable scope
outer_function <- function() {
internal_var <- 20
inner_function <- function() {
print(paste("Accessing internal_var inside inner_function:", internal_var))
}
inner_function()
return(internal_var)
}
# Using the function
outer_result <- outer_function()
print(paste("Returned from outer_function:", outer_result))
# Anonymous Functions
# -------------------
# Using an anonymous function (a function without a name)
squared_numbers <- sapply(1:5, function(x) x^2)
print("Squared Numbers:")
print(squared_numbers)