Chapter 4 General Coding

4.1 Objects

Objects are any ‘thing’ that you create in R. They’re shown in your Environment.

There are a huge number of objects in R. The following illstrates a numer of the core object types:

Tip:

When naming objects it is useful to do the following:

  1. Make the names meaningful but short e.g. we could call School Workforce Census Table swfc.

  2. Stick to one convention. The standard for R is snake_case. See here for further details on R Style Guide.


To run that code you will first need to create a new script File > New File > R Script.

You can then run line by line by having your cursor on that line or highlight chunks and then doing one of the following:

  • Press CTRL + ENTER
  • Click ‘Run’ in the top right hand corner of the script window

Tip:

  • Double click highlights term
  • Triple click highlights line
  • Quadruple click highlights entire script


The <- sign is called a get sign. It ‘gets’ the output from the right hand side and attributes it to the object name.

Tip: ALT + - is a shortcut to inputting the get sign.


Activity A3.3: What does typeof(OBJECT NAME) do?


Activity A3.4: Now save your work in the R folder!


Writing the following code will remove a specified object:

Writing the following code will remove all objects:

Activity A3.5: Arguments are the bits of code inside brackets, and if there are multiple arguments they’re separated by commas.

Explain the what the argument inside the second rm in the code above does.


4.2 Comments

Activity A3.6: Type 1+1 and run it, what comes up in the console? Put a # in front of 1+1, what comes up in the console?

Comments are really important for annotating code, so that you and others know exactly what the code does and why.

Here we add a description of what setwd() does:

Tip:

  • CTRL + SHIFT + C comments multiple lines at once
  • CTRL + SHIFT + R creates a section, which you can jump between using the dropdown list in the bottom left corner of the script window