Skip to main content

1  Installing R and RStudio

You need two programs, both free, installed in this order. R is the language. RStudio is the editor you will actually open: a window for writing R code, running it, and looking at the results. RStudio does nothing without R underneath it, which is why R goes first.

1.1 Installing R

Go to https://cran.r-project.org. The links for the three operating systems are at the top of the page.

  • Windows. Click “Download R for Windows”, then “base”, then the large download link at the top. Run the installer and accept every default.
  • macOS. Click “Download R for macOS”. There are two .pkg installers. Pick the one labeled for Apple silicon (arm64) if your Mac has an M-series chip, and the Intel (x86_64) one otherwise. Apple menu, then About This Mac, tells you which you have. Open the .pkg and click through.
  • Linux. Use your package manager. On Ubuntu that is sudo apt install r-base.

This book assumes R 4.1 or later. Anything you download today is far newer than that.

1.2 Installing RStudio

Go to https://posit.co/download/rstudio-desktop/. The page detects your operating system and offers one download button for RStudio Desktop. Install it like any other program. It finds your R installation by itself.

1.3 The four panes

Open RStudio. The window is divided into panes, each with tabs along its top.

  • Console, on the left. This is R itself. You type a line at the > prompt, press Enter, and R answers.
  • Source, top left, above the Console. This is the text editor for your files. It only appears once a file is open, so on first launch the Console fills the whole left side.
  • Environment, top right. A list of every object you have created in this session, with its value. It is empty now.
  • Files, Plots, Packages, Help, bottom right. A file browser, the place figures appear, the list of installed packages, and the documentation viewer.

1.4 A first command

Click in the Console, type 2 + 2, and press Enter.

2 + 2
#> [1] 4

In this book, code sits in a shaded box and R’s reply is shown below it after #>. Your Console shows the reply without the #>.

The answer is 4. The [1] in front of it is a counter: it says that this line of output begins with the first element of the result. It earns its place in Chapter 3, where results have hundreds of elements.

1.5 Scripts

The Console forgets. Close RStudio and whatever you typed is gone. Work you want to keep goes in a script, a plain text file of R commands.

From the menu bar choose File, then New File, then R Script. An empty tab called “Untitled1” opens in the Source pane. Type these lines into it.

# Period of a 1 m pendulum, in seconds
2 * pi * sqrt(1 / 9.81)
#> [1] 2.006067

Put the cursor on the second line and press Ctrl+Enter (Cmd+Enter on a Mac). RStudio sends that line to the Console and runs it. Select several lines first and the same keys run all of them. A 1 m pendulum takes about 2.006 s per full swing. pi is built in and sqrt() takes a square root. Chapter 2 covers both.

The first line is a comment. R ignores everything from a # to the end of the line, so comments are notes to the reader, who is usually you in three weeks.

Save with Ctrl+S (Cmd+S) and give the file a name ending in .R, such as pendulum.R. The script is the record of what you did. The Console is for trying things out.

1.6 Projects

A script needs to know where its data files are. RStudio’s answer is the project: one folder for one course or one lab, holding the scripts, the data, and the figures together.

Choose File, then New Project. In the dialog pick New Directory, then New Project. Type a directory name such as physics-lab, choose where it should live, and click Create Project. RStudio restarts inside the new folder. It contains a file ending in .Rproj. Double-click that file in future to reopen the project.

R now looks for files starting from the project folder. A path like "data/pendulum.csv" means “the file pendulum.csv in the data folder of this project”, and it keeps meaning that on a lab partner’s computer. You never have to type C:/Users/....

The book uses two small data sets. Run these lines in the Console once to create a data folder in your project and download both files into it.

dir.create("data")
download.file("https://rforphysics.daverosenman.com/data/pendulum.csv",
              "data/pendulum.csv")
download.file("https://rforphysics.daverosenman.com/data/cooling.csv",
              "data/cooling.csv")

Click the data folder in the Files tab to confirm they arrived. They are used from Chapter 5 onward.

1.7 Packages

Most of what this book uses after Chapter 5 comes from packages, add-ons that anyone can write and publish. Installing one downloads it to your computer. You do this once.

install.packages(c("tidyverse", "broom", "orbitr"))

This takes a few minutes and prints a great deal of text. The tidyverse is a collection of packages for data and plotting, broom tidies up the results of fits, and orbitr simulates gravitational systems.

NoteWindows and Rtools

On Windows, R may print a warning that Rtools is required. It is not required for these packages. Rtools is for building packages from source code, and these arrive already built. Ignore the message.

An installed package is not yet available. You load it with library() at the start of every session, which in practice means at the top of every script.

library(tidyverse)

Note the difference: quotes in install.packages(), none in library().

1.8 Getting help

Type a question mark followed by a function’s name.

?sqrt

The Help tab opens the documentation for sqrt(). Every help page has the same layout: a description, the arguments, and runnable examples at the bottom, which are often the fastest way in.

1.9 Reading error messages

You will see error messages daily, and so does everyone else who uses R. An error stops the command that caused it and breaks nothing else. Read the message, fix the line, run it again. Three errors account for most of a beginner’s first week.

squareroot(16)
#> Error in `squareroot()`:
#> ! could not find function "squareroot"

R knows no function by that name. Either it is misspelled, as here, or it lives in a package you have not loaded with library().

length_m
#> Error:
#> ! object 'length_m' not found

R knows no object by that name. You have not created it yet, or you created it with a different spelling. R is case-sensitive, so Length_m and length_m are different names.

The third is a typing error.

2 * pi sqrt(1 / 9.81)
#> Error in parse(text = input): <text>:1:8: unexpected symbol
#> 1: 2 * pi sqrt
#>            ^

“Unexpected symbol” means R met something that cannot come next. The message quotes the line up to the point where R gave up, so the mistake is at or just before the end of the quoted text. Here a * is missing between pi and sqrt. Missing commas and unclosed brackets produce relatives of this message.

TipThe + prompt

If the Console shows + instead of >, R thinks your command is unfinished, usually because of an unclosed bracket or quote. Press Esc to cancel and start the line again.

The setup is finished. Chapter 2 starts using R for what it does best on day one: arithmetic with physical quantities.