3 First Operations

In this lesson we learn how to calculate Mathematical expressions, as well as store its results in a R object.

3.1 Common Mathematical Expressions

Let’s start by using R as a simple calculator in the console directly. So, type in the top-right panel the following expression:

[1] 7

Now, how about other, still very simple, operations?

[1] 12

Division

[1] 0.75

Exponentiation

[1] 81

Square Root

[1] 13

Natural logarithm

[1] 2.302585

Common logarithm

[1] 1

Use round brackets to group operations so that they are carried out first

[1] 34

What would happen if the round brackets were omitted?

[1] 100.6667

The argument of a function can contain arithmetic operations or mathematical expressions

[1] 4

Note that in R, you should only use parenthesis (or round brackets) but not square brackets for expressions in R.

[1] 19

Another way to ask for R to evaluate (calculate) an expression or piece of code is to select it, and click on the Run button on the right side of the first pane. Or, while selected, press Ctrl + Enter on your keyboard. Let’s see if we can reproduce the following expression in the “Source” pane (top-left), if you do it correctly, you should find 0.2193828. $[ (2^3 - 1) - log(10) ] / (3 + \sqrt{7^3 - 4})$

Lastly, there are some named objects that R provides you, like the constant $$\pi$$ or Month names and letters.

[1] 3.141593
 [1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov"
[12] "Dec"
 [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q"
[18] "R" "S" "T" "U" "V" "W" "X" "Y" "Z"