2  Basic R Syntax and Operations

NoteSession Overview

Estimated time: ~45 minutes

By the end of this session you’ll be able to:

  • Perform arithmetic calculations in R and predict the order in which operations are evaluated.
  • Create variables (objects) using the assignment operator <- and reuse them in later calculations.
  • Apply R’s variable naming rules, including why R is case-sensitive.
  • Create simple vectors with c() and identify R’s three basic data types: numeric, character, and logical.

Before you start: Overview of R and RStudio – make sure R and RStudio are installed and you know how to find the Console pane.

Self-paced tip: Work directly in the RStudio Console for this session. Type each example yourself rather than copy-pasting – it’s the fastest way to build muscle memory for R syntax.

2.1 Arithmetic / Mathematical Operations

Arithmetic operations are fundamental in R, as in many programming languages. They allow us to perform basic mathematical calculations. In this section, we will explore the primary arithmetic operators available in R.

Note

Please note that there is no need to save any part of this course or create a new file at this moment. We will initially work in the console, and later, we will proceed to create a new R R Script / R Markdown file, where we will write and save our code.

2.1.1 Operators

Here are the basic arithmetic operators in R:

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)
  • Exponentiation (^)

2.2 Using basic operators in R

Let’s examine these operators and observe how they function. We will use the console to execute the code. The console is the panel at the bottom left of your RStudio window. You can type code directly into the console and press enter to execute it. The console is a great place to experiment with code, but it is not a good place to save your code. We will learn how to save our code in a later section.

2.2.1 Addition

You can type or copy this code chunk and paste it in your console and hit enter

# Addition
3 + 4  # Output: 7
[1] 7

Hooray! You’ve just taken your first step into the world of coding with R. When you input “3 + 4”, R calculates that the sum is 7. You might have noticed the [1] preceding your output in the console; don’t worry, this simply indicates that 7 is the first (and only) element in the output. The index, [1], is particularly helpful when you’re dealing with lengthy outputs, as it marks the position of the first element in each line, making it easier to track elements.

Tip

Index with continuous numbers

Below exercise demonstrate indexing when you are working with large outputs.

Copy paste the code chunk in the console

# In this code we are telling R to store numbers from 1 to 100 in a an object called "numbers" 
numbers <- 1:100

# and then print the stored object (numbers in this case)
print(numbers)
  [1]   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18
 [19]  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36
 [37]  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54
 [55]  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72
 [73]  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90
 [91]  91  92  93  94  95  96  97  98  99 100

In this example, the sequence is straightforward because it consists of ordered numbers from 1 to 100, making it clear that the number at positions 1, 19, 37, 55, 73 and 91. However, the alignment of numbers and their respective positions may vary for each individual, depending on the size of the console pane in use.

Index with random numbers

Below exercise demonstrate indexing in R when the numbers are random.

# We are telling R to store numbers 1 to 35 randomly in a an object called random_numbers 
random_numbers <- rnorm(1:35)

# and then print the stored object (random_numbers in this case)
print(random_numbers)
 [1] -0.34785839  0.55732878 -0.58957045  0.39121640 -1.07102712  0.56319058
 [7]  0.32168602 -1.95637103 -0.47447911 -0.19298509 -0.05816089  2.00096263
[13]  0.16503103 -1.68838672  0.99412020  0.52289328  0.23277550  1.05794863
[19]  0.10472192 -0.18158364 -0.99711134 -1.53067762  1.73886287 -0.75947775
[25]  2.00300553 -0.58265296  0.37795381 -1.55326419  1.18613825  1.25609078
[31] -1.36234647  2.29947067 -0.28710116 -0.22803866 -0.33692955

In this R output, the numbers in square brackets, represent the index position of the first number on each line. However, the alignment of numbers and their respective positions may vary for each individual, depending on the size of the console pane in use and every time you run this code.

These index positions help you to quickly locate and reference specific elements in the output, particularly when dealing with large datasets.

2.2.2 Subtraction

Please type, the following arithmetic operations into the console, then press enter to execute the code and observe the results. Focus to type is to develop muscles memory.

# Subtraction
10 - 6  # Output: 4
[1] 4

