1. Basics of R#

This chapter is an introduction to some basic capabilities of R. After going through the chapter you will be able to

  • use R to evaluate arithmetic expressions (use R as a calculator)

  • add comments to your code

  • assign values to variables

  • create vectors

Tip

To explore the codes below yourself you need a working R installation on your machine. Further, it is recommended to install and use RStudio (rather than the R GUI) for running the codes.

The best way to work through the chapter is to read the discussion and then reproduce all code in your own R/RStudio installation. You can do this by copying code from a notebook cell to your R script and run the code line by line.

The chapter includes some exercises that allow you to test your understanding. It is recommended that you try these exercises on your own before choosing the option to reveal the solutions.

1.1. Using R as a calculator#

R can be used as a powerful calculator.

In order to evaluate an arithmetic expression

  • enter the expression at the prompt in the command console and press Enter.

  • or enter the expression into a line of your R script and run the line.

In order to enter expressions we need to know some basic syntax.

1.1.1. Basic arithmetic operations#

  • + Addition

  • - Subtraction

  • * Multiplication

  • / Division

  • ^ Exponentiation

  • (...) Brackets

For example,

1+3
4
3/2
1.5
5*6
30
3^3
27
(2+3)^2
25

1.1.2. Respecting the order of operations#

The above syntax can be extended to arbitrarily complex arithmetic expressions.

However, make sure to respect the order of operations when entering your expression.

For example, 9^(1/2) will evaluate \(9^\frac{1}{2}\) while 9^1/2 will evaluate \(9^1/2\)

9^(1/2)
3
9^1/2
4.5

As another example, (4+5)*3 will evaluate \((4+5)\times 3\), while 4+5*3 will evaluate \(4+5\times 3\)

(4+5)*3
27
4+5*3
19

Here are some more complicated examples:

To evaluate \(2(1+3)^{1/2}+5^3\) type

2*(1+3)^(1/2)+5^3
129

To evaluate \([2(1+3)^{1/2}+5]^3\) type

(2*(1+3)^(1/2)+5)^3
729

To evaluate \([2(1+3)]^{1/2}+5^3\) type

(2*(1+3))^(1/2)+5^3
127.828427124746

1.1.3. Some important mathematical functions#

  • Square roots: sqrt(x) returns the square root of \(x\)

    • Note that roots can be equivalently stated as powers.

    • For example, the square root of \(x\) can be equivalently stated as \(x^{1/2}\) and evaluated as x^(1/2).

sqrt(9)
3
  • Natural exponential: exp(x) returns \(e^x\)

    • For exponential functions to a base different than \(e\) simply use power notation.

    • For example, for \(2^3\) simply type 2^3.

exp(3)
20.0855369231877
  • Natural logarithm: log(x) returns \(\ln(x)\)

    • Note that R uses log(...) to call the natural logarithm, i.e. \(\ln(...)\) or the logarithm to the base \(e\)

log(3)
1.09861228866811
log(exp(3))
3
  • Logarithms to other bases: log(x,a) returns \(\log_a x\), the “logarithm to the base \(a\) of \(x\).”

    • For example, log(8,2) returns \(\log_2 8 = 3\), the “logarithm to the base 2 of 8”.

log(8,2)
3

1.1.4. Evaluating complex arithmetic expressions#

By using the above syntax correctly we can evaluate arbitrarily complex arithmetic expressions.

For example, to evaluate \(\sqrt{3\times(4/2)^5} + \log_5 2 - e^5\), type

sqrt(3*(4/2)^5 + log(2,5)) - exp(3) 
-10.2656246752053

Exercise 1.1

Evaluate the following arithmetic expressions in R

a)

\[ 7\times\frac{5^2}{(3-1)^3} + 2 \]

b)

\[ \log_2 (3+2\times5) \]

c)

\[ 1 + e^{3-\sqrt{2}} \]

1.2. Adding comments to your code#

In programming you will often have to write and work through long pieces of code. Long codes can be messy and it is useful to have a way to add comments to your code - pieces of text that are not executed but help the coder explain the code (often to herself) and make it more readable.

To start a comment in R, type # somewhere on a line of code and anything that follows on the line will not be executed, but will remain on the script as a comment.

For example, we can add a comment before a line of code. The comment in itself is not executed.

# The following code evaluates the log to the base 2 of 8

log(8,2)
3

A comment can also be added on the end of a line of executable code

log(8,2) # this evaluates the log to the base 2 of 8
3

While the examples of code encountered so far are not sufficiently complex to need explanation, it is a good idea to get into the habit of writing comments in your code. These notes will often use comments to explain pieces of code.

1.3. Assigning values to variables#

Warning

The concept of a variable has distinct (although related) meanings in the contexts of mathematics and programming.

For the following discussion, adopt a programming perspective, and think of a variable as a named storage of value.

We can use variables to store values of interest, allowing us to access these values by calling the name of the variable.

In R we can assign a value to a variable by using the <- or = operators.

For example, the code a <- 2 creates a variable named a whose value is the number \(2\). The same assignment can be equivalently done by using the code a = 2.

Note

While both <- and = can be used to assign values to variables, the <- syntax is preferred (partly for historical reasons) and henceforth these notes will follow this syntax.

For example, the following code assigns the value 3 to a new variable called a

