Using Scripts

You will find using R to be a more pleasant experience if you get used to using scripts. Scripts allow you to save your code and reuse it without having to type it in from scratch every time. The concept of a script is very simple — it’s just a text file with R commands in it.

To start a new script, select File->New script from the menu in R. A built-in text editor will pop up, and you’ll be able to type your script into this window.

Comments: You can (and should) use comments to annotate your code. Anything on a line following the # symbol will be ignored by R, so you can use # to delimit your comments.

An Example: Try out an example by creating a new script and typing the following commands into it:

#A sample script that generates a scatterplot
male_mating_success <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3)
male_reproductive_success <- c(0, 0, 0, 0, 0, 178, 74, 48, 174, 71, 280, 47, 427, 245, 452, 308, 364, 452, 255)
plot(male_plot <- male_reproductive_success ~ male_mating_success)
points(male_plot, pch=19, col=”firebrick”)

Running the Script: To run the script one line at a time, just open the script in R, select the line you would like to run, and press ctrl-R on your keyboard. To run the script all at once, make sure your script is in your working directory and type source(“sampleplotscript.R”) at the R command prompt (where “sampleplotscript.R” is the name of your script). The script needn’t be open in R for this method to work.

 


Advertisements