2  R syntax

All analyses within R are carried out using syntax, the R programming language. It is important to note that R is case-sensitive so always ensure that you use the correct combination of upper and lower case letters when running functions or calling objects.

Any text written in the R console or script file can be treated the same as text from other documents or programmes: text can be highlighted, copied and pasted to make coding more efficient.

When creating script files, it is important to ensure they are clear and easy to read. Comments can be added to script files using the # symbol. R will ignore any text following the # on the same line.

Style tip

Combining # and - creates sections within a script file, making them easier to navigate and organise.

For example:

# Load data ----------

# Tidy data ----------
Helpful hint

To comment out chunks of code, highlight the rows and use the keyboard shortcut ctrl + shift + c on Windows, and Command + shift + c on Mac

The choice of brackets in R coding is particularly important as they all have different functions:

All standard notation for mathematical calculations (+, -, *, /, ^, etc.) are compatible with R. At its simplest level, R is just a very powerful calculator!

Style tip

Although R will work whether a space is added before/after a mathematical operator, the style guide recommends to add spaces surrounding most mathematical operations (+, -, *, /), but not around ^.

For example:

# Stylish code
1959 - 683
(351 + 457)^2 - (213 + 169)^2

# Un-stylish code
1959-683
(351+457)^2 - (213 + 169) ^ 2

2.1 Exercise 2

  1. Add your name and the date to the top of your script file (hint: comment this out so R does not try to run it)
  2. Use R to answer to following sums:
  1. \(64^2\)
  2. \(3432 \div 8\)
  3. \(96 \times 72\)

For each part of question 2, copy the result from the console and paste them onto the same line of the script file as the code. Do this in a way that ensures there are no error messages if you were to run the entire script file.