0
0
R-programmingHow-ToBeginner · 3 min read

How to Use cat in R: Syntax, Examples, and Tips

In R, cat() is used to print text and variables to the console without quotes and with control over spacing and line breaks. You pass strings or variables separated by commas, and use \n for new lines inside the text.
📐

Syntax

The basic syntax of cat() is:

  • cat(..., file = "", sep = " ", fill = FALSE, labels = NULL, append = FALSE)

Where:

  • ... are the objects (text or variables) to print.
  • file specifies a file to write to instead of the console.
  • sep is the separator between objects (default is a space).
  • fill controls line wrapping.
  • labels is deprecated and ignored.
  • append decides if output appends to a file.
r
cat(..., file = "", sep = " ", fill = FALSE, labels = NULL, append = FALSE)
💻

Example

This example shows how to print text and variables together using cat(). It also demonstrates adding a new line with \n.

r
name <- "Alice"
age <- 30
cat("Name:", name, "\nAge:", age, "years\n")
Output
Name: Alice Age: 30 years
⚠️

Common Pitfalls

One common mistake is expecting cat() to add a new line automatically like print(). You must add \n explicitly for line breaks. Another is forgetting that cat() does not show quotes around strings, which can confuse beginners.

r
cat("Hello")
cat("World")

# Correct way with new line
cat("Hello\n")
cat("World\n")
Output
HelloWorld Hello World
📊

Quick Reference

Use cat() to print combined text and variables without quotes. Remember to add \n for new lines. Use sep to change space between items.

ParameterDescriptionDefault
...Objects to print (text or variables)Required
fileFile to write output (empty means console)""
sepSeparator between objects" "
fillLine wrap controlFALSE
labelsDeprecated and ignoredNULL
appendAppend to file if TRUEFALSE

Key Takeaways

Use cat() to print text and variables together without quotes in R.
Add \n inside strings to create new lines when using cat().
cat() does not add spaces or new lines automatically; control them with sep and \n.
cat() can write output to files using the file parameter.
Remember cat() outputs directly and returns NULL invisibly.