Print Character String to Newline of RStudio Console in R (Example)
In this tutorial, I’ll illustrate how to show a character string with newlines in the RStudio console in the R programming language.
Table of contents:
- Creation of Example Data
- Example 1: Print Newline with writeLines Function
- Example 2: Print Newline with cat Function
- Video, Further Resources & Summary
Here’s the step-by-step process…
Creation of Example Data
In the examples of this R programming tutorial, we’ll use the following character string text in R:
x <- "this is my first line\nthis is my second line" # Create example string
Our example string consists of two sentences separated by “\n”, indicating a newline.
We can print this character string to the RStudio console as follows:
x # Default print of string # "this is my first line\nthis is my second line"
As you can see, the whole character string was print into a single line and the separator “\n” is still shown. In the following examples, I’ll show how to return our character string in multiple lines.
Example 1: Print Newline with writeLines Function
Example 1 shows how to return our character string in several lines with the writeLines function. We simply have to insert the name of the data object containing our character string (i.e. x) into the function:
writeLines(x) # Apply writeLines function # this is my first line # this is my second line
As you can see based on the output of the RStudio console, our character string is shown in two different lines.
Example 2: Print Newline with cat Function
An alternative to the writeLines function is the cat function. The cat function can be applied the same way:
cat(x) # Apply cat function # this is my first line # this is my second line
Video, Further Resources & Summary
Do you want to know more about printing data in R? Then you might want to watch the following video of my YouTube channel. I’m showing the R programming code of this tutorial in the video.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, you may want to have a look at the related posts of this website:
In this R tutorial you learned how to paste and display substrings of a character string text in separate lines. In case you have additional questions, let me know in the comments below.
Statistics Globe Newsletter