0
0
R-programmingHow-ToBeginner · 3 min read

How to Print Output in R: Simple Syntax and Examples

In R, you can print output using the print() function for displaying objects or the cat() function for concatenating and printing text. Use print() for most cases and cat() when you want formatted text without quotes or extra line breaks.
📐

Syntax

The basic way to print output in R is using the print() function, which takes an object as input and displays it. Another common function is cat(), which concatenates and prints text without quotes and can control line breaks.

  • print(x): Prints the value of x with quotes for strings and a new line.
  • cat(..., sep = " ", fill = FALSE): Prints concatenated text with custom separators and optional line wrapping.
r
print(x)
cat(..., sep = " ", fill = FALSE)
💻

Example

This example shows how to print a string and a number using both print() and cat(). Notice how print() adds quotes around strings and a new line, while cat() prints text directly.

r
x <- "Hello, R!"
y <- 42

print(x)
print(y)

cat("Hello, R!", "The answer is", y, "\n")
Output
[1] "Hello, R!" [1] 42 Hello, R! The answer is 42
⚠️

Common Pitfalls

One common mistake is using cat() without a newline character, which causes the output to run together on the same line. Another is expecting print() to format text without quotes or extra information.

Always add \n at the end of cat() output to move to the next line.

r
cat("Hello")
cat("World")  # Output runs together

# Correct way:
cat("Hello\n")
cat("World\n")
Output
HelloWorld Hello World
📊

Quick Reference

FunctionPurposeNotes
print(x)Prints R objects with quotes for stringsAdds a new line automatically
cat(...)Concatenates and prints textNo quotes, control line breaks with \n
message(...)Prints messages to consoleUsed for warnings or info
sprintf(format, ...)Formats strings before printingUse with print or cat

Key Takeaways

Use print() to display R objects with automatic formatting and new lines.
Use cat() to print text without quotes and control spacing and line breaks.
Always add \n in cat() to avoid output running together on one line.
print() is best for debugging; cat() is better for user-friendly messages.
Remember that print() shows quotes around strings, cat() does not.