numbers <- c(1, 2, 3, 4, 5) # Create a vector of numbers
mean(numbers) # Calculate the mean of the numbers[1] 3
Functions in R are blocks of code designed to perform specific tasks.
They can take input, process the data, and return a result.
R includes many built-in functions that you can use right away, such as mean(), sum(), and sqrt().
Example: Using the mean() function:
numbers <- c(1, 2, 3, 4, 5) # Create a vector of numbers
mean(numbers) # Calculate the mean of the numbers[1] 3
function_name <- function(argument1, argument2, ...) {
# Code that performs some task
result <- argument1 + argument2 # Example of an operation
return(result) # Return the result
}add_numbers <- function(a, b) {
sum <- a + b # Add the two numbers
return(sum) # Return the result
}add_numbers(3, 5) # Call the function with two arguments[1] 8
add_numbers() takes two inputs, a and b.# symbol to add a comment. Everything after # on the same line is ignored by R.# This function adds two numbers together
add_numbers <- function(a, b) {
sum <- a + b # Add the two input numbers
return(sum) # Return the result
}
# Call the function with arguments 3 and 5
add_numbers(3, 5)[1] 8
Functions in R often return a value after performing their operations.
The return() statement is used to output the result from a function.
If no return() is specified, R automatically returns the last expression evaluated.
Example: A function that multiplies two numbers:
multiply_numbers <- function(x, y) {
product <- x * y # Multiply the inputs
return(product) # Return the result
}multiply_numbers(4, 6)[1] 24
mean() and how to create your own custom functions in R.