1

我有两台 Windows 机器。两个 Windows 10。当我在每个上运行以下代码时,我得到两个非常不同的输出:

library(tibble)

sink(file.path(tempdir(), "test.log"), append = FALSE)
     
print(as_tibble(mtcars))

sink()

一台机器给了我预期的输出: 在此处输入图像描述

另一台机器给了我相同的 tibble 数据,但似乎正在打印所有蜡笔颜色代码: 在此处输入图像描述

起初我认为它必须是 R 版本或蜡笔版本的差异。但是我现在已经在 R 4.0.3 和 crayon 1.3.4 上同步了。两者的 Tibble 版本都是 3.0.4。不知道接下来要检查什么。第二台机器最初拥有所有东西的更新版本。但我尽可能地恢复了,我仍然得到颜色代码。

有人对如何诊断有任何建议吗?

4

2 回答 2

1

根据@HenrikB 的出色建议,这是最终对我有用的代码:

  library(tibble)
  
  sink(file.path(tempdir(), "test.log"), append = FALSE)
  
  withr::with_options(c("crayon.colors" = 1), { 
    print(as_tibble(mtcars))
  })
  
  sink()

在此处输入图像描述

于 2021-04-04T19:29:40.717 回答
1

颜色由蜡笔包控制。您可以查询该包以了解支持多少种颜色,例如

> crayon::num_ansi_colors()
[1] 8
> crayon::has_color()
[1] TRUE

有不同的方法来配置颜色的数量。我想说,设置环境变量是最好的,因为它也将用于并行处理,如果你最终使用它的话。所以,

> Sys.setenv(R_CLI_NUM_COLORS = 2)
> crayon::num_ansi_colors()
[1] 2
> crayon::has_color()
[1] TRUE

如果将其设置为一种颜色,那么您将获得:

> Sys.setenv(R_CLI_NUM_COLORS = 1)
> crayon::num_ansi_colors()
[1] 1
> crayon::has_color()
[1] FALSE

现在,这里的关键是当只有一种颜色时,不会产生 ANSI 颜色转义码。因此,根据当前 R 环境是否支持颜色 ( crayon::has_color()),您将获得 ANSI 转义码。

由于您可能只想在sink():ing 时限制颜色数量,因此您不想永久设置。最简单的是为此使用withr,例如

library(tibble)

sink(file.path(tempdir(), "test.log"), append = FALSE)
     
withr::with_envvar(c(R_CLI_NUM_COLORS = 1), { 
  print(as_tibble(mtcars))
})

sink()

那应该为你做。

于 2021-04-04T18:21:05.947 回答