qdread
qdread

Reputation: 3943

How to write console output to a text file with Rscript, like you can with R CMD BATCH

In the past I have used R CMD BATCH to execute R code from the command line on a Linux server. The syntax I used was

R CMD BATCH --no-save --no-restore rcode.r output.txt

The above code writes console output to output.txt which can be monitored as the script is running. Is this also possible with Rscript? I would prefer to use Rscript since I have heard that R CMD BATCH is deprecated.

To clarify my original question, R CMD BATCH writes all console output, including messages, warnings, and print() statements, to output.txt. In contrast Rscript rcode.r > output.txt writes only the print()ed output to the text file and everything else to the terminal. How can I replicate the behavior of R CMD BATCH with Rscript?

Upvotes: 6

Views: 4290

Answers (2)

qdread
qdread

Reputation: 3943

I discovered after some digging that, at least on the Linux system I'm using, Rscript is just a convenience function. If you call

Rscript --verbose foobar.r

you will see the underlying call is:

running
  '/usr/lib/R/bin/R --no-echo --no-restore --file=foobar.r'

This means that --no-echo is baked into Rscript.

Therefore the solution is to run

/usr/lib/R/bin/R --no-restore --file=foobar.r > output.txt

where the --no-echo is removed, and the output is redirected to a text file as suggested by @MrFlick. The commands will be echoed in addition to the output.

You can create a new alias for Rscript if you want --no-echo to be removed by default. For example, in my .bashrc file I have the following:

function Rscript2() { R --no-restore --file="$1"; }
export -f Rscript2

Now, in my Slurm batch job scripts, I can run Rscript2 file.R to get the desired behavior: all R console output is included in the slurm-*.out files.

Upvotes: 6

MrFlick
MrFlick

Reputation: 206207

Just redirect the output to a file like you would with any other command line output

Rscript rcode.r > output.txt

Upvotes: 2

Related Questions