Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 55 / 68

Receiving command-line arguments

This lesson covers receiving command-line arguments with R's commandArgs, with the aim of passing values in from outside at run time.

commandArgs(trailingOnly = TRUE) receives the command-line arguments — the values passed when running with Rscript. It is the essential mechanism for a script whose options can be switched at run time.

The sample code checks whether arguments were passed with ifelse(length(args) > 0, args[1], "Anonymous"), using the first argument as the name if so and a fallback if not.

A common early stumble is the trailingOnly = TRUE setting. Leave it out and R's own startup options are included too, so you cannot get just the arguments you meant.

In professional work, this extends to automation scripts for data analysis that branch on the values passed in at run time.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)