9.1 Workspace management functions
Here are some functions helpful for managing your workspace that we’ll go over in this chapter:
Code | Description |
---|---|
ls() |
Display all objects in the current workspace |
rm(a, b, ..) |
Removes the objects a , b … from your workspace |
rm(list = ls()) |
Removes all objects in your workspace |
getwd() |
Returns the current working directory |
setwd(file = "dir) |
Changes the working directory to a specified file location |
list.files() |
Returns the names of all files in the working directory |
write.table(x, file = "mydata.txt", sep) |
writes the object x to a text file called mydata.txt . Define how the columns will be separated with sep (e.g.; sep = "," for a comma–separated file, and sep = \t" for a tab–separated file). |
save(a, b, .., file = "myimage.RData) |
Saves objects a , b , … to myimage.RData |
save.image(file = "myimage.RData") |
Saves all objects in your workspace to myimage.RData |
load(file = "myimage.RData") |
Loads objects in the file myimage.RData |
read.table(file = "mydata.txt", sep, header) |
Reads a text file called mydata.txt , define how columns are separated with sep (e.g. sep = "," for comma-delimited files, and sep = "\t" for tab-delimited files), and whether there is a header column with header = TRUE |
9.1.1 Why object and file management is so important
Your computer is a maze of folders, files, and selfies (see Figure 9.2). Outside of R, when you want to open a specific file, you probably open up an explorer window that allows you to visually search through the folders on your computer. Or, maybe you select recent files, or type the name of the file in a search box to let your computer do the searching for you. While this system usually works for non-programming tasks, it is a no-go for R. Why? Well, the main problem is that all of these methods require you to visually scan your folders and move your mouse to select folders and files that match what you are looking for. When you are programming in R, you need to specify all steps in your analyses in a way that can be easily replicated by others and your future self. This means you can’t just say: “Find this one file I emailed to myself a week ago” or “Look for a file that looks something like experimentAversion3.txt
.” Instead, need to be able to write R code that tells R exactly where to find critical files – either on your computer or on the web.
To make this job easier, R uses working directories.