1-07: Outputs

0.1 Changes…

1 Purpose

  • Output variables to the Console tab

  • Output messages to the Console tab

  • Output vectors, sequences, and mathematical operations

  • Output special characters to the Console tab, including a line feed

  • Output mixed message and variable statements to the Console tab

1.1 Files for the lesson

The files for this lesson:

 

If you have any questions about the material in this lesson, feel free to email them to the instructor, Charlie Belinsky, at belinsky@msu.edu.

2 Output to console

The Console tab has many uses and one of them is to output messages from a script – the messages can contain text, variable, or some combination of the two.  Outputting messages to the Console can be done using the function cat(), which stands for concatenate. This is R’s way of saying that cat() will concatenate (combine) variables and values to create an output.

 

Extension: cat() vs print()

2.1 Output a message

We will first use cat() to output a text message to the Console tab – to do this we need to put the message in quotes:

cat("Hello");
Hello
Figure 1: Outputting a text message in the Console tab

If you do not use quotes (” “), R will think you are referring to a variable.  For instance, the line cat(Hello) gives you the Object not found error because R thinks this is a reference to a variable named Hello – and, in this case, there is no variable named Hello

cat(Hello); # Will cause an «object not found» error
Error in cat(Hello) : object Hello not found
Figure 2: An error that occurs if you try to output a variable (object) that does not exist in your script.

Note: If there is a variable named Hello in your script, then cat(Hello); will output the value of the variable Hello.

2.2 Output multiple messages

You can add as many cat() statements to your script as you like and they will be displayed sequentially in the Console tab:

cat("Hello, World.");
cat("How are you?");
cat("I am fine.");
Hello World. How are you? I am fine.
Figure 3: Output message without spacing

2.3 The line feed: \n

But there is a problem here – R puts no spacing in between the lines (Figure 3).  This is typical behavior of programming languages – they do not add line feeds (e.g., enter or return) unless the script specifically requests that a line feed is added.

 

The instruction to add a line feed is to put \n inside the quotes ( “  ” ):

cat("Hello, World.\n");
cat("How are you?\n");
cat("I am\n fine.\n"); # the first \n will break up the line
Hello, World
How are you?
I am
 fine.
Figure 4: Message with line feeds

In Figure 4 we have our text on multiple lines.  Notice that the \n does not get printed to the screen.  \n is an instruction to R to add a line feed, sometimes called a newline character, and \n needs to be put inside the quotes.

 

\n can be put anywhere in a quote.  In the above code there is a \n put in between “am” and “fine”, hence the line feed between the two words.  The exact same message as Figure 4 can be output to the Console tab using only one cat() statement with multiple \n:

cat("Hello, World.\nHow are you?\nI am\n fine?\n");
Hello, World
How are you?
I am
 fine.
Figure 5: Using one cat() statement with multiple \n to output multiple lines of text

3 Escape character: backslash ( \ )

The backslash in programming is used in a string as an escape character. An escape character tells R that the next character is to be treated as a command rather than the character. This is similar to the way the Shift, Control, or Alt keys on your keyboard change the meaning of the character that is pressed with them (e.g, control-C is a command to copy).

 

Backslash can be used to

  • put in a control like a line feed ( \n ) or a tab ( \t )

  • print a character that has a functional meaning like a double quote ( \“ ). In other words, treat the double quote as a character for output, not as the start or end of a string. This also works if you want to output a backslash ( \\ )

  • use Unicode to print our characters not on the keyboard using Unicode.  Here is a link to a partial list of Unicode characters.  Use the Escape sequence given on the page.  Note: according to Wikipedia, there are around 150,000 Unicode characters – and just recently Unicode has added lots of emojis.

 

cat("\tAnd the boy said, \"Hello\" \n");
cat("Send a backslash \\ to the Console\n")
cat("Some Unicode characters: \u00C5 \u0A94 \u0115\n");
    And the boy said, "Hello" 
Send a backslash \ to the Console
Some Unicode characters: Å ઔ ĕ
Figure 6: Using backslash ( \ ) to output special characters.

4 Output messages with variables

Let’s output data from the twoWeekWeatherData.csv file to the Console tab.

 

First we will read in the file, like we did last lesson:

  weatherData = read.csv(file="data/twoWeekWeatherData.csv", 
                         sep=",",                   
                         header=TRUE);
                        

And then save the highTemp and lowTemp columns to their own variable:

highTemps = weatherData$highTemp;
lowTemps = weatherData$lowTemp;

