The sink() function redirects all console output (print statements, results) to a file instead of displaying it on screen. It’s useful for capturing analysis results, creating reports, or logging output from long-running analyses.

Important: sink() captures printed output, not data objects. For exporting data frames, use write.csv() or write.table() instead.

When to Use sink()

You’ll use sink() when:

  • Capturing print output to a text file
  • Creating analysis reports by redirecting console output
  • Logging function results
  • Creating audit trails of analysis
  • Generating text-based reports

Proper Syntax

# Start redirecting output to file
sink("output_file.txt")

# All print() and cat() output goes to file
print(data)
cat("Analysis complete\n")

# Stop redirecting, return to console
sink()

Pro Tip: Always use sink() without arguments to resume console output!

Examples

Correct Usage: Capturing Console Output

Let’s see how to properly use sink() to capture printed output:

# Redirect output to file
sink("analysis_results.txt")

# All output below goes to file
cat("Analysis Results\n")
cat("================\n\n")

# Print objects - output goes to file
print(summary(mtcars))
cat("\nCorrelation:\n")
print(cor(mtcars[,1:4]))

# Resume normal console output
sink()

# This prints to console (output redirecting is off)
print("Analysis complete!")

Real Example: Creating an Analysis Report

# Capture complex analysis output
sink("report.txt")

# Header
cat("Statistical Analysis Report\n")
cat("Generated: ", format(Sys.time()), "\n\n")

# Analysis
cat("Summary Statistics:\n")
print(summary(mtcars))

cat("\n\nData Overview:\n")
print(head(mtcars))

# Return to console output
sink()

cat("Report written to report.txt\n")

Common Mistakes to Avoid

Mistake 1: Confusing sink() with export functions

# ❌ WRONG - sink() doesn't export to CSV like this
sink("data.csv")
data <- mtcars
sink()  # This won't create a proper CSV!

# ✅ CORRECT - Use write.csv() for data export
write.csv(mtcars, "data.csv")

Mistake 2: Forgetting to close sink()

# ❌ PROBLEM - If you forget sink(), console output stays redirected!
sink("file.txt")
# ... lots of code ...
# Oops! Forgot to call sink() - all future output goes to file!

# ✅ SOLUTION - Use try/on.exit to guarantee cleanup
f <- function() {
  sink("file.txt")
  on.exit(sink())  # Guaranteed to run even if error occurs
  print("This goes to file")
}

Mistake 3: Nesting sink() calls without tracking

# ❌ CONFUSING - Multiple sink levels
sink("file1.txt")
sink("file2.txt")
sink("file3.txt")
sink()  # Closes file3, still in file2!
sink()  # Closes file2, still in file1!
sink()  # Finally back to console

# ✅ SAFER - Use sink(file=NULL) to close all
sink()  # May not work as expected
sink(file=NULL)  # Better guarantee to reset

Mistake 4: Expecting sink() to save data

# ❌ WRONG - sink() doesn't save the object
sink("data.txt")
my_data <- data.frame(x=1:5, y=6:10)
sink()  # my_data is not saved to file!

# ✅ CORRECT - Print first, then save
print(my_data)  # Goes to sink
# Or use save() to save objects
save(my_data, file="my_data.RData")

Pro Tips

  1. Always check sink status: sink.number() returns how many sinks are active
  2. Use with sessionInfo(): sink() + sessionInfo() + sink() for reproducible reports
  3. Combine with cat() for formatted output: More control than print()
  4. Use append=TRUE: sink(file="output.txt", append=TRUE) to add to existing file

See Also