## 2.4 Functions

Functions take in inputs, execute commands, and return output. They are extremely useful because if we have to make a particular calculation multiple times, we can just program a function and reuse it in the future. For example, sum is a function that takes in inputs of numbers, and returns the value of all the numbers added together.

### 2.4.1 Defining a function

The most basic function is a function that has does not return any value.

Hello<- function (...) {
cat("Hello World")
}
Hello()
## Hello World

Now, we define a function called myadd that adds 2 input numbers together and returns the total value.

myadd <- function (x, y) {
return(x+y)
}
myadd(3, 4)
## [1] 7

From the example, we can see that a function consists of 2 parts, the 1st being the inputs, and the 2nd being the body of the function. When you define a function, you need to specify how many inputs the function requires. How you name them is up to you, but it is likely you will need to use the names of the inputs in the body of the function. The body of the function is where you write the code for what you want the function to do with the inputs. Do not forget to include a return statement, otherwise there will be no output shown in the console for the function.

We can also set default value of a function:

myadd <- function (x, y=1) {
return(x+y)
}
myadd(3)
## [1] 4
myadd(3, 4)
## [1] 7

Now also that since R is a vectorized program, function can take vector as imputs:

myadd <- function (x, y) {
return(x+y)
}
myadd(1:3, 3:5)
## [1] 4 6 8

### Exercise

Write the following function:

• take three numerical numbers
• calculate the product of three numerical inputs
• display the value
• return the value as function output

### 2.4.2 Assignment of function outputs

You can also store the output of a function into another variable, by assigning the output to that variable.

For example, result stores the value of add(3,4), which is 7. When you call result, you will then get the value 7.

result <- myadd(3, 4)
result 
## [1] 7

### 2.4.3 Help on function

Type a function’s name at the console, you can see the code behind. If you Type “? function’s name”, you will see its help file as in Figure 2.1.

? sum

### 2.4.4 Source code of a function

If you type the function name without bracket, then it will show the code of the function.

myadd <- function (x, y) {
return(x+y)
}
myadd
## function (x, y) {
##        return(x+y)
## }