rrscript

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


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?


Solution

  • 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