Lesson 2 of 17 · Week 01 · Tue Sep 29
R Basics
Questions
- How do I find my way around Positron?
- How do I compute, compare and store values in R?
- How do I manage objects and packages in a session?
Objectives
- Name the main areas of the Positron window and what each is for.
- Use R for arithmetic and mathematical functions, and compare values (including decimals) correctly.
- Assign values to valid, readable names and predict what a sequence of assignments produces.
- List and remove objects; install and load packages.
How to work through this lesson
This is a self-guided lesson for Tuesday morning. Work through it in order:
- Open your course folder in Positron (see Lesson 1) and create
scripts/week01-basics.R. - 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.
- Do the five exercises at the bottom of this page. They check your answer automatically.
- Download your proof-of-completion PDF at the end of the page.
- 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:
- Editor (centre): where your script files open, one tab per file. This is where you write code you want to keep.
- Console (panel below the editor): where R actually runs. Its tabs also include a Terminal for command-line work.
- Explorer (left, the top icon in the thin Activity Bar): the files and folders of the folder you opened. The other Activity Bar icons open search, source control (Git) and extensions.
- Session and Plots (right-hand side bar): Variables lists every object in your R session with its type and a preview, and the Plots pane shows figures. Help pages open on the right as well.
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:
install.packages("dplyr"): downloads and installs a package. Do this once, in the console. Note the quotes. To install several in one go:install.packages(c("dplyr", "tidyr")).library(dplyr): loads an installed package so you can use its functions. Put this at the top of every script that needs it.
Other helpers: installed.packages(), update.packages(), remove.packages("name").
For the afternoon
Bring these three things to the discussion & peer-review session:
- Your proof-of-completion PDF for this lesson.
- Your
scripts/week01-basics.R, which should run from top to bottom without errors. - 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:
- Does it run top to bottom, in a fresh R session, without errors? If not, where does it stop?
- Could you tell what each object holds just from its name?
- Find one comment that explains why, not just what. If there isn't one, suggest one.
- What's one thing they did that you'll borrow?
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 usedClick 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.
Exercise 2 — Track the values
0 / 10 attempts usedClick 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.
Exercise 3 — Compare with care
0 / 10 attempts usedTwo 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 isTRUEif box A weighs more than box B (convert units first!), andsame_total:TRUEif0.7 + 0.1equals0.8, computed in a way that gives the mathematically correct answer.
Exercise 4 — Tidy the environment
0 / 10 attempts usedSeveral 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.
Exercise 5 — Install and load (practice mode)
0 / 10 attempts usedIn 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:
- install both
readrandjanitorwith a single call toinstall.packages(), and then - load
readr.
Key Points
- Write code in a script in the editor and send it to the console with Ctrl/Cmd+Enter.
- Use
<-to assign; the right-hand side is computed first, with the current values. - Compare decimals with
isTRUE(all.equal(x, y)), not==. ls()lists objects andrm()removes them.- Install a package once with
install.packages("name"); load it withlibrary(name).
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.