Writing your first function in R
A function in R is a set of instructions for a certain task to complete. The function could take any input you define, or it could work without any input. In this recipe, you will learn how to write a function and you will learn about the components of a function.
Getting ready
Let’s say you want to calculate the ratio of the standard deviation and mean of a given vector of five numbers. The input values are (3
, 7
, 2
, 6
, 9
). To give these five values as an input to a function, you need to create a vector that contains these numbers as follows:
V1 <- c(3, 7, 2, 6, 9)
How to do it…
To write a function, the first and most important thing is the name of the function. Let's perform the following steps to write your first function in R:
- You must give a name to the new function that you are going to write. The name of the function must start with a character. The function name could start with a dot (
.
) or with an underscore (_
). Now, let’s give the name of the...