Pregunta

Suppose I have an R script:

library('nnet')    
something <- runif(50); 
print(something) 

When I run this script from the command line, it prints:

> library('nnet')
> something <- runif(5); 
> print(something)
 [1] 0.04665518 0.93574275 0.96387299 0.07410239 0.92834019

I would like it to print only:

[1] 0.04665518 0.93574275 0.96387299 0.07410239 0.92834019

and I cannot figure out how to do this. sink("/dev/null") doesn't do anything, redirecting stderr manually doesn't do anything, and I can't find any useful information on this.

¿Fue útil?

Solución

Resolution is to run with Rscript, and not with R. Examples elsewhere (e.g. How can I read command line parameters from an R script?), run scripts from the command line with

R --args args1 args2... < foo.R

running with

Rscript foo.R args1 args2 ...

produces only the output, and not the script. It's also a much cleaner way to run scripts.

Otros consejos

Not an R user myself, but is this something that might be helpful to you? How can I run an 'R' script without suppressing output?

From the linked question:

specify print.eval parameter set to TRUE if you want to get only the output (and not the commands). If you would need the commands too, you should set echo to TRUE (which implies setting print.eval to TRUE).

For example:

source('myscript.R', print.eval = TRUE)
source( 'path/name/filnam.R' , verbose=FALSE)

For RStudio IDE (Version 1.1.383) in Windows:

Pressing Ctrl+Shift+Enter keys run entire script with echo (verbose)

Pressing Ctrl+Shift+S keys run entire script without echo (non-verbose)

For running in the terminal directly:

R --slave --args dense 12 0.98 < foo.R

For running R script from Python:

process = subprocess.Popen(["R --slave --args %s %d %.2f < /path/to/your/rscript/foo.R" % (, 12, 0.98) ], shell=True)
process.wait()

For running R script in terminal / command line and in the background, while suppress / avoid printing every line of the scripts and the output of the program, using R CMD BATCH as follow:

R CMD BATCH--slave foo.R 2>&1  foo.out &

See also this reference

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top