Something that may have come up during the project is referencing data sets and other files in our Rmarkdown document.
In this lab, we’ll look at how RStudio interacts with your computer’s
file system, how file paths work, and how to save data from
R to use later.
Before we get into R, let’s spend a few minutes
organizing our course files.
If you haven’t already done so, create a folder on your computer
named STA230. I recommend either creating this folder on
your Desktop or in your Documents.
Inside this folder, create three subfolders:
Labs — for your lab files.Data — for datasets we use in class.HW — for homework assignments.Projects - You get the idea…Your folder structure should look something like this:
STA230/
├── Labs/
├── Data/
├── HW/
└── Projects/
If you already have a folder for STA230, you do not need to create another one! Just make sure the subfolders exist.
If you have existing course files, move a few into their appropriate folders. You can finish organizing the rest outside of class.
RStudio has a built-in file browser that allows us to navigate our computer’s folders without leaving RStudio.
You can find this under the Files tab, usually in the lower-right pane. From here, you can open folders, create new folders, rename files, and perform many of the same operations you would using your computer’s regular file browser.
We can also use the Files pane to change R’s working directory.
When we ask R to read or save a file, it needs to know where to look. R uses a location called the working directory.
We can check our current working directory using:
getwd()
The output will be a file path identifying a folder on your computer.
We can change the working directory directly using
setwd(), or we can do so through RStudio’s file
browser.
Navigate to your STA230 folder in the Files pane. Then
click the cog/gear icon (More) and select Set As Working
Directory.
Run getwd() again. You should see a path ending in your
STA230 folder.
Try the following command:
list.files()
This function lists the files and folders in your current working
directory. You should see the three folders you created earlier, along
with anything else you have stored in STA230.
Now use RStudio’s file browser to set Data as your
working directory and run getwd() and
list.files() again.
Notice how the results change depending on which folder is your working directory.
When you’re finished, return your working directory to the main
STA230 folder.
A file path tells your computer where a particular file is located. For example, a file stored on a Windows computer might have a path resembling:
C:/Users/Student/Documents/STA230/Data/penguins.csv
This is an absolute path, meaning it specifies the location of the file starting from a particular location on your computer.
Absolute paths depend on how a particular computer is organized. A path that works on one student’s computer might not work on another.
We can also use relative paths.
A relative path describes where a file is located relative to some starting location.
For example, suppose our working directory is STA230,
and we have a file named penguins.csv inside the
Data folder.
Instead of writing its full location, we can use:
"Data/penguins.csv"
R interprets this as: Starting from the working directory, open the Data folder and find penguins.csv.
We can also check whether a particular file exists:
file.exists("Data/penguins.csv")
This returns TRUE if R can find the file at that
location and FALSE otherwise.
We use / to separate folders. In R, it’s generally
easiest to use forward slashes, even if you’re working on Windows.
There are a few useful conventions for relative paths:
| Symbol | Meaning |
|---|---|
Data/file.csv |
Look inside the Data subfolder. |
../ |
Move up one folder. |
../../ |
Move up two folders. |
./ |
Refer to the current folder. |
For example, suppose our working directory is
STA230/Labs, but we want to access a dataset in
STA230/Data.
We could use:
"../Data/penguins.csv"
The .. tells R to move up from Labs into
STA230, after which it enters Data.
We’ve already spent time importing datasets using functions such as
read.csv(). We can also export data from R into files on
our computers.
We’ll use the palmerpenguins dataset for this
example.
First, make sure your working directory is set to
STA230, then run:
library(palmerpenguins)
write.csv(penguins, "Data/penguins.csv", row.names = FALSE)
The write.csv() function saves the dataset as a CSV
file. The row.names = FALSE argument prevents R from adding
an unnecessary column containing row numbers.
Since our working directory is STA230, R saves the file
inside our Data folder.
We can also save R objects using saveRDS():
saveRDS(penguins, "Data/penguins.rds")
An RDS file preserves the R object, including information about its structure and variable types. Unlike CSV files, RDS files can also store objects such as lists, models, and functions.
We can retrieve these files using read.csv() and
readRDS():
penguins_csv = read.csv("Data/penguins.csv")
penguins_rds = readRDS("Data/penguins.rds")
Using the examples above, export the penguins dataset as both a
.csv and an .rds file into your
Data folder.
Open RStudio’s Files tab and navigate to the
Data folder. Verify that both files were created.
Now open your computer’s regular file explorer and locate those same files.
Return to RStudio and change your working directory to
STA230/Labs.
Using relative paths, import both files into R without changing your working directory or moving the files. You will need to modify the paths in the examples above.
Use file.exists() to verify that R can locate both files
from your new working directory.
When you’re finished, return your working directory to
STA230.
Relative paths aren’t unique to R. They are used in websites, HTML documents, and many other types of computer files.
For example, when I link to a lab on our course website, I might write:
[Open the Lab](Labs/Lab.html)
This tells the browser to look inside a folder named
Labs for a file named Lab.html.
The path is interpreted relative to the location of the document containing the link. This is slightly different from R code, where relative paths are generally interpreted relative to the working directory.
Suppose we have the following files:
STA230/
├── index.html
└── Labs/
├── Lab1.html
└── Lab2.html
Inside index.html, a link to Lab1 could use:
[Lab 1](Labs/Lab1.html)
But if we were writing a link inside Lab2.html to return
to index.html, we would use:
[Home](../index.html)
The same principles apply to relative paths whether we’re importing data or linking between documents.
Throughout the semester, you may have noticed that the Environment tab in RStudio has accumulated quite a few objects. Every time we create a data frame, vector, or function, R stores that object in our environment until we remove it or end the R session.
Having a large number of objects in your environment can make it difficult to keep track of what you’re working with. It can also cause problems if your code depends on objects that you created previously but forgot to include in your script.
We can remove individual objects using rm():
rm(penguins_csv)
Or remove all objects from the global environment using:
rm(list = ls())
You can also clear your environment through RStudio by clicking the broom icon at the top of the Environment tab.
Clearing your environment does not delete your R scripts or files saved on your computer. It only removes the objects currently stored in R’s memory.
Save any work you want to keep, then clear your environment using
either the broom icon or rm(list = ls()).
Your Environment tab should now be empty.
Try importing one of your saved penguins files again. Even though you’ve cleared the environment, the file should still be available.
Once you’ve verified this, clear your environment again.
One useful habit is to occasionally clear your environment and run your script again from the beginning. If everything works, that’s a good indication that your script contains the code needed to reproduce your results, rather than relying on objects left over from earlier work.
There is no file submission for this lab. When you’ve finished, please show me or the class mentor the following:
STA230 folder, with the Labs,
Data, and HW subfolders, using your computer’s
file explorer..csv and
.rds formats in your Data folder. Show me
these files in RStudio’s Files tab.Once I’ve checked your work, you’re finished with the lab!