How to use the cat() function for multiline strings in R

Overview

Creating multiline strings is a simple way to split a long string into different lines in your code. To create multiline strings in R, we use the cat() function.

To use the cat() function, all we need to do is pass the multiline string variable as a parameter value, as shown below:

cat(multiline_variable)

The multiline_variable parameter is the variable that contains the multiline string.

Code

string1 <- 'In the land of myth
and in times of magic,
the destiny of a great kingdom
rests on the shoulders of a young man.'
# using the cat() function
cat(string1)

When the cat() function is not used to return a multiline variable (string), R will simply add \n at the end of each line break. \n is an escape character, and n tells us that it is a new line.

Code

string1 <- 'In the land of myth
and in times of magic,
the destiny of a great kingdom
rests on the shoulders of a young man.'
# without using the cat() function
string1

Free Resources