2.2.3 Multiplication

# Multiplication
5 * 3  # Output: 15
[1] 15

2.2.4 Division

# Division
8 / 2  # Output: 4
[1] 4

2.2.5 Exponentiation

# Exponentiation
2^3  # Output: 8
[1] 8

2.2.6 Order of Operations in R

In R, like in most programming languages, when a line of code contains multiple operations, it’s crucial to understand how these operations are prioritized and executed. This prioritization is governed by the “Order of Operations.” This concept, sometimes known as operator precedence, dictates the rules R follows to evaluate expressions.

The order of operations in R is as follows:

  1. Parentheses (): Operations inside parentheses are performed first. This allows you to override the default order of operations. For example, in 2 * (3 + 4), the addition inside the parentheses is performed before the multiplication.

  2. Exponents ^: Next, R performs exponentiation. For instance, in 3 ^ 2 * 4, the exponentiation 3 ^ 2 is evaluated before the multiplication.

  3. Divide / and Multiply *: These operations are on the same level of precedence and are performed from left to right. For example, in the expression 10 / 2 * 3, R first divides 10 by 2, and then multiplies the result by 3.

  4. Add + and Subtract -: These also share the same level of precedence and are executed from left to right. In 5 + 3 - 2, R first adds 5 and 3, then subtracts 2 from their sum.

Remember, R follows these rules strictly. However, you can always use parentheses to structure your expressions in a way that reflects the intended calculations. Understanding and utilizing the order of operations is essential for writing accurate and efficient R code.

TipActivity

Activity basic operators and order of operations in R

Type each of the following expressions into the console and press enter to execute:

  • 8 + 2 * 5
  • (8 + 2) * 5
  • 20 / 4 - 3
  • 20 / (4 - 3)
  • 3 ^ 2 + 4
  • 3 ^ (2 + 4)

Note down the output for each expression. Think about why each expression gives the result it does based on the order of operations.

Do your numbers match with these?

  • 8 + 2 * 5 = 18 (Multiplication before addition)
  • (8 + 2) * 5 = 50 (Parentheses first, then multiplication)
  • 20 / 4 - 3 = 2 (Division before subtraction)
  • 20 / (4 - 3) = 20 (Parentheses first, then division)
  • 3 ^ 2 + 4 = 13 (Exponentiation before addition)
  • 3 ^ (2 + 4) = 729 (Parentheses first, then exponentiation)

Understanding the order of operations is essential for accurate computations in R

2.3 Objects, Variables and Vectors

In R, think of an “object” as a box where you can store all kinds of things. This box could contain a single item, like a marble, or many items, like a bunch of marbles lined up in a row. In R, everything is stored in these kinds of boxes, and each one is called an ‘object.’

Now, imagine that inside one of these boxes, you have a tray of eggs. This tray is a bit like a “vector” in R. It holds items (the eggs) that are all the same kind, neatly in a row. If you replace eggs with numbers, that’s what a numeric vector is – a line-up of numbers.

And when you talk about a “variable,” it’s like having a name tag on your box. It’s the name you give to your box so you can find it easily among other boxes. For instance, if you put a name tag that says ‘x’ on a box with the number 10 inside, ‘x’ is your way of saying, “This is where I keep my number 10.”

Let’s simplify that:

  • Object: A box for keeping any item or set of items in R.
  • Vector: A tray inside the box that holds items of the same type in a neat line.
  • Variable: The name tag on the box, telling you what’s inside without having to open it.

2.3.1 Vectors in R

Vectors are one of the most fundamental data types in R. They are collections of elements that are all of the same type. You can create a vector using the c() function, which stands for ‘combine’:

# Creating a numeric vector
numbers <- c(1, 2, 3, 4, 5)

# Creating a character vector
words <- c("apple", "banana", "cherry")

2.3.2 Manipulating Vectors

Once you have a vector, you can perform operations on all its elements at once:

# Adding 2 to each element
numbers + 2  # Output: 3, 4, 5, 6, 7
[1] 3 4 5 6 7
# Concatenating strings
paste(words, "fruit")  
[1] "apple fruit"  "banana fruit" "cherry fruit"

