In R, a function is a set of statements organized together to perform a specific task. R has a number of built-in functions, and you can also create your own functions, which are known as user-defined functions.
Basic structure of a function in R
function_name <- function(arg1, arg2, ...){ # Function body # Computation goes here return(value)
}
Built-in Functions in R
R provides a plethora of built-in functions for various tasks. For instance:
- Arithmetic functions: sum(), mean(), etc.
- Statistical functions: lm(), t.test(), etc.
- Graphics-related: plot(), hist(), etc.
Example:
# Using the built-in mean function
values <- c(2, 4, 6, 8, 10)
average <- mean(values)
print(average) # Outputs: 6
User-defined Functions
You can create your own functions in R for tasks that you perform frequently or to encapsulate complex logic.
Example:
Let's create a function that calculates the square of a number:
# Defining the function
square <- function(x) { return(x^2)
}
# Using the function
result <- square(5)
print(result) # Outputs: 25
Another example, a function to calculate the factorial of a number:
factorial_calc <- function(n) { if(n <= 1) { return(1) } else { return(n * factorial_calc(n-1)) }
}
print(factorial_calc(5)) # Outputs: 120
Functions with Default Arguments
You can define default values for function arguments. If the function is called without the argument value, it will use the default value.
Example:
# A function to raise a number to a power with a default power of 2
power_function <- function(base, exponent = 2) { return(base^exponent)
}
print(power_function(3)) # Outputs: 9, since it uses the default exponent of 2
print(power_function(3, 3)) # Outputs: 27
In practice, R's capability to handle and create functions is a crucial aspect of the language, especially for data analysis workflows. Functions help to modularize and reuse code, making the overall analysis more organized and manageable.