Understanding how to define and use functions in R
Functions in R are blocks of code that perform a specific task. They are defined using the function() keyword followed by the function name and parameters.
# Define a function to calculate the square of a number
square <- function(x) {
return(x^2)
}
# Call the function
result <- square(5)
print(result) # Output: 25Functions can take parameters as input and return values as output. Parameters are specified within the parentheses in the function definition, and the return keyword is used to specify the return value.
# Function with parameters and return value
add <- function(a, b) {
return(a + b)
}
# Call the function
result <- add(3, 5)
print(result) # Output: 8You can specify default values for function parameters. If a value is not provided for a parameter during function call, the default value will be used.
# Function with default argument
greet <- function(name = "World") {
print(paste("Hello", name))
}
# Call the function
greet("John") # Output: Hello John
greet() # Output: Hello WorldRecursive functions are functions that call themselves. They are useful for solving problems that can be broken down into smaller, similar subproblems.
# Recursive function to calculate factorial
factorial <- function(n) {
if (n == 0) {
return(1)
} else {
return(n * factorial(n - 1))
}
}
# Call the function
result <- factorial(5)
print(result) # Output: 120Now that you've learned about functions in R, it's time to practice. Try the following exercises to test your understanding:
calculate_mean that takes a vector of numbers as input and returns the mean value.is_even that takes an integer as input and returns TRUE if it's even, otherwise FALSE.fibonacci to generate the nth Fibonacci number.