What you see isn't always what you have

Take a look at line2, the string you just defined, by printing it:

line2

Even though you used single quotes so you didn't have to escape any double quotes, when R prints it, you'll see escaped double quotes (\")! R doesn't care how you defined the string, it only knows what the string represents, in this case, a string with double quotes inside.

When you ask R for line2 it is actually calling print(line2) and the print() method for strings displays strings as you might enter them. If you want to see the string it represents you'll need to use a different function: writeLines().

You can pass writeLines() a vector of strings and it will print them to the screen, each on a new line. This is a great way to check the string you entered really does represent the string you wanted.

This exercise is part of the course

String Manipulation with stringr in R

View Course

Exercise instructions

We've put your lines from Alice's Adventures in Wonderland in a vector called lines.

  • Take a look at lines to see R's representation of the strings.
  • Pass lines to writeLines() to see the content of strings you've created.
  • By default writeLines() separates the strings with a newline, which you can change using the sep argument. Write lines to the screen again, but this time set the sep argument to a space, " ".
  • Finally, try using writeLines() on the string "hello\n\U1F30D". You'll learn about what's going on here in the next exercise.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Putting lines in a vector
lines <- c(line1, line2, line3)

# Print lines
___

# Use writeLines() on lines
___

# Write lines with a space separator
___

# Use writeLines() on the string "hello\n\U1F30D"
___