We can directly output the whole temperature vector values along with a line feed:

cat(lowTemps);  # prints the variable lowTemps in the Console
cat("\n");      # adds a line feed -- so the next message goes to the next line
45 43 46 38 36 45 32 50 48 40 36 43 45 63
Figure 7: Output the 12 values in the lowTemps variable

4.1 Combine text and variables in one command

We can combine content (e.g., variables and text) in one cat() command by using comma to separate the different types of content:

cat("The low temps are:", lowTemps, "\n");
The low temperatures are: 45 43 46 38 36 45 32 50 48 40 36 43 45 63
Figure 8: Combining a text message and variables in one output

Trap: Misplacing (or forgetting) quotes

5 Output indexed values

We can output a single value from a vector by indexing it:

cat(lowTemps[4], "\n");     # 4th value in lowTemps

Or, output a more robust message about the 4th day:

cat("On the 4th day the high temperature was", highTemps[4], "and the low temperature was", lowTemps[4], "\n");
On the 4th day the high temperature was 40 and the low temperature was 38
Figure 9: Combining multiple text messages and variables in an output

Or, even do math on the values:

cat("On the 4th day the difference in temperature was", 
      highTemps[4] - lowTemps[4], "degrees\n"); 
On the 4th day the difference in temperature was 2 degrees

6 Output multiple values

We can use c() to index multiple values within a vector:

cat(lowTemps[c(4, 8, 3, 11)], "\n");  # 4th, 8th, 3rd, and 11th values in lowTemps
38 50 46 36 

Or, we can use the sequencing operators to output multiple values in a vector:

  cat(lowTemps[5:9], "\n");   # simple sequence: 5th through 9th value
  cat(lowTemps[seq(from=1, by=2, to=10)], "\n"); # Values 1,3,5,7,9
36 45 32 50 48
45 46 36 32 48
Figure 10: Output of sequenced values in lowTemps

And add messages to the above output:

  cat("Day 5-9 temperature:",lowTemps[5:9], "\n");  
  cat("Temp on odd days:", lowTemps[seq(from=1, by=2, to=10)], "\n");
Day 5-9 temperature: 36 45 32 50 48 
Temp on odd days: 45 46 36 32 48 
Figure 11: Outputting contiguous values in lowTemps using the sequencing operator.

cat() commands can go across multiple lines – this one cat() is functionally the same as the above two cat():

  cat("Day 5-9 temperature:", lowTemps[5:9], "\n", 
      "Temp on odd days:", lowTemps[seq(from=1, by=2, to=10)], "\n");
Day 5-9 temperature: 36 45 32 50 48 
Temp on odd days: 45 46 36 32 48 
Figure 12: Outputting the values of lowTemps using seq()

7 The concatenate, cat(), function

We have used cat() many times in this script to output variable and text to the Console but we really have not talked about cat() itself.

 

Let’s search for cat in the search bar of the Help tab:

Figure 13: Information about the cat() function in the Help tab.

The first part of cat() is the three dots “”.  When the 3 dots are at the beginning of a function, the three dots say that cat() will accept any number of objectsas inputs.  The objects can be text in quotes, string variables, numeric variables, or other objects we have not discussed yet like Dates.

 

Note: the three dots in cat() has a different meaning from the three dots in read.csv().  When three dots are at the first argument of a function (e.g., cat()) it means that any number of inputs are accepted.  When the three dots are elsewhere (e.g., read.csv()) it means the function can be extended with arguments that are not on the list.

 

After the three dots, cat() has 5 arguments: file, sep, fill, labels, and append. These all have default values (e.g., file=““, sep=” “)

7.1 The sep argument

Arguments are used to modify the behavior of a function.  sep changes how the different components of the output are separated– the default is to use 1 space.  We are going to change the sep argument.

 

Let’s take the code from above and add the sep argument to cat() and give sep the value ” ** “:

  cat("Day 5-9 temperature:", lowTemps[5:9], "\n", 
      "Temp on odd days:", lowTemps[seq(from=1, by=2, to=10)], "\n",
      sep = " ** ");

And you will notice that the different components in cat() are separated by ” ** “.

Day 5-9 temperature: ** 36 ** 45 ** 32 ** 50 ** 48 ** 
 ** Temp on odd days: ** 45 ** 46 ** 36 ** 32 ** 48 ** 
Figure 14: Using the sep argument in cat()

Note: The most common way people use sep is to set sep=““– in other words, set sep to nothing so nothing is added to the output.

 

