2.5 Workspace
The workspace is your current R working environment and includes any user-defined objects (vectors, matrices, data frames, lists, functions). The following code provides the basics for understanding, configuring and customizing your current R environment.
2.5.1 Working Directory
The working directory is the default location for all file inputs and outputs.
# returns path for the current working directory
getwd()
[1] "C:/Users/Aubur/github/afit-dsl/r-basics"
# returns the basename of the current working directory
home <- basename(getwd())
# go up one level above the current working directory
setwd('..')
# set the working directory to a specified directory
setwd(home)
2.5.2 Environment Objects
To identify or remove the objects (i.e. vectors, data frames, user defined functions, etc.) in your current R environment:
# list all objects
ls()
# identify if an R object with a given name is present
exists("object_name")
# remove defined object from the environment
rm("object_name")
# you can remove multiple objects by using the `c()` function
rm(c("object1", "object2"))
# basically removes everything in the working environment -- use with caution!
rm(list = ls())
2.5.3 Command History
You can view previous commands one at a time by simply pressing the up arrow on your keyboard or view a defined number of previous commands with:
2.5.4 Saving and loading your workspace
You can save and load your workspaces. Saving your workspace will save all R files and objects within your workspace to a .RData file.
# save all items in workspace to a .RData file
save.image()
# save specified objects to a .RData file
save(object1, object2, file = "myfile.RData")
# load workspace into current session
load("myfile.RData")
Note that saving the workspace without specifying the working directory will default to saving in the current directory. You can further specify where to save the .RData by including the path: save(object1, object2, file = "/users/name/folder/myfile.RData")
2.5.5 Workspace Options
You can view and set options for the current R session:
2.5.6 Shortcuts
To access a menu displaying all the shortcuts in RStudio you can use option + shift + k. Within RStudio you can also access them in the Help menu » Keyboard Shortcuts.