Setting Up R & R Studio
Installing, Launching, and Organising R and RStudio: Panes, Working Directories, Projects, and Packages
Two programs, two jobs
R is the statistical programming language together with the engine that executes it. It is downloaded from CRAN, the Comprehensive R Archive Network, and once installed it can be used entirely on its own from a plain terminal.
RStudio is an integrated development environment: a separate program, written by a different organisation, that provides an editor, a file browser, plot and help panes, and project management, and that sends your code to an R installation already present on the machine.
The practical consequences of that division follow immediately. RStudio can be installed without an earlier R installation, but R must be available before RStudio can execute R code.
Installing R first is the recommended sequence for a ready-to-use setup. Upgrading RStudio never changes which version of R you are running, and upgrading R never changes your editor.
If a colleague reports a different numerical result, check both the R version, visible at the top of the console at startup or from R.version.string, and the versions of relevant packages.
The RStudio version, reported separately by rstudioapi::versionInfo()$version, identifies the interface and does not replace those checks.
The four panes and what each is for
A default RStudio window is divided into four regions, and knowing which one you are typing into prevents most beginner confusion.
- Console. Code typed here executes immediately and is not saved into any file you can re-run; the History pane does keep the text of what you submitted, but a scrollback of past commands is not an analysis you can execute from the top. It is the right place for one-off checks: inspecting an object, reading a help page, testing whether a package loads.
- Source editor. This is where .R script files are written and saved. A script is the durable, re-runnable record of an analysis. Code is usually sent from here to the console line by line, but the file is what survives.
- Environment and History. The Environment pane lists the objects currently in memory; History lists commands previously submitted. The Environment pane showing an object is not evidence that any saved file creates it.
- Files, Plots, Packages, and Help. A file browser rooted at the working directory, the plot device, a list of installed packages with checkboxes that load them, and rendered help pages.
The single most useful habit at this stage is to put every line that matters into a script, and to reserve the console for throwaway commands.
The test to apply is: if I quit R, restart with an empty environment, and run my script top to bottom, does everything I need get rebuilt?
If the answer depends on something typed into the console three hours ago, the analysis is not reproducible even for you.
The working directory
Every R session has a working directory: the folder R treats as "here" when a file path does not begin at the root of the filesystem. getwd() reports it and setwd() changes it.
Paths come in two kinds. An absolute path starts from the filesystem root and names a location exactly, such as /Users/sam/Documents/stats/scores.csv.
A relative path is interpreted from the working directory, such as data/scores.csv. Relative paths are strongly preferred in shared work, because an absolute path encodes one particular computer, one particular user account, and one particular operating system.
A script beginning with a hard-coded setwd() call is the classic cause of a project that runs for its author and fails on the first line for everyone else.
Two portability details are worth knowing early. Windows displays paths with backslashes, but in R a single backslash begins an escape sequence, so a Windows path must either double each separator or simply use forward slashes, which R accepts on every platform.
And file.path("data", "scores.csv") builds a path with the correct separator automatically.
Projects: the better answer to the working-directory problem
An RStudio Project is a folder containing a small .Rproj file. Opening the project starts a fresh R session whose working directory is automatically set to that folder.
Nothing needs to be hard-coded, and every collaborator gets the project folder as the working directory without editing paths.
For a self-contained project whose scripts refer to files kept inside its folder, moving or renaming the whole folder keeps those project-relative paths working. References outside the project, such as ../shared/scores.csv, can break after a move.
The recommended structure is to keep the .Rproj file at the top of the folder, put raw data in a data/ subfolder, put scripts in an R/ or scripts/ subfolder, and refer to files by relative paths from the project root.
The rule of thumb is: if your script contains setwd(), you probably want a project instead.
Packages: installing into a library, loading every session
R ships with a set of base packages, and thousands more are distributed through CRAN. Two distinct operations are involved, and confusing them accounts for a large share of early error messages.
- install.packages("dplyr") downloads the package and writes it into your library, a folder on disk. Packages are installed into a library as needed and persist across sessions, so the step is not repeated every time you work. R may search shared system libraries as well as user and project-specific libraries; the paths can differ across users, R versions, and projects. Inspect .libPaths() for the libraries searched by the current session. A package is installed again when it is updated or reinstalled. The package name must be quoted.
- library(dplyr) attaches an already-installed package to the current session's search path so its functions can be called by name. This is done every session, and conventionally at the top of the script. Quotes are optional here.
Read the two failure messages carefully, because they point to different problems. Error in library(dplyr) : there is no package called 'dplyr' means the package is not available in the current R process's active library paths, the directories .libPaths() reports.
Usually it has simply not been installed into any of them; if you know a copy exists elsewhere on the machine, under another user account or another R version's library, check .libPaths() and whether the session is using the library you intended.
Error: could not find function "mutate" when the package is installed is a common sign that it has not been attached in this session, but it is not conclusive: an unavailable function can also result from a misspelling or from a package version that does not provide that function.
Run library(dplyr) and retry; if attachment does not resolve the error, use packageVersion("dplyr") and the package documentation to verify the spelling and whether that version provides the function. Choose the function you test with some care.
A few dplyr names, filter and lag among them, also belong to packages R attaches by default, so filter(scores, mark > 70) without library(dplyr) reports no missing function at all: the call reaches stats::filter, a time-series smoothing function, which does no lookup inside the data frame and simply evaluates mark > 70 in the calling environment.
What happens depends on the inputs: stats::filter may report object 'mark' not found if that name is unavailable in the calling environment, fail to coerce scores to a time series, or return a time-series result if mark exists and the inputs are suitable.
None of these outcomes is dplyr row filtering. The error is not could not find function, because the name filter was found.
That is why library(dplyr) prints a note about objects masked from stats. In a fresh R session with only the default packages attached, mutate and arrange are generally unavailable; finding them after library(dplyr) can be a useful quick check in that limited setting.
Their unqualified availability does not prove that dplyr is attached or that a call will use dplyr: other packages, including plyr, and user code can provide the same names.
Use search() to check whether package:dplyr is attached, and call dplyr::mutate when the function source matters.
A related point: install.packages() belongs in the console, not in a shared script, because re-downloading a package on every run is slow and changes the collaborator's machine without asking.
Starting clean
By default R can offer to save your workspace, all the objects in memory, into a hidden .RData file on exit and silently reload it next time.
This feels convenient and is a trap: objects reappear with no visible code that creates them, so a script that has quietly stopped working keeps appearing to work.
In RStudio's global options, set "Save workspace to .RData on exit" to Never and clear "Restore .RData into workspace at startup".
Then restart the session often, and let the script rebuild everything from the beginning. Getting this habit right at setup time is what makes every later stage of an analysis trustworthy.
Last week a student successfully ran install.packages("ggplot2"). Today they open a fresh RStudio session, run ggplot(data = scores, aes(x = hours, y = mark)), and see Error in ggplot(...) : could not find function "ggplot". What is the correct explanation and fix?
Mark Yourself Question
- Grab a piece of paper and try this problem yourself.
- When you're done, check the "I have answered this question" box below.
- View the solution and report whether you got it right or wrong.
A student's script contains the line scores <- read.csv("data/scores.csv") and returns:
Error in file(file, "rt") : cannot open the connection In addition: Warning message: cannot open file 'data/scores.csv': No such file or directory
The file definitely exists on the laptop, inside a folder named data that sits next to the script. Explain what has gone wrong, give the commands that confirm the diagnosis, and give both an immediate fix and a durable fix.