3.3 Current working directory
An aside about directory paths. When working with R, you need to be aware of your current working directory (CWD). As the name suggests, this is the directory (folder) in which you are currently working. If no paths are specified, any files you wish to import or export to and from R will be with respect to this directory.
The Files tab in the bottom-right corner is not always set to your CWD. Think of this as a Windows explorer (or Finder in Mac) built-in with Rstudio. This tab allows you to navigate your file system and check on files. This means that during your session, you may navigate away from your CWD.
To check your CWD use the command:
getwd()
and to change your CWD to another location use the setwd(file-path)
command.
When using save()
it is better to explicitly specifing the path to the folder where you want to save your data to so that no mistakes are made when you move away from your CWD.
3.3.1 File paths
File paths come in two forms:
- relative filepath is relative to the current working directory. For example, using a Windows system, if my currently working directory is
C:\Users\john.smith\Documents
and I save a script called “area-rectangle.R” without specifying a specific location, then R will save the file in the locationC:\Users\john.smith\Documents\area-rectangle.R
. - absolute filepath is the fullpath of the location starting with the drive letter in Windows (e.g. C: or D:); or in Linux and Mac starting with the
\
symbol, meaning https://aarnet.zoom.us/j/579276844the root directory (the top).
R uses the forward slash (/
) to specify filepaths by default. If you use the Windows format with the backwards slash (\
), you will get an error. You can use two backward slashes (\
) to escape the error but it’s faster and easier to read to use the /
slash.