Run R script from command line
If you want the output to print to the terminal it is best to use Rscript
Rscript a.R
Note that when using R CMD BATCH a.R
that instead of redirecting output to standard out and displaying on the terminal a new file called a.Rout will be created.
R CMD BATCH a.R
# Check the output
cat a.Rout
One other thing to note about using Rscript is that it doesn't load the methods
package by default which can cause confusion. So if you're relying on anything that methods provides you'll want to load it explicitly in your script.
If you really want to use the ./a.R
way of calling the script you could add an appropriate #!
to the top of the script
#!/usr/bin/env Rscript
sayHello <- function(){
print('hello')
}
sayHello()
I will also note that if you're running on a *unix system there is the useful littler package which provides easy command line piping to R. It may be necessary to use littler to run shiny apps via a script? Further details can be found in this question.
What's the best way to use R scripts on the command line (terminal)?
Content of script.r
:
#!/usr/bin/env Rscript
args = commandArgs(trailingOnly = TRUE)
message(sprintf("Hello %s", args[1L]))
The first line is the shebang line. It’s best practice to use /usr/bin/env Rscript
instead of hard-coding the path to your R installation. Otherwise you risk your script breaking on other computers.
Next, make it executable (on the command line):
chmod +x script.r
Invocation from command line:
./script.r world
# Hello world
Running R Code from Command Line (Windows)
You want
Rscript.exe
.You can control the output from within the script -- see
sink()
and its documentation.You can access command-arguments via
commandArgs()
.You can control command-line arguments more finely via the getopt and optparse packages.
If everything else fails, consider reading the manuals or contributed documentation
Run Rscript interactive (readline()) in Command-line
Instead of asking, you can pass arguments, parameters, to the script.
Instead of
scrpt.R:
r=readline(prompt="number: ")
print(sqrt(r))
You can do
scrpt.R:
args<-commandArgs(TRUE)
print(sqrt(as.numeric(args[1])))
And at the command window,
c:\R\ax>Rscript scrpt.R 2 arg2 arg3
[1] 1.414214
Related Topics
Automatically Delete Files/Folders
Issue with Geom_Text When Using Position_Dodge
Remove Backslashes from Character String
Ggplot2 Heatmap with Colors for Ranged Values
Efficient Way to Filter One Data Frame by Ranges in Another
Problems Installing the Devtools Package
Drawing Pyramid Plot Using R and Ggplot2
Overlay Data Onto Background Image
Converting Excel Datetime Serial Number to R Datetime
The Same Width of the Bars in Geom_Bar(Position = "Dodge")
Add "Filename" Column to Table as Multiple Files Are Read and Bound
Floating Point Less-Than-Equal Comparisons After Addition and Substraction
Line Break When No Data in Ggplot2
Moving Average of Previous Three Values in R