In R, you can create your own functions to perform specific tasks. Here are some examples of creating functions, using parameters, and return statements:
## Creating functions
# Define a function to calculate the mean of a vector
mean_vector <- function(x) {
sum_x <- sum(x)
n_x <- length(x)
mean_x <- sum_x / n_x
return(mean_x)
}
# Use the function to calculate the mean of a vector
x <- c(1, 2, 3, 4, 5)
mean_x <- mean_vector(x)
print(mean_x)
In this code, we first define a function called `mean_vector` that takes a single parameter, `x`. Inside the function, we calculate the sum of `x`, the length of `x`, and then the mean of `x`. Finally, we use the `return()` function to return the mean of `x`. We then use the function to calculate the mean of a vector `x` and print the result.
## Parameters
# Define a function to calculate the area of a rectangle
area_rectangle <- function(length, width) {
area <- length * width
return(area)
}
# Use the function to calculate the area of a rectangle
length <- 5
width <- 6
area <- area_rectangle(length, width)
print(area)
In this code, we define a function called `area_rectangle` that takes two parameters, `length` and`width`. Inside the function, we calculate the area of a rectangle as the product of `length` and `width`. We then use the `return()` function to return the area. We then use the function to calculate the area of a rectangle with a length of 5 and a width of 6, storing the result in the `area` variable, and then print the result.
## Return statements
# Define a function to check if a number is even
is_even <- function(x) {
if (x %% 2 == 0) {
return(TRUE)
} else {
return(FALSE)
}
}
# Use the function to check if a number is even
num <- 4
even <- is_even(num)
print(even)
In this code, we define a function called `is_even` that takes a single parameter, `x`. Inside the function, we use an if-else statement to check if `x` is even using the modulo operator `%%`. If `x` is even, we use the `return()` function to return `TRUE`, and if `x` is odd, we use the `return()` function to return `FALSE`. We then use the function to check if the number `num` is even, storing the result in the `even` variable, and then print the result.
Note that there are many other ways to define and use functions in R, including using default parameter values, variable-length parameter lists, and anonymous functions. You can find more information on these techniques in the R documentation or online tutorials and resources.