Trap: Misplacing (or forgetting) quotes

7.2 The file argument

By default, cat() will output to the Console. But, you could have cat() output to a file by using the file argument.  The file argument in cat() works just like the file argument in read.csv() with one exception:  if the file does not exist yet then R will create the file.

 

So, this line:

cat("Hi", file="hello.txt");

creates a file called hello.txt in your Project Folder and add the text hi to the file.

 

Extension: Sending Console info directly to file

8 Application

A. Line 47 in the script downloaded for this lesson is beyond 85 characters, break the line up so that it functions the same but does not go over 85 characters.

 

B. In the Help for the function c(), the S3 method has 3 dots as the first argument. In comments answer: What does the three dots tell you about the c() function?

 

C.  Using one cat(), output to the Console:

  • the date of the 11th day and the amount of precipitation on that day

  • the difference in precipitation between the 3rd and 4th day

  • every 3rd days precipitation

  • the precipitation for days 12, 9, 4 – using a index vector created with c()

  • Challenge: output the total precipitation for the first 10 days (without using sum(), which is not something you have learned yet!)

Make sure you use newlines (\n) to make the output readable.

 

D. Using cat(), output the data from part B to a file named output.txt in your data folder (instead of the Console)

  • Use the file argument in cat()– the file format is the same as the file format in read.csv()

 

E. Challenge: Using cat(), append your name and three different Unicode characters to the text in the output.txt file created in part C.  Hint: look at the arguments in cat() – you need to change one of them.
 

 

Save the script as app1-07.r in your scripts folder and  email your Project Folder to Charlie Belinsky at belinsky@msu.edu.

 

Instructions for zipping the Project Folder are here.

 

If you have any questions regarding this application, feel free to email them to Charlie Belinsky at belinsky@msu.edu.

8.1 Questions to answer

Answer the following in comments inside your application script:

  1. What was your level of comfort with the lesson/application?

  2. What areas of the lesson/application confused or still confuses you?

  3. What are some things you would like to know more about that is related to, but not covered in, this lesson?

9 Extension: cat() vs print()

The two main functions used to output to the Console are cat() and print()The big difference is that print() does a lot more formatting of the output than cat().  You would likely use print() when you want to display the results of a statistical test, which often has a complicated format.  cat() does very little formatting on its own – cat() lets the programmer control the output.  You would use this when you want to output text and some simple data – or, where you really want control of the output format.

10 Trap: Misplacing (or forgetting) quotes

It is easy to accidentally forget a quote, add a quote, or simply move a quote to a place it does not belong. The following code has a missing quote on line 8 right after “The values are…

rm(list=ls());  options(show.error.locations = TRUE);

distance = 100;
time = 50;
velocity = distance/time;

cat("The values are..., "\nDistance: ", distance, "\ntime: ",
    time, "\nvelocity: ", velocity);

If you execute the script above, you will get the following message in the Console:

> source("~/.active-rstudio-document")
Error in source("~/.active-rstudio-document") : 
  ~/.active-rstudio-document:«7:26: unexpected '\\'»
6: 
7: cat("The values are..., "\
                            ^

The error is unexpected ‘\\’ on line 7, character 26. R is telling you that is does not understand why the character on line 7, character 26 is a backslash ( \ ). This might not be the most helpful message.

 

However, RStudio has a built-in feature to help you find misplaced quotes – the color scheme.  The quoted text is in a different color than other parts of the code.  For example, in the XCode color scheme – text in quotes is colored red.

 

Figure 15: Missing quote in cat()

Figure 15 shows that, right after “The value are… , the variables are all treated as if they are in quotes and the messages are outside the quotes. Since one quote was missing, the error propagated and assumed characters to be variables/numbers and variables/numbers to be characters.

 

We will add the missing quote to line 8:

cat("The values are...«"», "\nDistance: ", distance, "\ntime: ",
    time, "\nvelocity: ", velocity);

Now the correct components of the output are in quotes and the script executes without an error:

> source("~/.active-rstudio-document")
The values are... 
Distance:  100 
time:  50 
velocity:  2

11 Extension: Sending Console info directly to file

sink() is a commonly used command in R that redirects all Console output to a file. The following command will send all future Console output to the file output2.txt in the data folder.

sink(file="data/output2.txt") # send Console content to data

By “all future output”, RStudio will send the output from all script execution (no matter the script file) to the file until you undo the command like this:

sink(file=NULL)