Script Files in R
From ECON 520
It can be a bit tedious to write the same code over and over again in R. Script files let you write R commands in a separate text file, and then run them in R. Some advantages to script files:
- You can have an exact record of the commands for later use
- You can add comments (which are ignored by R, but useful for remembering what you intended to do)
- You can modify your previous work without retyping everything you did
Here's how to use script files in R:
First, create a text file using a text editor such as Notepad in Windows, TextEdit in Mac, or pico in Unix. Write your commands, one to a line. Lines beginning with a "#" are comments and ignored by R. Be sure to save the file as a text file (not in Word format, or rich text format), and note where this file is saved.
In R, make sure the working directory is the same one that contains the script file. You can change the working directory using the pull-down menu, or using the setwd() command. Then, use the command source(file="<filename>") to have R read the script file and execute the commmands.
Here is an example. The file testscript.R contains the following lines:
x <- rnorm(1000,1) # comments ignored by R hist(x)
After typing up testscript.R and saving it, we start R and issue:
> source(file="testscript.R")
R generates 1000 standard normal draws, and then generates their histogram. The histogram should pop up in a separate window.
