RStudio最新版本结合dplyr捕获输出时的格式编码异常问题
capture.output() for Tibbles in RStudio 1.4+ Problem Overview
When working with tibbles in the latest RStudio (version 1.4.1106 "Tiger Daylily"), using capture.output() to capture printed tibble output results in unwanted ANSI escape codes (for coloring and styling) instead of clean plain text. This issue didn’t pop up in older RStudio versions or the base R GUI.
Example of the Issue
library(dplyr) x <- tibble(test=c("Hello","World")) # Capturing output returns messy ANSI codes txt <- capture.output(x, type = "output") print(txt)
Output with unwanted codes:
[1] "\033[38;5;246m# A tibble: 2 x 1\033[39m" " tes " [3] " \033[3m\033[38;5;246m<chr>\033[39m\033[23m" "\033[38;5;250m1\033[39m Hello" [5] "\033[38;5;250m2\033[39m World"
Root Cause
RStudio 1.4+ enables styled/colored output for tibbles by default, using the crayon and pillar packages to add visual formatting. When you use capture.output(), it captures the raw output stream—including these ANSI escape codes that control text color, boldness, and italics.
Solutions
1. Disable Styling for a Single Print Call
Force plain text output by adding style = "plain" to the print() function inside capture.output():
txt <- capture.output(print(x, style = "plain")) print(txt)
Clean expected output:
[1] "# A tibble: 2 x 1" " test " " <chr>" "1 Hello" "2 World"
2. Disable Colored Output Globally
If you want to turn off styled output for all tibble prints in your session, set these options:
# Disable all crayon-based colored output options(crayon.enabled = FALSE) # Alternatively, force CLI to use only 1 color (no styling) options(cli.num_colors = 1)
After setting these, capture.output(x) will return plain text without any ANSI codes for the rest of your session.
3. Fine-Tune Pillar Styling
Since tibbles use the pillar package for formatting, you can disable specific styling features individually instead of turning off all coloring:
options( pillar.bold = FALSE, # Turn off bold text pillar.underline = FALSE, # Turn off underlining pillar.syntax_highlight = FALSE # Turn off syntax highlighting for data types )
This gives you granular control over which formatting elements to disable.
Environment Details
- RStudio Version: 1.4.1106 "Tiger Daylily" (desktop mode)
- R Version: 4.0.5
- Attached Packages:
dplyr_1.0.5 - Relevant Dependencies:
crayon_1.4.1,pillar_1.6.0
内容的提问来源于stack exchange,提问作者Regis

