<- function(x){
cal_power
<- x^2; b <- x^3
a <- c(a, b)
out names(out) <- c("squared", "cubed")
# or return(out)
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
<- function(arg1, aug2, ...){
name
<FUNCTION BODY>
return(value)
}
Example
In this case
Function name:
cal_power
Function inputs:
x
Function body:
<- x^2; b <- x^3
a <- c(a, b)
out 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 { }
<- function(x){
cal_sqrt
^2
x
}
Method 2: without { }
<- function(x) x^2 cal_sqrt
4.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}}\]