Print and Cat in R

cat() vs print() in R - A Complete Guide

📘 Understanding cat() and print() in R with Examples

In R programming, displaying output is a basic but important part of debugging and building clear programs. Two commonly used functions for output are:

  • print()
  • cat()

While both are used to display output, they behave differently, especially when formatting output or printing multiple values.

🐱 What is cat()?

cat() stands for "concatenate and print". It is used to combine values and display them as a single string.

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

🔑 Key Features:

  • Does not print the type of object
  • No quotes or newlines by default
  • Can be used to write to files

🖨️ What is print()?

print() is a generic function used to print any R object to the console.

print(x, ...)

🔑 Key Features:

  • Shows quotes for strings
  • Adds a newline automatically
  • Good for structured output and debugging

📊 Examples: cat() vs print()

📌 Example 1: Basic Strings

cat("Hello World")
# Hello World

print("Hello World")
# [1] "Hello World"

📌 Example 2: Multiple Values

cat("My score is", 90, "\n")
# My score is 90

print(c("My score is", 90))
# [1] "My score is" "90"

📌 Example 3: Newlines and Tabs

cat("Line1\nLine2\n")
# Line1
# Line2

cat("Item1\tItem2\tItem3\n")
# Item1	Item2	Item3

📌 Example 4: Writing to a File

cat("Writing this to file", file = "output.txt")

📌 Example 5: Printing Lists

mylist <- list(a = 1, b = 2)

cat(mylist)
# Error – cat() can't print complex objects

print(mylist)
# $a
# [1] 1
# $b
# [1] 2

📌 Example 6: cat() for Formatting

name <- "Shubham"
score <- 95
cat("Student:", name, "scored", score, "marks.\n")

📌 Example 7: Looping with cat()

for(i in 1:3) {
  cat("Value is", i, "\n")
}
# Value is 1
# Value is 2
# Value is 3

📋 When to Use What?

Task Use cat() Use print()
Display text with formatting Yes No
Debug variables No Yes
Print complex objects No Yes
Write to file Yes No
Clean output in loops Yes No
Structured console output No Yes

🧪 Final Practical Example

name <- "Ravi"
marks <- 82
subject <- "Maths"

# Using cat
cat("Student", name, "scored", marks, "in", subject, "\n")

# Using print
print(paste("Student", name, "scored", marks, "in", subject))

🎯 Summary

  • Use cat() when you want user-friendly, formatted text output (e.g. progress messages, summaries).
  • Use print() when debugging, or printing structured data types like vectors, lists, or data frames.

Post a Comment

0 Comments

Me