Chapter 5: R Print Output
R Print Output means how to show results, messages, variables, tables, or anything on your screen (console in RStudio) so you (or others) can see what’s happening.
R gives you several ways to do this — not just one print() like in many languages. Each method has its own personality, strengths, and best-use cases. We’ll go through them one by one, like I’m showing you on my screen, with exact copy-paste examples, differences, when to use which, and common beginner mistakes.
Open RStudio → new script → paste and run line-by-line (Ctrl+Enter) as we go.
1. The Simplest & Most Automatic Way: Just Type the Name (Implicit Print)
In interactive mode (console or script run line-by-line), R auto-prints the result if you don’t assign it.
|
0 1 2 3 4 5 6 7 8 9 10 11 |
# Just type this 42 + 58 # Or a variable marks <- c(78, 92, 85, 67) marks # ← auto-prints the vector |
Output:
|
0 1 2 3 4 5 6 7 |
[1] 100 [1] 78 92 85 67 |
→ Notice the [1] ? That’s R saying “this is element 1 of a vector”. Very useful for quick checks, but ugly in final scripts/reports.
2. The Classic: print() function
Most generic way — works on almost everything (numbers, vectors, data.frames, models, lists…).
|
0 1 2 3 4 5 6 7 8 9 |
print("Namaste Hyderabad! 🌶️") # string print(3.14159) # number print(marks) # vector print(head(iris)) # famous built-in dataset (first 6 rows) |
Typical output for vector:
|
0 1 2 3 4 5 6 |
[1] 78 92 85 67 |
For data frame:
|
0 1 2 3 4 5 6 7 8 9 |
Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa ... |
Useful arguments for print():
|
0 1 2 3 4 5 6 7 |
print(marks, quote = FALSE) # no quotes around strings if any print(head(iris), digits = 2) # limit decimal places |
Key fact: print() returns the object invisibly → useful in pipes sometimes.
|
0 1 2 3 4 5 6 7 |
library(dplyr) iris |> filter(Species == "setosa") |> print(n = 3) # shows only 3 rows |
3. The Most Flexible & Clean: cat() – Concatenate and Print
cat() is what most experienced R users use for nice, custom messages.
Main differences from print():
- No [1] index shown
- No automatic quotes around strings
- Can combine many things (text + variables) easily
- Adds no newline by default → you control with \n
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Basic cat("Today in Hyderabad it's 29°C\n") # Combine text + variables city <- "Hyderabad" temp <- 29.5 humidity <- 60 cat("In ", city, " today: ", temp, "°C & ", humidity, "% humidity\n") |
Output (clean, no extras):
|
0 1 2 3 4 5 6 |
In Hyderabad today: 29.5 °C & 60 % humidity |
Pro examples:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Progress message in a loop for(i in 1:5){ cat("Processing file", i, "of 5...\n") } # With rounding avg <- mean(marks) cat("Average marks =", round(avg, 1), "\n") # Average marks = 80.5 |
Very common pattern (you’ll see everywhere):
|
0 1 2 3 4 5 6 |
cat("Iteration =", i, "| Loss =", format(loss, digits=4), "\n") |
Note: cat() returns NULL invisibly → cannot do x <- cat(“hi”) (it will be NULL).
4. For Informational / Diagnostic Messages: message()
Used mostly in functions/packages to show progress/info without being “normal output”.
- Goes to stderr (separate stream) → in R Markdown/Quarto you can suppress messages but keep normal prints
- Always adds newline
|
0 1 2 3 4 5 6 7 |
message("Starting analysis for ", city, "...") message("Found ", nrow(iris), " rows in dataset") |
Output (usually in red/italic in RStudio):
|
0 1 2 3 4 5 6 7 |
Starting analysis for Hyderabad... Found 150 rows in dataset |
When to prefer message():
- Inside your own functions
- Progress updates
- Non-critical info (warnings use warning(), errors use stop())
5. Quick Comparison Table (Cheat Sheet Style)
| Method | Best For | Adds [1] index? | Quotes strings? | Auto newline? | Can combine text+vars easily? | Returns the object? | Typical Use Case |
|---|---|---|---|---|---|---|---|
| Just name | Quick interactive check | Yes | Yes (for char) | Yes | No | Yes | Exploring in console |
| print() | Show any R object nicely | Yes (vectors) | Yes | Yes | No | Yes (invisible) | Showing data.frames, models |
| cat() | Clean custom messages | No | No | No (add \n) | Yes | NULL | Progress, logs, user messages |
| message() | Info / progress in functions | No | No | Yes | Yes | NULL | Package development, diagnostics |
6. Bonus: Redirect Output to File with sink()
Sometimes you want all output (print + cat + auto-prints) to go to a .txt file instead of console.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Start redirecting sink("my_output_log.txt") # creates/overwrites file print("This goes to file") cat("So does this\n") summary(iris) # whole summary goes to file! sink() # IMPORTANT: close it! Return to console # Now check the file (in Files pane or open it) |
Very useful for long analyses / batch jobs.
7. Your Mini Practice Right Now (Run This!)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# Setup student <- "Webliance" score <- 92.7 passed <- TRUE # Different styles – see differences print(student) # with quotes & [1] cat("Student:", student, "\n") # clean cat("Score:", score, "| Passed:", passed, "\n") message("Analysis complete for ", student, "!") # Fancy one-liner cat(sprintf("Hi %s! Your score is %.1f/100 → %s\n", student, score, ifelse(passed, "Passed 🎉", "Try again"))) |
Output mix will look like:
|
0 1 2 3 4 5 6 7 8 9 10 |
[1] "Webliance" Student: Webliance Score: 92.7 | Passed: TRUE Analysis complete for Webliance! Hi Webliance! Your score is 92.7/100 → Passed 🎉 |
Perfect — now you understand why people choose one over another.
Questions?
- Want deeper dive into sprintf() / format() for fancy formatting?
- How to print tables nicely (kable, pander, flextable)?
- Or next topic (subsetting? dplyr? plotting?)?
Just say — I’m here with the next whiteboard ready! ☕🚀
