cal_power <- function(x){
a <- x^2; b <- x^3
out <- c(a, b)
names(out) <- c("squared", "cubed")
out # or return(out)
}4 Writing Your Own Functions
Sometimes we need to create our own functions for a specific purpose. They are called user-defined functions.
4.1 Syntax
Functions are created using the function()
Main components of a function
Function name
Function inputs
Function body
Function output
name <- function(arg1, aug2, ...){
<FUNCTION BODY>
return(value)
}Example
In this case
Function name:
cal_powerFunction inputs:
xFunction body:
a <- x^2; b <- x^3
out <- c(a, b)
names(out) <- c("squared", "cubed")- Function output:
out
Evaluation
cal_power(2)squared cubed
4 8
4.2 Exercise
What are the key factors to consider when selecting a function name in R?
How should function argument names be chosen for clarity and usability?
Is it necessary to explicitly use return() to output a value from a function in R?
4.3 Function with single line
Method 1: with { }
cal_sqrt <- function(x){
x^2
}Method 2: without { }
cal_sqrt <- function(x) x^24.4 Exercise
- Write a function to calculate the median.
help:
5%%2[1] 1
4%%2[1] 0
- Write a function to calculate the correlation coefficient
\[r=\frac{\sum_{i=1}^{n}(x_i-\bar{x})(y_i-\bar{y})}{\sqrt{\sum_{i=1}^n(x_i-\bar{x})^2\sum_{i=1}^n(y_i-\bar{y})^2}}\]