a <- 3

Now a call to a retuns the assigned value

a
3

Furthermore, we can use the variable in the place of it’s value in any operation:

a+3
6
a^2
9
a^a
27

We can assign the value of arbitrarily complex arithmetic expression to a variable. For example

b <- log(8,2) + sqrt(4)
b
5

Henceforth, any arithmetic expression involving a and b will use thee values stired in a and b to evaluate.

a+b
8

Exercise 1.2

Assing the value \(2\) to a new variable called r.

Then assign the value of the expression \(4r^2\) to a new variable called b.

Then call b to see its value.

1.4. Vectors#

For the purpose of the following discussion think of a vector (naively) as a data structure representing an ordered list of numbers.

Warning

The concept of a vector has distinct (although related) meanings in the contexts of mathematics and programming.

We will learn about the precise mathematical meaning of vectors later in the course.

However, at this stage we emphasise the programming-context meaning of vectors as a data structure, which will be needed for many of the topics discussed in these notes.

For example, the ordered list of numbers \([1,2,5,7]\) is a vector of four elements, with the first element \(1\), the second element \(2\), the third element \(5\) and fourth element \(7\). Note that this is a different vector from the vector \([1,2,7,5]\) as even though they both contain the same elements, these elements appear in different order. The order matters in a vector.

1.4.1. Constructing vectors by using the c() function#

In general, a vector of the form \([x1,x2,...,xn]\),

  • where \(x1,x2,...,xn\) are some specific numbers

  • can be constructed by typing c(x1,x2,...,xn).

For example, to construct the vector \([1,2,5,7]\) simply type c(1,2,5,7)

c(1,2,5,7)
  1. 1
  2. 2
  3. 5
  4. 7

We can also assign the value of a vector to a variable.

For example, to assign the above vector to a variable called a type

a <- c(1,2,5,7)
a
  1. 1
  2. 2
  3. 5
  4. 7

We can obtain the number of elements in a vector by using the length() function.

length(a)
4

We can access the different elements of a vector by calling the vector followed by the element’s index in square brackets. In general, given a vector named vec, then the code vec[n] returns the \(n\)-th element of the vector.

For example, to call the 4th element of the vector a above, type

a[4]
7

1.4.2. Constructing vectors of evenly spaced numbers#

In some context (especially in Plotting in R) we will need to construct vectors of evenly spaced numbers.

This can be done by using the seq() function (for sequence). In general, the code seq(from=a, to=b, by=d) creates a vector with first element a, last element b and distance d between consecutive elements.

For example, to create the vector \([1,2,3,4,5,6,7,8,9,10]\) and assign it to a variable named a we can type

a <- seq(from=1, to=10, by=1)
a
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

As another example, to create the vector \([1,1.5,2,2.5,3,...,9,9.5,10]\) and assign it to a variable named a we can type

a <- seq(from=1, to=10, by=0.5)
a
  1. 1
  2. 1.5
  3. 2
  4. 2.5
  5. 3
  6. 3.5
  7. 4
  8. 4.5
  9. 5
  10. 5.5
  11. 6
  12. 6.5
  13. 7
  14. 7.5
  15. 8
  16. 8.5
  17. 9
  18. 9.5
  19. 10

Note that exactly the same can be achieved by passing the arguments without keywords from, to and by.

a <- seq(1, 10, 0.5)
a
  1. 1
  2. 1.5
  3. 2
  4. 2.5
  5. 3
  6. 3.5
  7. 4
  8. 4.5
  9. 5
  10. 5.5
  11. 6
  12. 6.5
  13. 7
  14. 7.5
  15. 8
  16. 8.5
  17. 9
  18. 9.5
  19. 10

As discussed above we can use length() to check the number of elements, and can access specific elements by indexing with [].

For example, the number of elements of a defined above is

length(a)
19

The 12th element of a is

a[12]
6.5

Exercise 1.3

Construct a vector, called vec, of evenly spaced numbers between -5 and 5 with distance 0.25 between consecutive elements.

Find the number of elements of the vector.

Find the 13th element of the vector.

1.4.3. Constructing vectors of evenly spaced numbers using the : operator#

As seen above one way to construct a vector of evenly spaced numbers between a and b with distance 1 between consecutive elements is to use seq(from=a, to=b, by=1)

However, when the distance between elements is 1, we can also use the shorthand notation a:b instead.

For example, to construct the vector \([-3,-2,-1,0,1,2,3]\) and assign it to a variable a we can type

a <- -3:3
a
  1. -3
  2. -2
  3. -1
  4. 0
  5. 1
  6. 2
  7. 3

Note that exactly the same vector can be constructed using the seq() function

seq(from=-3,to=3,by=1)
  1. -3
  2. -2
  3. -1
  4. 0
  5. 1
  6. 2
  7. 3

The seq() function is more powerful because it also allows us to construct vectors where distance between elements is different from 1. For example, the vector constructed by seq(from=0, to=2, by=0.25) cannot be constructed using the : operator.

Nonetheless, constructing equally spaced vectors with : is a useful shorthand notation in cases when we want all elements of the vector to be consecutive integers. We will encounter such cases during the course, so you should be aware of the syntax.

This completes the chapter on Basics of R. In the next chapter we turn attention to using R for plotting functions of one variable.