For our first steps in R let’s explore the RStudio console, in which we can execute our firts commands.

Note: To clean the text in the console use the shortcut (ctrl + L)

Note: To clean the text in the console use the shortcut (ctrl + L)

1. R as a calculator (basic operations)

In R we can make basic operations like addition (+), substraction (-), multiplication (*) and division (/).

2+5
## [1] 7
3-1
## [1] 2
2*4.5
## [1] 9
3/2
## [1] 1.5

We can also make compound operation joining basic operations, for this case it’s a good idea to use parentheses to define the precedence (Order in which the operations are evaluated), for example the sum and the substraction operations have less prescedence than operations like multiplication and division in R as we can see in this example:

6 + 3 * 7
## [1] 27
(6+3)*7
## [1] 63

Another basic operations that R has are the integer division (%/%), remainder (%%) y and exponentation (^).

3%/%2
## [1] 1
7%/%3
## [1] 2
2^8
## [1] 256

2. Logic or Boolean Operators

The logic values in R are TRUE and FALSE and with them we can generate a set of operations that has as result one of this values, this operators are called logic or boolean operators; we can find the equality (==), inequality (!=), less than (<), more than (>), less or equal (<=), more or equal (>=), and (&) and or (||).

7 == 3
## [1] FALSE
4 < 8
## [1] TRUE
2 >= -4
## [1] TRUE
(0 < 1) & (5 != 8 - 3)
## [1] FALSE

Until now all of the operators that we have seen are binary operators (need two entities to be evaluated), an unary operator(just need one entity to be evaluated) is the negation operator, not (!).

!TRUE
## [1] FALSE
!((2^8 == 8^2) || (2+2 != 2*2 ))  
## [1] TRUE

3. Variables and assignment operators

The variables in R, as in most of the programming languages, are entities made of a storage address and a symbolic name or alias, we use them to save data and ease its usage. To create a variable in R we just need choose a name and assign a value (two variables can’t have the same name), to assign the value we can use the assignment operators (<-) (=).

variable1 = 2;
variable2 <- variable1^5;
variable3 = variable2/variable1; variable3
## [1] 16

As we can see at the end of each assignment statement there is a semicolon (;), this is made to separate the instrucions, also if we want to see the value of a variable we just need write the variable name and skip the (;) this will tell R to show in console the variable’s value; if we want to see the values of the variables consecutively, we should do it as follows:

variable1; variable2; variable3
## [1] 2
## [1] 32
## [1] 16

Note: The upperase in the variable name matters, for example: Var and var are two diferent variables

In the right upper corner we can see something like that:

This is the Enviroment tab, here we can find the variables that we have recently created and their values. To delete them we just click in the broom icon or select the Session tab and choose the option Clear Workspace…

4. Constants and Math Functions

R includes functions like square root sqrt(), exponential and logarithmic functions exp(), log(), log10(), trigonometric functions sin(), cos(), tan(), absolute value abs(), rounding functions celiling(), floor(), trunc(), round(), signif(), in addition, there are constants like \(\pi\), here we have some examples of their usage:

sin(45*pi/180)
## [1] 0.7071068
sqrt(81)
## [1] 9
exp(1)
## [1] 2.718282

If we want to know more information about a function we write in the console the question mark (?) and the function name. For example:

?trunc

After doing that, we can see something similar to what the image shows us, this is the help tab and offers us the R’s documnetation, here we can see how to use the function, some examples and others details.

Some useful constants in R are (letters LETTERS), we can see the content of this constants writing the name in the console line.

letters
##  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
## [20] "t" "u" "v" "w" "x" "y" "z"
LETTERS
##  [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
## [20] "T" "U" "V" "W" "X" "Y" "Z"

As we can see the letters are between double quotes ("") that is because the way to save a word is using the string data type and here you can see how to define it:

string = "Hello World"; string
## [1] "Hello World"

5. Vectors and Matrices

5.1 Define Vectors

A vector is a set of values that has an order and are index (we can access to a value in a vector with its index, usually an integer) and we can assign a vector to a variable. In R there are many ways to define a vector, the most basic way is for extension (Specify each elements one by one). Every element in the vector must have the same type.

To create vectors by extension we can use the next commands:

vec1 = c(1, "one", 3.6666, pi); 
num <- 2^4;
vec2 = c(num, sin(pi), floor(4.5), 3)

Note: The vec1 only has strings values