2.3.3 Variables in R

In R, to assign a value to a variable, we use the assignment operator <-.

The <- assignment operator is one of the most utilized operator in R. In RStudio, the keyboard shortcut for the assignment operator <- is Alt + - (Alt and hyphen) on Windows and Linux. On a Mac, you can use Option + - (Option and hyphen) to type the assignment operator <-. So, you would hold down the Alt or Option key and press the hyphen key at the same time.

my_number <- 10  # 'my_number' is now 10
my_text <- "Hello, world!"  # 'my_text' is now "Hello, world!"

In these examples:

  • my_number and my_text: are the names of the variables.

  • 10 and “Hello, world!”: are the values we’re storing in the variables.

  • <-: is the assignment operator that stores/assigns the values into the variables.

2.3.4 Using Variables

Once a value is stored in a variable, you can use the variable name to access the value:

my_number + 5  # Output: 15
[1] 15

You can also change the value stored in a variable by assigning a new value to it (older value will be overwritten and will not be available anymore):

my_number <- 20  # 'my_number' is now 20
TipTry it yourself

Create a variable called my_age and set it to your age. Then, on a new line, use it in a calculation, e.g. my_age * 2. Finally, reassign my_age to a different number and run the calculation again – notice how the result updates.

2.3.5 Variable Naming Rules

When naming your variables, keep in mind the following rules:

  • Variable names should start with a letter.
  • They can contain letters, numbers, underscores (_), and periods (.).
  • They cannot contain spaces or other special characters.
valid_name <- 10  # This is a valid variable name
also_valid123 <- 20  # This is also valid

This line will cause an error because of the space in the variable name Type the code in console without # and see the error message

# not valid <- 30
WarningCommon Mistakes
  • Spaces in names. not valid <- 30 fails because R reads not, valid, and <- 30 as separate pieces. Use not_valid instead.
  • R is case-sensitive. my_number and My_Number are two completely different objects. If R says object not found, check that you’ve typed the name with exactly the same capitalisation as when you created it.
  • <- vs = vs ==. Use <- to assign a value to a variable (e.g. x <- 5). A single = can also assign at the top level, but <- is the convention used throughout this course. A double == is different again – it compares two values (you’ll meet this in Data Frames and Lists).

2.4 Basic Data Types

Understanding data types is crucial as they form the foundation upon which we build our data analysis. In R, the main data types you will encounter are numeric, character, and logical.

2.4.1 Numeric Data Type

Numeric data types include both integers and floating-point numbers. Here’s how you can work with numeric data in R:

  • Numeric Examples
num1 <- 5        # integer
num2 <- 5.5      # floating-point number

2.4.2 Character Data Type

Character data type is used to store text. Here’s how you can work with character data in R:

  • Character Examples
char1 <- "Hello"       # a word
char2 <- "Hello, world!"  # a sentence

2.4.3 Logical Data Type

Logical data type represents TRUE or FALSE values, which are often the result of comparisons. Here’s how you can work with logical data in R:

  • Logical Examples
log1 <- TRUE            # TRUE value
log2 <- (5 > 3)         # TRUE, because 5 is greater than 3

2.5 Summary & Self-Check

Key takeaways:

  • R follows the standard order of operations: parentheses first, then exponents, then multiplication/division (left to right), then addition/subtraction (left to right).
  • An object is a box for storing values; a variable is the name tag on that box; a vector (created with c()) is a row of values of the same type stored in one object.
  • The assignment operator <- (shortcut: Alt + - on Windows/Linux, Option + - on Mac) stores a value in a variable. Reassigning a variable overwrites its old value.
  • Variable names start with a letter, can contain letters, numbers, _ and ., cannot contain spaces, and are case-sensitive.
  • R’s three basic data types are numeric (numbers), character (text, in quotes), and logical (TRUE/FALSE).

Check your understanding:

What is the result of 2 + 3 * 4?

Which of these is the conventional assignment operator used throughout this course?

True or false: in R, my_var and My_Var refer to the same object.

What’s next: Continue to R Markdown Basics to start saving your code in a workbook instead of just the console.