在 R 中,如何在执行命令之前 trace/log 命令

In R, how to trace/log commands before executing them

使用bash,我们可以使用set -x将所有执行的命令打印到终端。有没有办法用 R 脚本做到这一点?

我们可以使用loadhistory()

“有多种历史记录机制可用于不同的 R 控制台,它们以相似但不相同的方式工作。R 的其他用途,特别是嵌入式用途,可能没有历史记录。这在 readline 和 GNOME 和MacOS X 控制台,但不是其他情况(例如,在批处理中使用或在嵌入式应用程序中)。"

看这里: https://astrostatistics.psu.edu/su07/R/html/utils/html/savehistory.html

loadhistory(file = ".Rhistory")
savehistory(file = ".Rhistory")

history(max.show = 25, reverse = FALSE, pattern, ...)

timestamp(stamp = date(),
          prefix = "##------ ", suffix = " ------##",
          quiet = FALSE)

我不认为 Rscript 本身会做你想做的事,但有办法。让我带你找到那条路。

我将从 foo.R 中的简单脚本开始:

1+1
2*3

如何调用Rscript

$ Rscript --help
Usage: /path/to/Rscript [--options] [-e expr [-e expr2 ...] | file] [args]

--options accepted are
  --help              Print usage and exit
  --version           Print version and exit
  --verbose           Print information on progress
  --default-packages=list
                      Where 'list' is a comma-separated set
                        of package names, or 'NULL'
...

注意到 --verbose,我尝试:

$ Rscript --verbose foo.R
running
  '/usr/lib/R/bin/R --no-echo --no-restore --file=foo.R'

[1] 2
[1] 6

还没有,但是……--no-echo 看起来很有趣。让我模仿那些论点并直接使用 R

$ R --no-restore --file=foo.R

R version 4.0.5 (2021-03-31) -- "Shake and Throw"
Copyright (C) 2021 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> 1+1
[1] 2
> 2*3
[1] 6

读取 R --help 的输出后,我们可以通过添加 --quiet:

来消除其中的一些内容
$ R --quiet --no-restore --file=foo.R
> 1+1
[1] 2
> 2*3
[1] 6