Interactive Exercise
This exercise explores running R interactively in two ways: issuing commands that run immediately at the R prompt and creating a script of these commands to run once the script has been saved.
Open R or R Studio on your computer by opening the application. You can open R on the command line by typing R
at the command prompt.
Once the R console opens, use the commands below to enter some data and find the mean. The >
symbol represents the R prompt. Type the characters following the prompt and press return when you reach the end of the line. The lines that start with are output lines that show what R will print in the console when you enter the preceding command. Your console output should match the sample output below. The next topic will describe the commands in more detail.
Interactive mode allows for data exploration and checking elements of code. Often, you will want to document the analysis steps by writing a sequence of commands to a script file. Telling R to execute the script file allows you to exactly duplicate the analysis and a slight modification of the script will allow it to process other data. You might write and test a script to analyze a subset of a large dataset on your own computer and then use your script on an HPC system to execute the full analysis. While systems like Stampede2 and Frontera allow interactive use, large analyses are typically run via scripts submitted as a batch job.
To complete this exercise, create an R script with the above commands and then source the file. This will execute all of the lines in the file and produce similar output to entering the commands manually. Printing output has to be done explicitly in scripts, using the function (as discussed below). In R or R Studio, choose "New Document" (R) or "R Script" (R Studio) from the File menu. Enter the same commands you entered interactively, but substitute
,
and
for the lines
,
and
. Save the file as
in your home directory. While both R and R Studio have an interface button to run an open R file, try running the script using only console commands. In the R console, source the script file (this example assumes that you saved the script file in your home directory and make the appropriate changes to the file path). Make sure to use double backslashes if you are using Windows.
Do you get the same output as when you typed in the first set of commands? You should!