You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RStudio最新版本结合dplyr捕获输出时的格式编码异常问题

Fixing ANSI Escape Codes in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 14:02:30