
Chapter3 First steps in R
Now that we’ve started to familiarize ourselves with our tool of choice, we can finally get down to business and focus on writing code!
In this chapter, we will take our first steps in R. We’ll begin by learning how to use mathematical, relational, and logical operators to perform simple operations in R. Learning R is a long journey (spoiler: this journey never really ends since R is constantly evolving). Especially at the beginning, it may seem overly difficult because you’re encountering many programming commands and concepts for the first time. However, once you’ve become familiar with the basics, progress will speed up considerably (unstoppable, we would say!).
In this chapter, we will introduce many elements for the first time that will be revisited and explored in greater depth in later chapters. So don’t worry if not everything is clear right away. Learning your first programming language is hard, but you have to start somewhere. Ready for your first lines of code? Let’s become a useR!
3.1 Mathematical Operators
R is a great calculator. In Table 3.1, the main mathematical operators and functions used in R are listed.
Function | Name | Example |
---|---|---|
x + y | Addition | > 5 + 3 <br/>[1] 8 |
x - y | Subtraction | > 7 - 2 <br/>[1] 5 |
x * y | Multiplication | > 4 * 3 <br/>[1] 12 |
x / y | Division | > 8 / 3 <br/>[1] 2.666667 |
x %% y | Modulo | > 7 %% 5 <br/>[1] 2 |
x %/% y | Integer Division | > 7 %/% 5 <br/>[1] 1 |
x ^ y | Power | > 3 ^ 3 <br/>[1] 27 |
abs(x) | Absolute Value | > abs(3-5^2) <br/>[1] 22 |
sign(x) | Sign of an Expression | > sign(-8) <br/>[1] -1 |
sqrt(x) | Square Root | > sqrt(25) <br/>[1] 5 |
log(x) | Natural Logarithm | > log(10) <br/>[1] 2.302585 |
exp(x) | Exponential | > exp(1) <br/>[1] 2.718282 |
sin(x)<br/>cos(x)<br/>tan(x)<br/>asin(x)<br/>acos(x)<br/>atan(x) | Trigonometric Functions | >sin(pi/2) <br/>[1]1 <br/>>cos(pi/2) <br/>[1]6.123234e-17 |
factorial(x) | Factorial | > factorial(6) <br/>[1] 720 |
choose(n, k) | Binomial Coefficient | > choose(5,3) <br/>[1] 10 |
Notice how specific functions are used to perform operations like square root or absolute value. In R, functions are called by typing <function-name>()
(e.g., sqrt(25)
) and placing the arguments of the function inside the parentheses. We will explore functions in more detail in Chapter 4.2.
3.1.1 Order of Operations
When performing operations, R follows the same order used in regular mathematical expressions. Therefore, the precedence of operators is:
^
(power)%%
(remainder of a division) e%/%
(integer division)*
(multiplication) e/
(division)+
(addition) e-
(subtraction)
Note that in the presence of functions (e.g., abs()
, sin()
), R first replaces the functions with their results and then proceeds with the operations in the previously indicated order.
The order of operation execution can be controlled by using parentheses ( )
. R will perform all the operations inside the parentheses following the same order indicated above. By using multiple groups of parentheses, we can achieve the desired results.
Note that in R only round parentheses ( )
are used to manage the order of execution of operations.
Square brackets [ ]
and curly brackets { }
are instead special operators used in R for other purposes, such as selecting elements and defining code blocks. (See also Chapter 7.2)
Exercises
Calculate the result of the following operations using R:
\(\frac{(45+21)^3+\frac{3}{4}}{\sqrt{32-\frac{12}{17}}}\)
\(\frac{\sqrt{7-\pi}}{3\ (45-34)}\)
\(\sqrt[3]{12-e^2}+\ln(10\pi)\)
\(\frac{\sin(\frac{3}{4}\pi)^2+\cos(\frac{3}{2}\pi)}{\log_7{e^{\frac{3}{2}}}}\)
\(\frac{\sum_{n=1}^{10} n}{10}\)
Notes for solving the exercises:
- In R, the square root is obtained with the function
sqrt()
, while for roots of different indices, the exponential notation is used (\(\sqrt[3]{x}\) is given byx^(1/3)
). - The value of \(\pi\) is obtained with
pi
. - The value of \(e\) is obtained with
exp(1)
. - In R, logarithms use the function
log(x, base=a)
, where the natural logarithm is considered by default.
3.2 Relational and Logical Operators
These operations may not seem particularly interesting at the moment, but they will prove very useful later on, for example, for selecting elements (see Chapter 7.2.1).
3.2.1 Relational Operators
In R, you can evaluate whether a given relationship is true or false. For example, we can evaluate whether “2 is less than 10” or whether “4 is an even number.”
R will evaluate the propositions and return the value TRUE
if the proposition is true or FALSE
if the proposition is false. In Table 3.3, the relational operators are listed.
Function | Name | Example |
---|---|---|
x == y | Equal | > 5 == 3 <br/>[1] FALSE |
x != y | Not equal | > 7 != 2 <br/>[1] TRUE |
x > y | Greater than | > 4 > 3 <br/>[1] TRUE |
x >= y | Greater than or equal to | > -2 >= 3 <br/>[1] FALSE |
x < y | Less than | > 7 < 5 <br/>[1] FALSE |
x <= y | Less than or equal to | > 7 <= 7 <br/>[1] TRUE |
x %in% y | inclusion | > 5 %in% c(3, 5, 8) <br/>[1] TRUE |
Be careful that to evaluate the equality between two values, you must use==
, not =
. This is a very common mistake made frequently.
The =
operator is used in R to assign a value to a variable. This topic will be covered in Chapter 4.1.1.
Note that in any programming language, the values TRUE
and FALSE
correspond to the numerical values 1
and 0
, respectively. These are called boolean values.
In R, it is also possible to abbreviate TRUE
and FALSE
as T
and F
, respectively, although this practice is not recommended as it could generate confusion. Indeed, while TRUE
and FALSE
are reserved words (see Chapter 4.1.2), T
and F
are not (i.e., the latter can also serve as names for any other user-defined variables, thus generating confusion).
3.2.2 Logical Operators
In R, it is possible to combine multiple relations to evaluate a desired proposition. For example, we could evaluate whether “17 is greater than 10 and less than 20.” To combine multiple relations into a single proposition that R will evaluate as TRUE
or FALSE
, the logical operators shown in Table 3.5 are used.
Function | Name | Example |
---|---|---|
!x | Negation | > !TRUE <br/>[1] FALSE |
x & y | Conjunction | > TRUE & FALSE <br/>[1] FALSE |
x | y | Inclusive Disjunction | > TRUE | FALSE <br/>[1] TRUE |
These operators are also known as boolean operators and follow the common definitions of logical operators. Specifically:
- In the case of logical conjunction
&
, for the proposition to be true, both relations must be true. In all other cases, the proposition will be evaluated as false (see Table 3.7).
x | y | x & y |
---|---|---|
TRUE | TRUE | TRUE |
TRUE | FALSE | FALSE |
FALSE | TRUE | FALSE |
FALSE | FALSE | FALSE |
- In the case of inclusive logical disjunction
|
, for the proposition to be true, at least one relation must be true. The proposition will only be evaluated as false when both relations are false (see Table 3.9).
x | y | x | y |
---|---|---|
TRUE | TRUE | TRUE |
TRUE | FALSE | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | FALSE |
For completeness, we should mention that there is also the exclusive disjunction among the logical operators. The proposition will be evaluated as false if both relations are either true or false. For the proposition to be evaluated as true, one relation must be true while the other must be false.
In R, the exclusive disjunction between two relations (x and y) is indicated with the function xor(x, y)
. However, this function is rarely used.
x | y | xor(x, y) |
---|---|---|
TRUE | TRUE | FALSE |
TRUE | FALSE | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | FALSE |
3.2.3 Order of Evaluation of Relations
When evaluating the truthfulness of propositions, R executes the operations in the following order:
- Mathematical operators (e.g.,
^
,*
,/
,+
,-
) - Relational operators (e.g.,
<
,>
,<=
,>=
,==
,!=
) - Logical operators (e.g.,
!
,&
,|
)
The complete list of the order of operation execution is available at the following link https://stat.ethz.ch/R-manual/R-devel/library/base/html/Syntax.html. Remember that if there is any doubt about the order of operation execution, the best thing to do is to use round parentheses ( )
to clarify any possible ambiguities.
Note that the %in%
operator, which we previously indicated among the relational operators, is actually a special operator. Specifically, it does not follow the same rules as the other relational operators regarding the order of execution.
The best solution? Use parentheses!
Exercises
Perform the following exercises using relational and logical operators:
- Define two false relations and two true relations that allow you to evaluate the results of all possible combinations using the logical operators
&
and|
. - Define a proposition that allows you to evaluate whether a number is even. Define another proposition for odd numbers (hint: what does
%%
remind you of?). - Define a proposition to evaluate the following condition (remember to test all possible scenarios): “x is a number between -4 and -2 or a number between 2 and 4.”
- Perform the following operations:
4 ^ 3 %in% c(2,3,4)
and4 * 3 %in% c(2,3,4)
. What do you observe in the order of operation execution?