Hello (Again) World

Download

Before moving on to new material, we can apply what we’ve learned so far to enhance our Hello World script from the last tutorial. I’ll also introduce a handy new function called paste() that can be used to combine strings. Before moving on, ensure that your hello.R script resembles mine:

# Hello World
# Last edited on 08-14-2016

# Store string in object
my_string <- "Hello, world!"

# Print string
print(my_string)       # Correct syntax

Let’s begin by tidying up a little. Since we’re making edits to the code, we should set the comment on line 2 to the current date. Because we also know by now that the syntax on line 8 is correct, we no longer need the comment:

# Hello World
# Last edited on 08-16-2016

# Store string in object
my_string <- "Hello, world!"

# Print string
print(my_string)

Again, this is about forming good habits. As you learn and begin to write more complex code, you will appreciate having learned to keep things clean and organized.

The next thing we’ll do is query the class of our object my_string, using class(). Store the result of that function in a new variable called my_class, making sure to write a comment describing what you’re doing:

# Hello World
# Last edited on 08-16-2016

# Store string in object
my_string <- "Hello, world!"

# Store class of object
my_class <- class(my_string)

# Print string
print(my_string)

Next, we’ll use the paste() function to combine the contents of both our objects. Paste, like most R functions, accepts multiple arguments. These arguments are separated by commas, and provide additional details on what action you want a function to perform. In this case, each of the strings you wish to combine are passed as separate arguments, like so:

> paste("Sidney", "Crosby")
[1] "Sidney Crosby"

Create a new object called statement, and assign it the string "Hello, world! is a character" using the paste() function. Then, substitute my_string for statement in the final print() command:

# Hello World
# Last edited on 08-16-2016

# Store string in object
my_string <- "Hello, world!"

# Store class of object
my_class <- class(my_string)

# Form statement with paste()
statement <- paste(my_string, "is a", my_class)

# Print string
print(statement)
[1] "Hello, world! is a character"

We can improve this statement, but I first need to introduce additional arguments for both paste() and print(). As you learn R, Google will be your best friend. You’ll be able to pull up documentation for R function like paste() to help give you a better understanding of how they may be used. Like I mentioned earlier, most R functions accept multiple arguments. Many of these are given default values, meaning you mustn’t specify them when using the function. In the documentation for paste(), in addition to accepting one or more objects to be concatenated, the argument sep has a default value of " ". As its name might indicate, this argument is used to pass a string to separate each term. The output obtained above proves that paste() will separate each term with a space unless otherwise specified. If you had tried to add punctuation, the output would have resembled:

[1] "Hello, world! is a character ."

We’ll prevent this by explicitly setting sep to "", an empty character. The new statement on line 11 should be:

statement <- paste(my_string, " is a ", my_class, ".", sep = "")

Note that we’ve had to put spaces on either side of "is a" to account for the fact they are no longer formed by default. The next thing we want to do is put the original string "Hello, world!" in quotations. Since the printed output is already contained within quotations, and quotes in quotes are ugly, we’ll do two things. First, we’ll use the quote argument for print() to remove the quotation marks from the output. Use your friend Google to find out how to do this (I’ll have done it in my code below if you get stuck). The second thing you’ll do is add single quotes to the statement using paste (you’ll find that R does not like """; see below for an explanation/solution).

Note: Open quotations or parentheses confuse R. When it sees a new quotation, it will evaluate everything as text until a new quotation completes it. This is more advanced material, but if you want to coerce R to treat something as a literal character, you can escape its properties using \ (backslash). You can ask for a literal double quote with "\"", but here’s the rub: not all functions in R know how to recognize escapes. Print(), for example, does not. Instead, you can use cat() with the added benefit that it does not surround the output in quotations

# Hello World
# Last edited on 08-16-2016

# Store string in object
my_string <- "Hello, world!"

# Store class of object
my_class <- class(my_string)

# Form statement with paste()
statement <- paste("'", my_string, "'", " is a ", my_class, ".", sep = "")

# Print string
print(statement, quote = FALSE)
[1] 'Hello, world!' is a character.

Next, to illustrate how to use logical expressions in a real albeit impractical script, I’ll create a new object called is_character and assign to it the result of the expression my_class == "character". Then, I’ll modify the statement to print "It is TRUE that 'Hello, world!' is a character.":

# Hello World
# Last edited on 08-16-2016

# Store string in object
my_string <- "Hello, world!"

# Store class and boolean
my_class <- class(my_string)
is_character <- my_class == "character"

# Form statement with paste()
statement <- paste("It is ",
                   is_character,
                   " that ",
                   "'", 
                   my_string, 
                   "'", 
                   " is a ", 
                   my_class, 
                   ".", 
                   sep = ""
                   )

# Print string
print(statement, 
      quote = FALSE
      )
[1] It is TRUE that 'Hello, world!' is a character.

You’ll notice I’ve restructured my code. This is a matter of preference and you’re not obligated to follow suit. This is closer to my preferred structure, though in time you are likely to develop your own style.

The upper-case TRUE is an eyesore in our printed statement, so we’ll use a new function, tolower(), to convert it to lower-case:

tolower(is_character),                                  # Line 13
[1] It is true that 'Hello, world!' is a character.     # Output

Voila!

In the next lesson, I’ll talk about the ubiquitous [1] and vectors.

Complete and Continue  
Discussion

3 comments