Chapter 2 Basic Syntax

To get started, let’s use R as a simple calculator. To try it out, navigate to the console pane of RStudio and try adding two numbers by typing 5+8 into your console and press enter. You should see something like this:

> 5+8
[1] 13

The > indicates that the console is ready to accept input. The result is printed directly into the console with a preceding [1]. This indicates an index as by default R treats every number is a vector of length 1. We will talk about vectors later - for now you can safely ignore the [1].

Execution is triggered by both a newline (e.g. pressing enter) or a semicolon (;):

> 1+1; 2-4
[1] 2
[1] -2

R offers all standard arithmetic operators, including the basic operators +, -, * and / as well as ^ for exponents and %%for modulus (the remainder from division). Here are some examples

> 5*3
[1] 15
> 2^10
[1] 1024
> 7%%3
[1] 1

R respects the standard order of operations such that multiplications (and divisions) are given a higher precedence than additions (and subtractions) and exponents precede both. To choose a specific order, parenthesis may be used.

> 1+2*3
[1] 7
> (1+2)*3
[1] 9
> 1+2^3
[1] 9
> (1+2)^3
[1] 27

2.0.1 Exercises: Arithmetic Operators

See Section 18.0.1 for solutions.

Calculate the following expressions:

  1. 1+2+3

  2. 11+2

  3. 21+2