seq(from = 5, to = 8, by = 0.5)
[1] 5.0 5.5 6.0 6.5 7.0 7.5 8.0
One of R’s greatest strengths is its functional programming capabilities. In this chapter, we describe the main characteristics of functions in R, demonstrating them with a variety of examples. We explore mathematical functions, such as logarithmic and trigonometric functions, as well as other useful functions like round()
and ifelse()
.
Most computations in R involve the use of functions. An R function is a set of commands that are executed each time the function is called, performing a specific task. The standard version of R includes a number of built-in functions, and many others can be added or created by users (known as user-defined functions). We have already used some R functions to search for help, such as help()
and example()
.
In R, a function is called by typing its name followed by parentheses. The values provided inside the parentheses, separated by commas, are referred to as the function’s arguments.
Let’s have look at an example:
seq(from = 5, to = 8, by = 0.5)
[1] 5.0 5.5 6.0 6.5 7.0 7.5 8.0
The function name is seq
, and we pass three named arguments from = 5
, to = 8
and by = 0.5
. The arguments from = 5
and to = 8
specify the starting and ending values of the sequence we want to create, while by = 0.5
defines the increment between each value in the sequence.
The above result can also be obtained without naming the arguments, as shown below:
seq(5, 8, 0.5)
[1] 5.0 5.5 6.0 6.5 7.0 7.5 8.0
INFO
We don’t need to specify the names of the arguments; instead, we can simply pass the values in the correct order, and R will match each value to its corresponding argument based on their position—this is known as positional matching.
Additionally, the seq()
function provides several other arguments, which are documented on its help page and can be accessed by running ?seq
:
seq(from = 1, to = 1, by = ((to - from)/(length.out - 1)), length.out = NULL, along.with = NULL, ...)
For example, instead of specifying by = 0.5
, we can use the argument length.out = 26
to create a sequence of 26 numbers as follows:
seq(5, 8, length.out = 26) # 26 numbers in the sequence
[1] 5.00 5.12 5.24 5.36 5.48 5.60 5.72 5.84 5.96 6.08 6.20 6.32 6.44 6.56 6.68 6.80
[17] 6.92 7.04 7.16 7.28 7.40 7.52 7.64 7.76 7.88 8.00
Note that when R prints a long sequence of values, it automatically splits the output across multiple lines for readability. The numbers in square brackets indicate the index of the first value on each line within the full sequence. In this example, [1]
indicates the position of 5.00
, which appears first on the first line, while [17]
indicates the position of 6.92
, which appears first on the second line. (These indices may differ in your console, as the number of values displayed per line depends on the available console width.)
Now, consider this command:
seq(5, 8)
[1] 5 6 7 8
This generates a sequence running from 5 to 8. Since no step size is specified, the default increment step is calculated as by=((to - from)/(length.out - 1)) = (8-5)/(4-1) = 1, which is then passed to the seq()
function.
Let’s explore another example. The log()
is a mathematical function that calculates logarithms. To display its argument names along with their default values, we can use the args()
function, as shown below:
args(log)
function (x, base = exp(1))
NULL
In the log()
function, x
is a required argument, while base
is an optional argument and has a default value of exp(1)
.
x
is a required argument because if it is not provided to the function, the calculation will fail (i.e., the logarithm is undefined), resulting in an error:log(base = 10)
Error: argument x is missing, with no default
base
, log()
function will use exp(1)
by default:log(15) # in R, the default base for the log function is e (i.e., exp(1))
[1] 2.70805
However, if we provide the argument base = 10
, the log()
function will calculate the base-10 logarithm:
log(15, base = 10) # the log function uses the specified base 10
[1] 1.176091
IMPORTANT
In R functions, some arguments are required and must be provided, while others are optional because they have default values specified in the function definition.
Next, let’s calculate the natural logarithm of 3 (base =
log(3)
[1] 1.098612
All of the following expressions are equivalent:
However, the following expression is not equivalent:
Moreover, it’s important to note that not all functions have or require arguments to work. For example:
date()
[1] "Fri Sep 12 12:35:00 2025"
The date()
function in R returns the current date and time as a character string.
R has many built-in mathematical functions such as the log(x)
that we have already seen.
Logarithms
log(5) # natural logarithm (or base-e logarithm)
[1] 1.609438
There are even built-in logarithmic functions with different bases:
Exponents
exp(5) # Calculates Euler's number (e ≈ 2.718) raised to the power of 5
[1] 148.4132
Trigonometric functions describe the associations between the sides and angles of a right-angled triangle. They also allow us to use angle measurements, either in radians or degrees, to determine the coordinates of any point on a circle, such as the unit circle. In R, trigonometric functions operate on angles measured in radians by default.
sin(pi/2) # sine of pi/2 (pi approximately equals to 3.14)
[1] 1
cos(pi) # cosine of pi
[1] -1
tan(pi/3) # tangent of pi/3
[1] 1.732051
sqrt(9) # returns the squared root of a number
[1] 3
abs(-9) # returns absolute value of a number
[1] 9
sign(-9) # returns the sign of a number (-1 if negative, 0 if zero, 1 if positive)
[1] -1
factorial(3) # factorial (e.g., 3! = 1x2x3)
[1] 6
round()
functionThe round()
function, which follows the rounding principle, is commonly used for rounding numbers. By default, it returns the nearest integer. For example:
round(7 / 3) # rounding 7/3 (2.333) to the nearest integer
[1] 2
To control the precision of the result, we can use the digits
argument to specify the desired number of decimal places. For example:
round(7 / 3, digits = 2) # rounding 7/3 to two decimal places
[1] 2.33
When the first digit to be dropped is exactly 5, the round()
function follows a commonly used rule in programming: it rounds to the nearest even number. For example:
round(1.5) # it rounds 1.5 to the nearest even number, which is 2
[1] 2
round(2.5) # it rounds 2.5 to the nearest even number, which is 2
[1] 2
There are a couple of additional functions that can be useful for rounding numbers:
ceiling(16.2) # round up to the nearest integer
[1] 17
floor(16.2) # round down to the nearest integer
[1] 16
trunc(125.2395) # truncates the decimal places, removing any fractional part
[1] 125
ifelse()
functionIn R, the ifelse()
function evaluates a logical condition and returns one of two specified values depending on whether the condition is TRUE
or FALSE
. The syntax is straightforward: ifelse(condition, value_when_true, value_when_false)
.
Let’s demonstrate its usage with basic examples:
ifelse(0.7 > 0.5, 1, 0)
[1] 1
In this example, ifelse()
checks if 0.7 is greater than 0.5. Since the condition is TRUE
, the function returns 1.
ifelse(0.3 > 0.5, 1, 0)
[1] 0
Here, the condition is FALSE
because 0.3 is not greater than 0.5, so the function returns 0.
We can create our own functions using function()
, which provides a powerful way to extend R’s capabilities and reuse code efficiently.
The essential parts of a function are:
The function’s name
The arguments (or parameters) of the function
The function’s body (the code statements)
Here’s a simple example of a function that calculates the logarithm of a number to base 7:
log7 <- function(x) {
log(x, base = 7)
}
# calculate the logarithm of 5 to base 7
log7(5)
[1] 0.8270875
In this example, the function is defined by assigning the function(x)
object to the name log7
using the assignment operator (<-
). (A detailed discussion of objects and assignment operators is presented in Chapter @ref(robjects)). The x
argument within the parentheses of function()
serves as the input, while the code within the curly braces {}
forms the function body—the code block that is executed when the function is called.