How to make a directory your working directory
If you want to work in an orderly manner, you will be creating subdirectories in your folder. Or you will want to work with data files in teachers' folders without copying them home. Whenever you want to work with a file, you will have to read it in an R object with a function. There are different functions for reading different file formats, but each wants to know the file's file path. You can specify it in two ways: absolute or relative.
To find out the absolute path of a file in the GUI, you hit the gear button and select Copy Folder Path to Clipboard. With absolute paths, you are always safe. However, if they are long, they are going to clutter your code. Therefore you also should use relative paths.
The relative path is always relative to your working directory. The default in RStudio's factory settings is your home directory. Whenever your file of interest is located in your home directory and you have not changed the default, mentioning just the file name in the file is good enough.
Things get more complicated when you start coralling your files to RStudio projects or when you change your working directory in your script or in RStudio's Global options. For the start - whenever you get an error message saying that a file or directory was not found, check what your current working directory is. You can manipulate it in the GUI as well as programmatically.
Manipulating the working directory in the GUI
Hit the gear button and select from the drop-down menu either Set as Working Directory to make your current directory your working directory or Go to Working Directory to find out what your current working directory is. This option will take you there.
Manipulating the working directory programmatically
To see the absolute path to your working directory, call function getwd() (just type it like this. When you typing it in the Console, just hit Enter; if you are writing a script, higlight that line and hit the Run button above the script-writing pane and you will see the result down in the Console).
To change your working directory, call function setwd(). It has one argument called dir. It takes the absolute or relative path to your intended working directory, enclosed by quotes. The code below changes the working directory from home to doc_target (a subdirectory of home, see figure below) checks the change, and changes the working directory back to home (tilde ~ stands for your home).
> getwd() [1] "/lnet/aic/personal/cinkova" > setwd("doc_target") > getwd() [1] "/lnet/aic/personal/cinkova/doc_target" > setwd("~") > getwd() [1] "/lnet/aic/personal/cinkova" |
Back to Teaching Materials