Lesson 2 of 17 · Week 01 · Tue Sep 29

R Basics

Questions

Objectives

How to work through this lesson

This is a self-guided lesson for Tuesday morning. Work through it in order:

  1. Open your course folder in Positron (see Lesson 1) and create scripts/week01-basics.R.
  2. Read each section below. Type every example into your script (don't copy-paste) and run it with Ctrl/Cmd+Enter. Before running a line, predict what it will print.
  3. Do the five exercises at the bottom of this page. They check your answer automatically.
  4. Download your proof-of-completion PDF at the end of the page.
  5. Prepare the three things listed under For the afternoon.

Adapted from Software Carpentry's “Introduction to R and RStudio” episode (CC BY 4.0, The Carpentries). Text, examples and exercises have been rewritten for this course.

Finding your way around Positron

Positron's window is made of a few areas that you can resize, hide or move. By default:

If a pane is missing, use the View menu, or Ctrl/Cmd+Shift+P and type its name.

In the exercises on this site, the code box and its output stand in for the editor and console: the code runs in a real R session inside your browser.

R as a calculator

7 + 3 * 2       # multiplication before addition: 13
(7 + 3) * 2     # parentheses first: 20
2 ^ 10          # exponent: 1024
17 %/% 5        # integer division: 3
17 %% 5         # remainder: 2
6.02e23         # scientific notation for 6.02 x 10^23

If a line ends before R thinks the expression is finished (say, 7 +), the console shows a + prompt and waits for the rest. Finish the line or press Esc to cancel.

R also has the usual mathematical functions. You call a function by writing its name followed by parentheses holding its arguments:

sqrt(81)        # 9
log(100)        # natural log: 4.60517
log10(100)      # base-10 log: 2
exp(1)          # e: 2.718282
abs(-4.5)       # 4.5
round(3.14159, digits = 2)

Comparing things

5 == 5          # equal to (two = signs!)
5 != 3          # not equal to
4 < 9
4 >= 9

Comparisons return TRUE or FALSE: logical values. One warning: computers store most decimals approximately, so 0.1 + 0.2 == 0.3 is FALSE. To compare decimal numbers, use all.equal(), which allows a tiny tolerance, wrapped in isTRUE() so you always get a single TRUE/FALSE:

0.1 + 0.2 == 0.3                    # FALSE
isTRUE(all.equal(0.1 + 0.2, 0.3))   # TRUE

Variables and assignment

Store a value under a name with the assignment arrow <- (in Positron, Alt+- types it for you):

rain_mm <- 12.5
rain_in <- rain_mm / 25.4
rain_in
rain_mm <- rain_mm + 3     # overwrite with a new value

Assignment prints nothing. Type the name on its own line to see the value, and watch it appear in the Variables pane. The right-hand side is computed first, using the current values, and only then stored. That's why rain_mm <- rain_mm + 3 makes sense.

Rules for names: they may contain letters, digits, . and _; they must start with a letter or a dot (a dot can't be followed by a digit); they can't be reserved words like if or TRUE; and they are case-sensitive (Rain ≠ rain). Names starting with a dot are hidden: they work, but ls() doesn't show them. Pick one style and stick to it; this course uses lower_snake_case.

Comments start with #. Use them to explain why you did something; the code already says what.

A first look at vectors

1:6             # the integers 1 to 6
2 ^ (1:6)       # 2, 4, 8, 16, 32, 64
temps <- c(18.5, 21.0, 19.2)
temps * 9 / 5 + 32

Most R operations work on a whole vector at once. We'll come back to this many times.

Managing your environment

ls() lists the objects you've created. rm() deletes objects: rm(rain_in), or several at once with rm(rain_in, temps). Notice the empty parentheses in ls(): they tell R to call the function. Typing ls without them prints the function's own code.

When you pass an argument by name, use =, not <-: round(3.14159, digits = 2). Inside a function call, <- would create a variable instead of setting the argument.

Errors vs. warnings: an error stops R (nothing was computed). A warning means R did something but suspects it isn't what you wanted. Read both: the message usually points at the problem.

Packages

Base R is extended by thousands of packages. The two functions to know:

Other helpers: installed.packages(), update.packages(), remove.packages("name").

For the afternoon

Bring these three things to the discussion & peer-review session:

  1. Your proof-of-completion PDF for this lesson.
  2. Your scripts/week01-basics.R, which should run from top to bottom without errors.
  3. One surprise: an output or error you didn't predict, plus a sentence on what you now think is going on.

Peer review. Swap scripts with a partner and answer these, in writing, about their script:

Exercises

Each exercise gives you up to 10 checked attempts. Use Run as many times as you like to experiment first, then click Check answer when you're ready. Your exercises use numbers/subsets unique to you, so answers won't match a classmate's exactly.

Exercise 1 — Valid names

0 / 10 attempts used

Click Run to print eight candidate object names (they differ for every student). Store the ones that R accepts as object names (hidden ones included) in a character vector called valid.

Work it out from the rules above first. Then test yourself: try assigning a value to a name, e.g. site-id <- 1, and see what R says.

Pasting isn't accepted here — please type your answer so it reflects your own work.

      

Exercise 2 — Track the values

0 / 10 attempts used

Click Run to print a short program (the numbers are different for every student). Without running it, work out on paper the value of each variable after the last line. Then store your answers in a_final and b_final. Only after that, type the program in to check yourself.

Pasting isn't accepted here — please type your answer so it reflects your own work.

      

Exercise 3 — Compare with care

0 / 10 attempts used

Two objects are defined for you (click Run to see them): box_a holds a weight in kg and box_b a weight in grams. Create:

  • a_heavier: a comparison that is TRUE if box A weighs more than box B (convert units first!), and
  • same_total: TRUE if 0.7 + 0.1 equals 0.8, computed in a way that gives the mathematically correct answer.
Pasting isn't accepted here — please type your answer so it reflects your own work.

      

Exercise 4 — Tidy the environment

0 / 10 attempts used

Several objects were created for you. Run ls() to see them. Delete rain and days with one call to rm(), but keep everything else. Finish with ls() to confirm.

Pasting isn't accepted here — please type your answer so it reflects your own work.

      

Exercise 5 — Install and load (practice mode)

0 / 10 attempts used

In this box, install.packages() and library() are in practice mode: they only report what they would do, so nothing is really installed. Write the code you would run to:

  1. install both readr and janitor with a single call to install.packages(), and then
  2. load readr.
Pasting isn't accepted here — please type your answer so it reflects your own work.

      

Key Points

Proof of completion

Once you've attempted every exercise above, download a PDF summary of your work on this lesson — your name, the exercises you passed, attempt counts, timing, and your final code for each.