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.filespecifies a file to write to instead of the console.sepis the separator between objects (default is a space).fillcontrols line wrapping.labelsis deprecated and ignored.appenddecides 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.
| Parameter | Description | Default |
|---|---|---|
| ... | Objects to print (text or variables) | Required |
| file | File to write output (empty means console) | "" |
| sep | Separator between objects | " " |
| fill | Line wrap control | FALSE |
| labels | Deprecated and ignored | NULL |
| append | Append to file if TRUE | FALSE |
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.