R as a calculator

R is a very complete calculator that allows you to perform from simple arithmetic operations to solve complex equations. The basic arithmetic operators for addition, subtraction, multiplication and division in R are:

2+2  ## addition
[1] 4
2-2  ## subtraction
[1] 0
2*2  ## multiplication
[1] 4
2/2  ## division
[1] 1

You can pass multiple operations in a single line of code, but keep in mind that some operators have priorities over others, so use parameters to keep the desired operation order.

2+3+5+10+25-2  ## multiple operations
[1] 43
2+3*4  ## multiplications and divisions are done first
[1] 14
2+10/5
[1] 4
3^2/2  ## but power comes first
[1] 4.5
# Parenthesis are useful to determine the order of operations
3^(2/2)
[1] 3

R deals with large numbers using the e character followed by the number of positions the decimal point will move. If the number is positive, the decimal point moves to the right; if negative it moves to the left.

1.2e3 
[1] 1200
1.2e-2 
[1] 0.012

Logical operators

Boolean algebra (operations that return True or False values) can be done using the == (double equal signs = “equals to”) and != (“not” operator (!) followed by equal sign = “differs from”) logical operators:

1 == 1
[1] TRUE
1 == 2
[1] FALSE
1 != 1
[1] FALSE
1 != 2
[1] TRUE

The returned values from Boolean operations are TRUE and FALSE (always in capital letters), which can also be expressed by the single capital letters T and F, respectively.

T == TRUE
[1] TRUE
F == FALSE
[1] TRUE

“Greater than” (>), “smaller than or equal to” (<=), “and” (&), “or” (|) are all logical operators that can be used in R.

1 & 2 > 3  ## 1 and 2 are greater than 0
[1] FALSE
1 | 10 <= 5  ## 1 or 10 is smaller or equal to 5
[1] TRUE

Additional signs

Two dots (:) can be used to create a sequence.

1:10
 [1]  1  2  3  4  5  6  7  8  9 10
2.5:5.5
[1] 2.5 3.5 4.5 5.5

And the modulo operation (the remainder of a division) can be done using “%%”:

2%%2
[1] 0
3%%2
[1] 1

Missing and null values

Missing values in R are represented by the special object NA (“not available”). NAs reserve space in a vector, which is important to keep the original dimensions, but they can be very annoying when using some functions. We will see how to identify and deal with them in the Functions section. On the other hand, the special object NULL represents the absence of a value and indicates that an object contains no data. It can be used for example to create an object that will be fill with values later in a function to to remove the content of a preexisting object.