This lesson is in the early stages of development (Alpha version)

Calculating in RStudio

Overview

Teaching: 5 min
Exercises: 5 min
Questions
  • How do we process mathematical operations in RStudio?

Objectives
  • Become familiar with mathematical operators and in-built functions in RStudio.

  • Become confident using the console to run mathematical operations.

  • Understand the order of operations.

Dipping our toes

We have covered some relatively dry theory so let’s take some small steps and start interacting with R. From the console we can start exploring calculation. Write in the following commands:

10 - 5 #(subtraction) 
5
10 + 5 #(addition) 
15
10 * 5 #(multiplication) 
50
10 / 5 #(division) 
2
5 ^ 2 #(exponentiation) 
25
10 %% 3 #(modulus)  
1

Order of operations

Question: Before you enter the next calculation, take a second and consider what answer would you be expecting?

6 + 9 / 3 
9

If the answer was not what you were expecting you will need to become clear on order of operations in R.

Remember PE(DM)(AS)

* Operators with same precedent are calculated left to right.

This tells you what order mathematical operations will be performed and ensures consistency during evaluation.

To make this concept clearer, try:

(6 + 9) / 3 
5

Using brackets we have manipulated the order of operations to perform the addition before the division. Be conscious of how you structure your mathematical operations to ensure the desired results but also readability of your code.

Mathematical Functions

Base R provides you with a range of built in mathematical functions. If you need a fairly common operation there is a good chance it already exists. Let’s look at a few examples, try:

sqrt(9) 
3
abs(-5) 
5
round(3.4) 
3

There are a whole range of built-in functions that are available. You can check the help reference or perform a google search to find a definitive list.

Key Points

  • PEDMAS

  • Use in-built functions, you don’t need to reinvent the wheel.