participants <- 100
mean_age <- 21.4
condition_labels <- c("control", "treatment")3 Scripts, RData, projects, environments, and R Markdown
3.1 Why this chapter exists
When you start using R, you will encounter several different “things” that all live on your computer and that all seem related to R: scripts, RData files, R projects, the environment, R Markdown files. New users frequently confuse these. The confusion is not unfounded; the names are similar, the file extensions are similar, and the documentation often assumes you already know which is which.
This chapter introduces each of them and clarifies what they are for. By the end, you should be able to answer the question “what kind of file should I create to do this?” for each of the situations you will encounter.
A useful preliminary distinction: some of these things are files saved on your computer, while one of them (the environment) is a state held in memory while R is running. We will start with the in-memory thing because it underpins everything else.
3.2 The environment: what R is holding right now
When you run R (typically through RStudio), R holds in memory a list of all the objects you have created during the current session. This list is called the environment, or sometimes the workspace.
For example, suppose you open RStudio, type the following in the Console, and press Enter after each line:
You have now created three objects: participants, mean_age, and condition_labels. They are all in the environment. The Environment panel in RStudio (upper right) will show them: their names, their types, and a short preview of their contents.
The environment is not a file. It exists only while R is running. When you close R, the environment is gone. If you reopen R later and want those objects back, you have to either re-create them by running the same code, or load them from a saved file.
This brings us to the next distinction.
3.3 The R script (.R file)
An R script is a plain-text file with the extension .R. It contains R code: the same code you would type into the Console, but saved in a file so you can re-run it later.
To create a script in RStudio: in the menu, click File > New File > R Script. A blank document opens in a new panel (typically the upper-left). You can type code there.
participants <- 100
mean_age <- 21.4
condition_labels <- c("control", "treatment")To save the script, press Ctrl+S (Cmd+S on macOS) or click the disk icon at the top of the script panel. RStudio will ask you for a filename and a location. Use a meaningful name; for example, 01_setup.R.
To run the code in a script, you have several options:
- Run one line at a time. Place the cursor on a line and press Ctrl+Enter (Cmd+Enter on macOS). RStudio sends that line to the Console for execution.
- Run a selected block. Highlight several lines and press Ctrl+Enter. RStudio sends the highlighted block.
- Run the entire script. Click “Source” at the top of the script panel, or press Ctrl+Shift+Enter (Cmd+Shift+Enter on macOS).
A script is the most important file type you will create. Most of your work in R will live in scripts. Once a script is saved, you can return to it any time, on any computer that has R, and reproduce exactly what you did.
What a script does not contain: the results of running the code. A script is a recipe, not a meal. To get the results, the recipe has to be cooked again (i.e., run again).
This portability is what makes reproducibility possible in practice. If you share the script together with the data file it was written for, anyone (a collaborator, a reviewer, your future self) can run the script on that data and obtain the same results you did. Exactly the same recipe applied to exactly the same ingredients produces exactly the same meal, every time.
3.4 The RData file (.RData or .rda)
An RData file is a saved snapshot of objects. It is a binary file (not human-readable when opened in a text editor) with the extension .RData or .rda. It allows you to save objects from your environment to disk, and to load them back later.
There are two common situations.
Saving the entire environment. If you have several objects in your environment and want to save them all at once:
save.image(file = "session_state.RData")This saves every object currently in the environment into the file session_state.RData (in the current working directory; we will revisit working directories in Chapter 4). To load it back in a future session:
load("session_state.RData")Every saved object reappears in the environment under its original name.
Saving specific objects. If you only want to save some objects, list them:
save(participants, mean_age, file = "key_values.RData")This saves only participants and mean_age.
A few comments are worth making here. First, RData files are a convenience, not a substitute for a script. The script is the authoritative record of what you did; the RData file is just a cache of intermediate results. If you ever lose the RData file, the script can recreate it. If you lose the script, the RData file is just a pile of objects with no explanation. Save scripts religiously; save RData files when it would take a long time to recreate the objects (for example, after a long simulation or a slow data import).
Second, RStudio sometimes asks, when you close the program, whether you want to “save the workspace.” This refers to saving the entire environment to a file called .RData in the current working directory, which would then load automatically the next time you open R. We recommend answering No to this prompt, every time. Letting the environment persist invisibly between sessions is a common source of bugs (you cannot tell which objects come from your script and which come from a leftover state). We will return to this in Chapter 4.
3.5 The R project (.Rproj file)
An R project is a folder on your computer that has been formally designated as a project, by placing a small file with the .Rproj extension inside it. The .Rproj file itself is short and uninteresting; what matters is the structure it imposes on your work.
The mental model is simple: you keep one folder per analysis (or per piece of work) on your computer, and everything related to that analysis lives inside it. The folder typically holds input files (datasets, questionnaires, codebooks), the scripts that operate on those inputs, and the outputs the scripts produce (cleaned datasets, figures, tables, reports). When you turn that folder into an R project, RStudio knows that this folder is the home base for the work, and behaves accordingly.
When you open an R project in RStudio (by double-clicking the .Rproj file, or by going to File > Open Project), four things happen.
- RStudio sets the working directory to the project folder. The working directory is the folder R uses as a starting point for finding and saving files. Setting it correctly removes a large class of “file not found” errors.
- RStudio loads the project’s settings (which are minimal, but include things like indentation preferences and line endings).
- RStudio remembers which scripts you had open the last time you closed the project, and re-opens them.
- RStudio starts a fresh R session specific to that project, separate from any other project you might have open in another window.
The most immediately useful of these four things is the first: the working directory. Concretely, suppose your project folder is called 2024_survey and contains a file raw_data.csv. Inside the project, you can read the file with nothing more than its filename:
data <- read.csv("raw_data.csv")R looks for raw_data.csv relative to the project folder, finds it, and loads it. Saving output works the same way: if your script writes a figure to histogram.png, the file ends up inside the project folder, alongside everything else.
Without an R project, R does not know which folder you are working from, so the same line of code will either fail or load the wrong file. To make it work, you would have to spell out the full path to the file every time, something like:
data <- read.csv("C:/Users/yourname/Documents/research/2024_survey/raw_data.csv")This is brittle (the path differs between machines, between users, between operating systems) and tedious (every script and every collaborator has to update those paths to match their own setup). With an R project, the short filename raw_data.csv works on any machine that has the project folder.
A second consequence of the project structure is that projects are isolated from one another. You might have one project folder for 2024_survey and another for pilot_study. When you open one, R starts a fresh session, sees only the files in that project’s folder, and does not carry anything over from the other project. Opening a different project starts another fresh session in the other folder. The two analyses cannot accidentally read each other’s files, and changes to the environment in one project have no effect on the other.
The practical effect is that a project keeps everything related to one piece of work in one folder, makes file paths short and portable, and isolates each analysis from every other one. We will discuss projects again in Chapter 4 because they interact with sessions in a way that deserves its own treatment.
R projects are not mandatory. You can work with R by simply saving scripts alongside data files in any folder, without ever creating a .Rproj file. Many people start out that way. But projects are a substantial improvement over the ad hoc setup, and once your work grows past a couple of scripts and a single dataset, the organization that projects impose becomes hard to do without. Your future self will thank your present self for adopting projects early.
To create a project: in the RStudio menu, click File > New Project. A dialog opens with three choices.
- New Directory creates a new empty folder on your computer and sets it up as a project.
- Existing Directory turns a folder you already have into a project.
- Version Control creates a project by cloning a Git or SVN repository (we will not use this for now).
For a beginner, New Directory > New Project is the simplest path. Choose a name (e.g., my_first_project), choose a location on your computer, and click “Create Project.” RStudio creates the folder, places a .Rproj file inside it, and opens the new project. You will see the Files panel pointing at the new (empty) project folder.
3.5.1 Video walkthrough
You may find the following short video helpful for visualizing how to set up and use an R project.
3.6 R Markdown (.Rmd)
An R Markdown file is a plain-text file (extension .Rmd) that mixes prose with R code. The prose is written in a simple formatting language called Markdown; the code goes into “chunks” demarcated by special markers. When you “knit” the file, R runs the code, captures the output (numbers, tables, plots), and assembles a finished document (HTML, PDF, or Word) that contains the prose and the results, intermixed.
R Markdown is what you use when you want a document that is also a complete record of an analysis: a lab report, a methods write-up, a thesis chapter, or a journal article.
To create one in RStudio: File > New File > R Markdown. RStudio will pre-fill the file with a small example. Save it with File > Save, run it with the “Knit” button, and a finished document appears.
You will not produce R Markdown documents in Section 1 of this book. They are mentioned here so that the file extension does not surprise you, and so that the conceptual map is complete: a script is for code only, an R Markdown file is for prose plus code with results.
3.7 Putting the pieces together
A useful summary:
- The environment is the in-memory state. It exists only while R is running.
- A script (
.R) is a saved record of code. It does not contain results. - An RData file (
.RData) is a saved snapshot of objects. It contains values, not code. - An R project (
.Rproj) is a folder set up to keep one piece of work organized. - An R Markdown file (
.Rmd) is a document that mixes prose and code, producing a finished report when rendered.
In a typical research project you will use all of these together: a project folder containing scripts that produce intermediate RData files, with one or more R Markdown files writing up the analysis.
3.8 Tutorial: create your first project, script, and RData file
The following is a short hands-on exercise. Doing it once will make the rest of the book easier to follow.
- Open RStudio.
- Click File > New Project > New Directory > New Project.
- Name the directory
r_book_practiceand place it somewhere convenient (e.g., your Documents folder). Click Create Project. - In the new project, click File > New File > R Script. A blank script opens.
- Type the following lines into the script:
participants <- 100
mean_age <- 21.4
condition_labels <- c("control", "treatment")- Save the script with Ctrl+S (Cmd+S on macOS). Name it
setup.R. The file should now appear in the Files panel of RStudio. - Run the entire script: click “Source” at the top of the script panel. The three lines execute. Look at the Environment panel: the three objects should now be listed.
- Save those three objects to disk:
save.image("setup_state.RData")A new file, setup_state.RData, appears in your project folder.
- Close RStudio entirely. When asked whether to save the workspace, answer No. (We will use the explicit
save.imagewe just ran, not the implicit save-on-close.) - Reopen the project by going to your file browser, navigating to the
r_book_practicefolder, and double-clicking the.Rprojfile. RStudio reopens with that project loaded. - The Environment panel is empty: the previous session is gone. Recover the three objects:
load("setup_state.RData")The Environment panel now lists the three objects again.
You have just used a project, a script, and an RData file together, and you have seen the difference between code (preserved in the script) and state (preserved in the RData file).
3.9 Check your understanding
1. What is the “environment” in R?
2. What happens to the environment when you close R?
3. Which file type is the most authoritative record of what you did, and should be saved religiously?
4. What does save.image("session.RData") do?
5. What is the practical purpose of an R project?
6. Which best describes an R Markdown (.Rmd) file?
7. When RStudio asks whether to “save the workspace” on closing, should you say yes?