How to Read Command Line Parameters in R Script

To read command line parameters in R script, you can use the “commandArgs()” function. This function returns a character vector of the command line arguments passed to the R script.

Here’s a step-by-step guide on how to read command line parameters from an R script:

Step 1: Create an R script file

# Get command line arguments
args <- commandArgs(trailingOnly = TRUE)

# Print the arguments
cat("Number of arguments:", length(args), "\n")
cat("Arguments:", args, "\n")

In this script, the commandArgs(trailingOnly = TRUE) function extracts only the arguments after the script name. The cat() function prints the number of arguments and the arguments themselves.

Step 2: Run the R script with command line parameters

Open the terminal or command prompt, and navigate to the R script file’s directory.

Rscript Pro.R arg1 arg2 arg3


Number of arguments: 3
Arguments: arg1 arg2 arg3

Replace arg1, arg2, and arg3 with your desired command line parameters.

You can now access and use these command line parameters in your R script. For example, you can assign them to variables or use them in a conditional statement.

That’s it.

Leave a Comment