Open In App

R Program to Print a New Line in String

Last Updated : 16 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In R, printing a new line within a string is a common task, especially when formatting output for better readability or organizing information, we will discuss how to print a new line in a string using R Programming Language.

Method 1: Using cat() function

In this method, the need to call the cat() function which is here responsible to print text and text.

Syntax:

cat(text/file = “”, sep = ” “, fill = FALSE, labels = NULL, append = FALSE)

Parameters:

  • Text/file: text or file you want to print.
  • sep: separator
  • fill: If fill=TRUE, a new line will be printed if page is filled.
  • labels: labels if any
R
# storing strings in variables
string1 <- "GEEKS"
string2 <- "FOR"
string3 <- "GEEKS"

# line serperator
cat(string1,string2,string3)

# passing a string using \n to split
cat("GEEKS \nFOR \nGEEKS")

# passing variables using \n
cat(string1,"\n",string2,"\n",string3)

Output:

GEEKS FOR GEEKS
GEEKS  
FOR  
GEEKS
GEEKS  
FOR  
GEEKS

In this example, the \n character is used to break the string into multiple lines. The output shows the strings printed with line breaks where specified.

Method 2: Using writeLines() function

The writeLines() function is another useful function in R to write text line by line. It’s especially useful for outputting strings with newline characters.

Syntax:

writeLines(text, con = stdout(), sep = “\n”, useBytes = FALSE)

Parameters:

  • Text: text you want to print
  • con: A connection object or a character string.
  • Sep: separator
  • UseBytes: True/False
R
x <- "GEEKS \n FOR \n GEEKS"

# print x variable
writeLines(x)

# printing a string with \n new line
writeLines("GEEKS \nFOR \nGEEKS")

Output
GEEKS 
 FOR 
 GEEKS
GEEKS 
FOR 
GEEKS

Method 3: Split and Print New Line (Custom Function)

If you want more precision on how the new lines are inserted, you can define a custom function that splits the string and prints every piece on a separate line. The following example uses the strsplit() function to split the string into characters and print them line by line whenever it hits spaces.

R
printNewLine <- function(string) {
  splitString <- strsplit(string, split = "")[[1]]
  for (i in 1:length(splitString)) {
    cat(splitString[i])
    if (splitString[i] == " ") {
      cat("\n")
    }
  }
}

# Example usage:
printNewLine("GEEKS FOR GEEKS")

Output
GEEKS 
FOR 
GEEKS


Next Article

Similar Reads