How to Print Output in R [6 Ways]

Here are six primary methods used to print output in R:

  1. Using print()
  2. Using implicit printing
  3. Using cat()
  4. Using message(), warning(), and stop()
  5. Using sprintf() to format string
  6. Writing to a file

Method 1: Using print()

The print() function is explicitly used to display the value of an object.

Syntax

print(data, digits, na.print)

Parameters

  1. data: It specifies the argument to be displayed.
  2. digits: It defines the minimal number of significant digits.
  3. na.print: It indicates NA values output format.

Visual Representation

Visual Representation of print() Function in R

Example 1: Simple program of print() function

data <- 1:5
print(data)

Output

[1] 1 2 3 4 5

Example 2: Passing “digits” argument

Passing digits argument to the print() function

data <- 1 / 5
data2 <- 111 / 23
data3 <- 10900 / 2966

print(data, digits = 2)
print(data2, digits = 3)
print(data3, digits = 4)

Output

[1] 0.2
[1] 4.83
[1] 3.675

Example 3: Passing na.print argument

If you pass the na.print argument to empty, it will replace NA values with nothing in the output.

Visualization of Passing na.print argument to print() function

mat <- matrix(c(1, NA, 3, 4, NA, 6, 7, 8, NA),
   nrow = 3, byrow = TRUE
)

print(mat)
cat("After passing na.print argument to empty", "\n")

print(mat, na.print = "")

Output

Figure of Passing na.print argument to print() function

Method 2: Implicit printing

In interactive sessions (like R console or RStudio’s console), simply typing a variable or expression will print its value.

data <- 42

data

Output

[1]  42

Method 3: Using cat()

The cat() function concatenates and prints its arguments. It’s helpful for printing custom messages or formatting output. This function does not automatically add a new line at the end, so you often need to include “\n” for line breaks.

x <- 21

cat("The value of x is:", x, "\n")

Output

The value of x is: 21

Method 4: Using message(), warning(), and stop()

The message() prints a message but does not stop the execution of a function.

The warning() issues a warning message but, like message(), allows the execution to continue.

The stop() prints an error message and stops the execution.

message("This is a message.")

warning("This is a warning.")

Output

This is a message.

Warning message:
This is a warning.

Method 5: Using sprintf() for Formatted Strings

The sprintf() is used for formatted strings (similar to printf() in C/C++). It’s helpful when you need to format numbers or strings before printing.

x <- 19

sprintf("The value of x is: %f", x)

Output

[1] "The value of x is: 19.000000"

Method 6: Writing to a file

To print output to a file, you can use cat(), write.table(), or similar functions with a file connection.

x <- 1921

cat("The value of x is:", x, file = "output.txt", append = TRUE)

Output

Output of printing a variable in file in R

That’s it!

Leave a Comment