How to download an R script from the internet and run it

While you can input commands interactively into the R window, it is often more convenient to create a file (usually with a .R extension) that contains all the R code, and then ask R to run (aka: source) the commands in the file.

In the file short_test.R, I have put the R code to do a loop, and print out the numbers one through ten.  To run this script, first you need to create a folder on your computer that we will refer to as your working directory… Have this folder off of your root directory (C: directory in windows, and off of your base user directory in other platforms), and call this folder short_test_dir

Now, in R, you can use the setwd() command to change to that working directory (which tells R that from now on you want it to look only in that directory for files)

For windows, type at  the R command prompt

setwd("C:/short_test_dir")

and for Linux or Max OSX type

setwd("~/short_test_dir")

(the twiddle ~ means your home directory).  If you get an error at this point, it is because you did not properly create the folder short_test_dir under your home folder (or the C: directory in Windows), or you made a spelling mistake, or you forgot one or both quotes.

Now, a problem with Windows is that .R and data files downloaded from the internet tend to be saved with a .txt extension, and it is annoying to constantly have to remove it.  In addition, web browsers running on Windows seem to usually assume that any text file you are looking at on the internet must be HTML, so when downloading such files it puts HTML prefaces at the top, which prevent the files from being run in R.  To get around these problems, it is usually easiest to download the files using the R function download.file().

Thus, for windows, at the R command line type

download.file("http://www.sherrytowers.com/short_test.R","short_test.R")

and for Linux and Mac OSX type

download.file("http://www.sherrytowers.com/short_test.R","short_test.R")

If you get an error at this point, you’ve made a spelling mistake in the URL, or in the local directory name. Or you’ve forgotten one or more quotes.

Now, to run the file, type at the R command prompt

source("short_test.R")

You should see the numbers 1 through 10 being printed to the screen.

If you are creating your own .R file, you need to make sure that (particularly for Windows) a .txt is not appended to the end of it.

Now, using a text editor like Notepad (Windows) or TextEdit (Mac OSX), or whatever text editor you feel comfortable with, change the short_test.R file to print the numbers 11 to 100, but in a line, with each number separated by a space (rather than in a column).  Save the file, then make sure you can run the new file from the R command line.

You will be expected to have completed this exercise on your own before class, and to be adept at downloading, editing, and running R scripts.

Leave a Reply