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

Time:03-12

With bash, we can use set -x to print to the terminal all executed commands. Is there a way to do that with an R script?

CodePudding user response:

I don't think Rscript by itself is going to do what you want, but there is a way. Let me walk you through finding that way.

I'll start with a naive script in foo.R:

1 1
2*3

How can we call 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'
...

Noticing the --verbose, I try:

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

[1] 2
[1] 6

Not yet, but ... --no-echo seems interesting. Let me mimic those arguments and use R directly:

$ 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

After reading the output from R --help, we can silence some of that by adding --quiet:

$ R --quiet --no-restore --file=foo.R
> 1 1
[1] 2
> 2*3
[1] 6

CodePudding user response:

We could use loadhistory()

"There are several history mechanisms available for the different R consoles, which work in similar but not identical ways. Other uses of R, in particular embedded uses, may have no history. This works under the readline and GNOME and MacOS X consoles, but not otherwise (for example, in batch use or in an embedded application)."

See here: 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)
  • Related