Another way to create a vector is using the funtion scan() this function only reads by default real numbers, after writting and executing the function we can insert a list of numbers separated by a space, to finish the function execution we have to press the enter key twice.

To create vectors by comprehension we can use the next commands, (the (a:b) indicates a range of integer numbers starting in \(a\) and ending in \(b\))

vec3 = c(1:5, 5:1);
vec4 <- 1:6
5.2 Vector attributes and elements

Vectors have some attributes like the type of the values that are contained and its length, to know this atributes we can use the following comands:

length(vec4)
## [1] 6
typeof(vec1)
## [1] "character"

As we can see the type of the vec1 is "character" it means that the vector contains characters (a string with a single letter) or strings, if we want to access to an element of the vector we can use the ([]) operator, for example:

vec1[3]
## [1] "3.6666"
vec3[6:length(vec3)]
## [1] 5 4 3 2 1
vec2[c(1,4)]
## [1] 16  3
5.3 Operations with vectors

We can perform a basic operation among scalars and vectors, if you are doing operations betweent two vectors it is made entry by entry, if we want perform a scalar product between two vectors you must use the (%*%) operators.

x = c(1,2,3,4); 3*x; 3 + x
## [1]  3  6  9 12
## [1] 4 5 6 7
y <- c(1/2, 1/4, 1/9, 1/8); x*y; x + y; x%*%y
## [1] 0.5000000 0.5000000 0.3333333 0.5000000
## [1] 1.500000 2.250000 3.111111 4.125000
##          [,1]
## [1,] 1.833333
5.4 Define Matrices

A matrix in R is a two dimensional data structure that allow us to manage our information in an easier way with some other attributes than a vector has. It can be seen as a vector made of vectors and we have a severals way to create a matrix in R, for this we use the rbind() and cbind() that means row bind and column bind:

x1 = c(1:3);
x2 = c(5:7);
x3 = c(9:11);
Matrix1 <- rbind(x1,x2,x3);
Matrix2 <- cbind(x1,x2,x3);

Now we also can use the matrix() function to define them:

# This is a comment and what i write here will not be executed
myMatrix = matrix(1:9,nrow = 3, ncol = 3); # nrow (number of rows) ncol (number of columns)
# The same matrix is obtained using only one dimension
# myMatrix <- matrix(1:9, nrow = 3);
myMatrix1 = matrix(1:9, nrow = 3, byrow = TRUE) # fill the matrix by rows
5.5 Matrix attributes and elements

We can assign additional attributes to the matrices in order to organice its information in a better way. To get the attributes of a matrix we use the function attributes().

colnames(myMatrix) <- c("A", "B","C"); # Columns names
rownames(myMatrix) <- c("x", "y","z"); # Rows names
attributes(myMatrix); myMatrix
## $dim
## [1] 3 3
## 
## $dimnames
## $dimnames[[1]]
## [1] "x" "y" "z"
## 
## $dimnames[[2]]
## [1] "A" "B" "C"
##   A B C
## x 1 4 7
## y 2 5 8
## z 3 6 9

We can access to a matrix’s values using the operator ([]). In this case, since a matrix has two dimensions we need to indicate the rows, separate it with a coma and then indicate the columns we are looking for, just like this:

myMatrix1;
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
## [3,]    7    8    9
myMatrix1[1,3];
## [1] 3
myMatrix[1:3,2]
## x y z 
## 4 5 6
5.6 Operatorations with Matrices

Finally, the operations with matrices are similar to the operations with vectors. But here you can calculate the transpose t(A), its diagonal diag(A), some cross products crossprod(A,B) and another functions, also the result of the operator (==) between two matrices will give us a matrix full of boolean entries with the same dimensions as the pair we are comparing.

myMatrix1 * myMatrix;
##    A  B  C
## x  1  8 21
## y  8 25 48
## z 21 48 81
myMatrix1 + myMatrix;
##    A  B  C
## x  2  6 10
## y  6 10 14
## z 10 14 18
1/2*myMatrix;
##     A   B   C
## x 0.5 2.0 3.5
## y 1.0 2.5 4.0
## z 1.5 3.0 4.5
myMatrix - 1;
##   A B C
## x 0 3 6
## y 1 4 7
## z 2 5 8
myMatrix == t(myMatrix1)
##      A    B    C
## x TRUE TRUE TRUE
## y TRUE TRUE TRUE
## z TRUE TRUE TRUE