Running Code from Files: Scripts
If you w ill be entering more than a small handful of commands, rather than simply typing
them at the command prompt, it is prudent to use an editor to place them in a file. This
allows you to fix any errors in your code without needing to retype all of your commands.
It is also ver y useful if you are experimenting with some properties of a figure to get it just
right; when you have it just the way you like, you can save your commands to a file so that
you can easily reproduce or modify the figure again later.
Both R and MATLAB have built-in editors
and ways to execute commands from their
built-in editors and from files. Following standard computer ter minology, a file (or editor
window) containing some R or MATLAB commands is typically called a script.
7.1 Current working directory
Both R and MATLAB use what is called a current working directory.
The current working
directory is the default location for reading and writing files.
The command getwd() will display the current working directory. In the OS-X ver-
sion of R, it is a lso displayed at the top of the Conso le window. You can use
setwd('some/path/here') to set the current working directory to the specified path.
Use fo rward slashes as the path separators. Tilde expansion will be done on sys-
tems that support it, where a tilde represents your home directory. (You can enter
path.expand('~') to see what R considers your home directory to be.) So for ex-
ample, on most platforms you can enter a command like setwd('~/R-documents'),
and under an appropriate version of Windows you could enter a command like
You can see a listing of the files in the current working directory via the command dir(),
and can make a new directory (folder) named foo via dir.create('foo').
The command p wd s hows (prints) the current working directory, or you can also use cd
with no arguments. Yo u can use cd with an argument to set the working directory, e.g., cd
some/path/here. Tilde expansion will be done on s ome operating systems. Note that if your
path contains directories with spaces in them, you’ll ne ed to use the function-call form of
The standard Linux version of R does not have a GUI with an editor, but there are facil ities to integrate
the Emacs editor with R. Also see the free and open source RStudio project.
“Directory” is the traditional Unix name for what many people refer to as a “f older” under Windows
and Mac OS-X.

Get R and MATLAB now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.